Пример #1
0
  public void test_undefine_operation_152018() {
    helper.setContext(getMetaclass("Classifier"));

    Operation operation = null;

    try {
      // define some additional property
      operation =
          helper.defineOperation(
              "other(x : Integer) : Classifier = "
                  + "if general->size() >= x then general->asSequence()->at(x) else null endif");
    } catch (Exception e) {
      fail("Failed to parse: " + e.getLocalizedMessage());
    }

    assertNotNull(operation);

    // now, undefine this operation
    ocl.getEnvironment().undefine(operation);

    assertNull(operation.eContainer());
    assertNull(operation.eResource());

    try {
      // try to define this property again.  We should succeed
      operation =
          helper.defineOperation(
              "other(x : Integer) : Classifier = "
                  + "if general->size() >= x then general->asSequence()->at(x) else null endif");
    } catch (Exception e) {
      fail("Failed to parse: " + e.getLocalizedMessage());
    }
  }
 /** {@inheritDoc} */
 public String getEditString(final IAdaptable element, int flags) {
   if (element instanceof EObjectAdapter) {
     final Operation operation = ((Operation) ((EObjectAdapter) element).getRealObject());
     return operation.getName();
   }
   return "";
 }
  /**
   * Bind an operation by copying the signature from the actual.
   *
   * @param copy the copier
   * @param actual the actual. If an operation, its signature is copied to the template
   * @param operation The operation template
   * @return
   */
  public static Operation instantiateOperation(
      LazyCopier copy, Element actual, Operation operation) {
    try {
      Operation newOperation = copy.getCopy(operation);
      if (actual instanceof Operation) {
        for (Parameter parameter : ((Operation) actual).getOwnedParameters()) {
          Parameter newParam = EcoreUtil.copy(parameter); // copy parameter via EcoreUtil
          newParam.setType(copy.getCopy(parameter.getType()));
          newOperation.getOwnedParameters().add(newParam);
        }
      }
      TransformationContext.classifier = newOperation.getClass_();
      if (actual instanceof Classifier) {
        bindOperation(newOperation, (Classifier) actual);
      }
      String newName = AcceleoDriverWrapper.evaluate(operation.getName(), actual, null);
      newOperation.setName(newName);

      return newOperation;
    } catch (TransformationException e) {
      // throw runtime exception
      throw new RuntimeException(
          String.format(Messages.TemplateInstantiationListener_TrafoException, e.getMessage()));
    }
  }
  /**
   * Checks if a transition is one of the operations of its containing class. Pending: it only
   * checks against its name and not its entire signature.
   */
  public boolean isTransitionInClass(String transitionName, Class transitionClass) {

    // checks if the transition class is not empty. E.g. a feature that does not define that class
    if (transitionClass == null) return false;

    // Checks the operations looking for a name
    for (Operation operation : transitionClass.getOperations()) {
      if (operation.getName().equals(transitionName)) return true;
    }
    return false;
  }
Пример #5
0
 /**
  * Returns operation modifiers as string, separated with comma.
  *
  * @return a string containing the modifiers
  */
 private static String getModifiersAsString(Operation operation) {
   StringBuffer buffer = new StringBuffer();
   boolean needsComma = false;
   // Return parameter modifiers
   Parameter returnParameter = OperationUtil.getReturnParameter(operation);
   if (returnParameter != null) {
     // non unique parameter
     if (!returnParameter.isUnique()) {
       buffer.append("nonunique");
       needsComma = true;
     }
     // return parameter has ordered values
     if (returnParameter.isOrdered()) {
       if (needsComma) {
         buffer.append(", ");
       }
       buffer.append("ordered");
       needsComma = true;
     }
   }
   // is the operation a query ?
   if (operation.isQuery()) {
     if (needsComma) {
       buffer.append(", ");
     }
     buffer.append("query");
     needsComma = true;
   }
   // is the operation redefining another operation ?
   Iterator<Operation> it = operation.getRedefinedOperations().iterator();
   while (it.hasNext()) {
     Operation currentOperation = it.next();
     if (needsComma) {
       buffer.append(", ");
     }
     buffer.append("redefines ");
     buffer.append(currentOperation.getName());
     needsComma = true;
   }
   // has the operation a constraint ?
   Iterator<Constraint> it2 = operation.getOwnedRules().iterator();
   while (it2.hasNext()) {
     Constraint constraint = it2.next();
     if (needsComma) {
       buffer.append(", ");
     }
     if (constraint.getSpecification() != null) {
       buffer.append(constraint.getSpecification().stringValue());
     }
     needsComma = true;
   }
   return buffer.toString();
 }
Пример #6
0
 public Operation createOwnedPrimitiveOperation(
     PrimitiveType aPrimitiveType,
     String name,
     EList<String> paramNames,
     EList<Type> paramTypes,
     Type type,
     boolean isQuery) {
   Operation operation = aPrimitiveType.createOwnedOperation(name, paramNames, paramTypes, type);
   if (isQuery) {
     operation.setIsQuery(true);
   }
   return operation;
 }
Пример #7
0
 public Operation createOwnedOperation(
     Class aClass,
     String name,
     EList<String> paramNames,
     EList<Type> paramTypes,
     Type type,
     boolean isQuery) {
   Operation operation = aClass.createOwnedOperation(name, paramNames, paramTypes, type);
   if (isQuery) {
     operation.setIsQuery(true);
   }
   return operation;
 }
Пример #8
0
 public static String getCustomLabel(
     Message message, Operation operation, Collection<String> displayValue) {
   StringBuffer buffer = new StringBuffer();
   buffer.append(" "); // adds " " first for correct display considerations
   // visibility
   if (displayValue.contains(ICustomAppearance.DISP_VISIBILITY)) {
     buffer.append(NamedElementUtil.getVisibilityAsSign(operation));
   }
   // name
   if (displayValue.contains(ICustomAppearance.DISP_NAME)) {
     buffer.append(" ");
     buffer.append(StringHelper.trimToEmpty(operation.getName()));
   }
   //
   // parameters : '(' parameter-list ')'
   buffer.append("(");
   buffer.append(getParametersAsString(message, operation, displayValue));
   buffer.append(")");
   // return type
   if (displayValue.contains(ICustomAppearance.DISP_RT_TYPE)
       || displayValue.contains(ICustomAppearance.DISP_TYPE)) {
     buffer.append(getReturnTypeAsString(operation, displayValue));
   }
   // modifiers
   if (displayValue.contains(ICustomAppearance.DISP_MODIFIERS)) {
     String modifiers = getModifiersAsString(operation);
     if (!modifiers.equals("")) {
       buffer.append("{");
       buffer.append(modifiers);
       buffer.append("}");
     }
   }
   return buffer.toString();
 }
Пример #9
0
 protected static void addOcl() {
   Operation find =
       example
           .getConstructionCase()
           .createOwnedOperation(
               "findRoomPlan", list("nameToFind"), list((Type) example.getType("String")));
   Parameter result = find.createOwnedParameter("result", example.getRoomPlans());
   result.setDirection(ParameterDirectionKind.RETURN_LITERAL);
   result.setUpper(-1);
   result.setIsUnique(false);
   OpaqueExpression ocl =
       (OpaqueExpression)
           find.createBodyCondition("body")
               .createSpecification(
                   "spec", example.getRoomPlans(), UMLPackage.eINSTANCE.getOpaqueExpression());
   ocl.getLanguages().add("ocl");
   ocl.getBodies().add("housePlan.wallPlans->collect(roomPlans->any(rp|rp.name=nameToFind))");
 }
Пример #10
0
 /**
  * Gives the return parameter for this operation, or <code>null</code> if none exists.
  *
  * @return the return parameter of the operation or <code>null</code>
  */
 private static Parameter getReturnParameter(Operation operation) {
   // Retrieve the return parameter (assume to be unique if defined)
   Parameter returnParameter = null;
   Iterator<Parameter> it = operation.getOwnedParameters().iterator();
   while ((returnParameter == null) && (it.hasNext())) {
     Parameter parameter = it.next();
     if (parameter.getDirection().equals(ParameterDirectionKind.RETURN_LITERAL)) {
       returnParameter = parameter;
     }
   }
   return returnParameter;
 }
Пример #11
0
  /** Tests that unrecognized data types are represented by themselves, not by OclAny. */
  public void test_dataTypes_137158() {
    Package upackage = umlf.createPackage();
    upackage.setName("mypkg");
    Class uclass = upackage.createOwnedClass("B", false);
    DataType datatype = (DataType) pkg.createOwnedType("Thread", uml.getDataType());
    Operation operation = uclass.createOwnedOperation("f", null, null, datatype);
    operation.setIsQuery(true);

    helper.setContext(uclass);

    try {
      OCLExpression<Classifier> expr = helper.createQuery("self.f()");

      Classifier type = expr.getType();
      assertSame(datatype, type);

      operation.setUpper(LiteralUnlimitedNatural.UNLIMITED);

      expr = helper.createQuery("self.f()");

      type = expr.getType();
      assertTrue(type instanceof CollectionType<?, ?>);
      type = ((org.eclipse.ocl.uml.CollectionType) type).getElementType();
      assertSame(datatype, type);

      operation.setUpper(1);
      operation.setType(ocl.getEnvironment().getOCLStandardLibrary().getOclAny());

      expr = helper.createQuery("self.f()");

      type = expr.getType();
      assertSame(getOCLStandardLibrary().getOclAny(), type);
    } catch (Exception e) {
      fail("Failed to parse or evaluate: " + e.getLocalizedMessage());
    }
  }
Пример #12
0
 public static boolean isMatch(
     IRepository repository,
     Operation operation,
     List<TypedElement> arguments,
     ParameterSubstitutionMap substitutions) {
   if (arguments == null) return true;
   List<Parameter> operationParameters =
       filterParameters(operation.getOwnedParameters(), ParameterDirectionKind.IN_LITERAL);
   if (arguments.size() != operationParameters.size()) return false;
   for (Iterator<?> argIter = arguments.iterator(), parIter = operationParameters.iterator();
       argIter.hasNext(); ) {
     Parameter parameter = (Parameter) parIter.next();
     TypedElement argument = (TypedElement) argIter.next();
     if (!TypeUtils.isCompatible(repository, argument, parameter, substitutions)) return false;
   }
   return true;
 }
Пример #13
0
 /**
  * Returns operation parameters as a string, the label is customized using a bit mask
  *
  * @param e
  * @return a string containing all parameters separated by commas
  */
 private static String getParametersAsString(
     Message e, Operation operation, Collection<String> displayValue) {
   StringBuffer paramString = new StringBuffer();
   Iterator<Parameter> paramIterator = operation.getOwnedParameters().iterator();
   boolean firstParameter = true;
   int paramIndex = 0;
   while (paramIterator.hasNext()) {
     Parameter parameter = paramIterator.next();
     // Do not include return parameters
     if (!parameter.getDirection().equals(ParameterDirectionKind.RETURN_LITERAL)) {
       // get the label for this parameter
       String parameterString = getCustomLabel(e, paramIndex, parameter, displayValue).trim();
       paramIndex++;
       if (!parameterString.equals("")) {
         if (!firstParameter) {
           paramString.append(", ");
         }
         paramString.append(parameterString);
         firstParameter = false;
       }
     }
   }
   return paramString.toString();
 }
 @VisitBefore(matchSubclasses = true)
 public void visitActivity(Activity activity) {
   if (EmfBehaviorUtil.isProcess(activity)) {
     OJAnnotatedClass activityClass = findJavaClass(activity);
     super.implementEventConsumption(activityClass, activity, getEventActions(activity));
     for (ActivityNode n : EmfActivityUtil.getActivityNodesRecursively(activity)) {
       if (n instanceof AcceptCallAction) {
         AcceptCallAction acc = (AcceptCallAction) n;
         Operation no = EmfActionUtil.getOperation(acc);
         OperationMap map = ojUtil.buildOperationMap(no);
         OJAnnotatedOperation oper =
             operationAnnotator.findOrCreateOperation(activity, activityClass, map, true);
         OJBlock mainBlock = oper.getBody();
         if (EmfBehaviorUtil.hasExecutionInstance(no)) {
           PropertyMap actionMap = ojUtil.buildStructuralFeatureMap(acc);
           final String EXECUTE_STATEMENT = "executeStatement";
           oper.getBody()
               .removeFromStatements(oper.getBody().findStatementRecursive(EXECUTE_STATEMENT));
           mainBlock.addToStatements(actionMap.setter() + "(result)");
         } else {
           for (OutputPin pin : acc.getResults()) {
             PropertyMap pinMap = ojUtil.buildStructuralFeatureMap(pin);
             PropertyMap parameterMap =
                 ojUtil.buildStructuralFeatureMap(EmfActionUtil.getLinkedTypedElement(pin));
             mainBlock.addToStatements(pinMap.setter() + "(" + parameterMap.fieldname() + ")");
           }
         }
         if (!EmfBehaviorUtil.hasExecutionInstance(no)) {
           for (InputPin pin : EmfActionUtil.getReplyAction(acc).getReplyValues()) {
             if (((Parameter) EmfActionUtil.getLinkedTypedElement(pin)).getDirection()
                 == ParameterDirectionKind.RETURN_LITERAL) {
               Jbpm5ObjectNodeExpressor expressor = new Jbpm5ObjectNodeExpressor(ojUtil);
               mainBlock.addToStatements(
                   "result=" + expressor.expressInputPinOrOutParamOrExpansionNode(mainBlock, pin));
             }
           }
         }
         if (!activity.conformsTo((Classifier) no.getOwner())
             && activity.getContext() != null
             && activity.getContext().conformsTo((Classifier) no.getOwner())) {
           // TODO find the right activity and delegate to it
         }
       } else if (EmfActionUtil.isEmbeddedTask(n)) {
         Action t = (Action) n;
         String stereotypeName =
             n instanceof OpaqueAction
                 ? StereotypeNames.EMBEDDED_SINGLE_SCREEN_TASK
                 : StereotypeNames.EMBEDDED_SCREEN_FLOW_TASK;
         for (TimeEvent d :
             getLibrary().getResponsibilityDefinition(t, stereotypeName).getDeadlines()) {
           OJPathName date = ojUtil.classifierPathname(getLibrary().getDateType());
           OJPathName task = ojUtil.classifierPathname(t);
           String consumerName = eventUtil.getEventConsumerName(d);
           OJOperation findOperation =
               activityClass.findOperation(consumerName, Arrays.asList(date, task));
           if (findOperation == null) {
             findOperation = new OJAnnotatedOperation(consumerName, new OJPathName("boolean"));
             activityClass.addToOperations(findOperation);
             findOperation.addParam("date", date);
             findOperation.addParam("task", task);
             findOperation.getBody().addToStatements("return false");
           }
         }
       }
     }
   }
 }
Пример #15
0
  public static TransitionDetails transitionDetails(Transition trans) {
    String condition = "";
    TransitionDetails transition = new TransitionDetails();

    /// ****** guard condition ***********************
    EList<Constraint> ownedRules = trans.getOwnedRules();
    com.mbe.umlce.dataobjects.stateMachine.Guard guard =
        new com.mbe.umlce.dataobjects.stateMachine.Guard();
    for (Constraint Rule : ownedRules) {

      ValueSpecification Specifications = Rule.getSpecification();
      guard.setName(Rule.getLabel());
      OpaqueExpression expr = (OpaqueExpression) Specifications;

      condition += expr.getBodies().toString();
      guard.setBody(removeSquareBrackets(condition));
      // condition = expr.getLanguages();
      //	System.out.println("Condition : "+condition);
    }
    transition.setGuard(guard);

    Effect effect = new Effect();
    String methodBody = null;
    if ((OpaqueBehavior) trans.getEffect() != null) {
      methodBody = "";
      effect.setName(trans.getEffect().getLabel());
      // methodBody += ("\nif ( "+removeSquareBrackets(condition)+" ){\n");
      methodBody +=
          removeSquareBrackets(((OpaqueBehavior) trans.getEffect()).getBodies().toString());
      // System.out.println("Effect : "+methodBody);
      effect.setBody(methodBody);
    }

    // Trigger yet to read//

    //
    transition.setEffect(effect);
    /*		TimeEvent timeEvent=null;
    		ChangeEvent changeEvent = null;
    */
    // Triggers reading
    CallEvent callEvent = null;
    Operation operation = null;
    EList<Trigger> trigger = trans.getTriggers();
    com.mbe.umlce.dataobjects.stateMachine.Trigger trig =
        new com.mbe.umlce.dataobjects.stateMachine.Trigger();
    for (Trigger triger : trigger) {
      // System.out.println("Triger : "+triger.getQualifiedName());
      // if(triger.getEvent().getName().contains("CallEvent")){
      callEvent = (CallEvent) (triger.getEvent());
      operation = callEvent.getOperation();

      if (operation != null) {

        // System.out.println("Operation : "+operation.getLabel());
        EList<Parameter> parameters = operation.getOwnedParameters();
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> paramClass = new ArrayList<>();

        for (Parameter pm : parameters) {
          param.add(pm.getLabel());
          paramClass.add(pm.getClass().getName());
          // System.out.println("Parameters : "+pm.getLabel());
        }
        trig.setOpName(operation.getLabel());
        trig.setOpParameters(param);
        trig.setParametersClass(paramClass);
      }
    }
    transition.setTrigger(trig);
    // }
    return transition;
  }
Пример #16
0
 public void setOperationUpper(Operation anOperation, int value) {
   anOperation.setUpper(value);
 }
Пример #17
0
 public void setIsQuery(Operation anOperation, boolean isQuery) {
   anOperation.setIsQuery(isQuery);
 }
Пример #18
0
 public Classifier getOwner(Operation context) {
   return (Classifier) context.getOwner();
 }
  /**
   * 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();
  }