Example #1
0
      @Override
      public boolean visit(MethodInvocation node) {
        String mName = node.getName().getFullyQualifiedName().toString();
        Expression e = node.getExpression();
        String typName = "";
        if (e instanceof StringLiteral) {
          typName = "string";
        } else if (e instanceof FieldAccess) {
          FieldAccess field = (FieldAccess) e;
          typName = field.getName().getFullyQualifiedName();
        } else if (e instanceof Name) {
          typName = ((Name) e).getFullyQualifiedName();
          if (varTypMap.containsKey(typName)) {
            typName = varTypMap.get(typName);
          }
        } else {
          if (e != null) {
            typName = e.toString();
            if (typName.contains(".")) typName = typName.substring(0, typName.indexOf('.', 0));
            if (varTypMap.containsKey(typName)) typName = varTypMap.get(typName);
          }
        }

        String key = typName + "->" + mName;
        if (freqRecord.containsKey(key)) {
          freqRecord.put(key, freqRecord.get(key) + 1);
        } else {
          freqRecord.put(key, 1);
        }
        return super.visit(node);
      }
 public void invoke(MethodInvocation invocation) throws Throwable {
   next.invoke(invocation);
   if (invocation.found() && invocation.getResult() != null) {
     invocation.setResult(
         convert(invocation.getGenericReturnType(), invocation.getResult(), mapping));
   }
 }
    private void jitMethodInvocation(
        MethodInvocation invocation, Class<?> currentClass, boolean firstInvocation) {
      Method method = invocation.getMethod();
      if (firstInvocation && (method == null || (method.getModifiers() & Modifier.STATIC) == 0)) {
        mv.visitVarInsn(ALOAD, 1);
      }

      if (method == null) {
        if (!firstInvocation) {
          mv.visitVarInsn(ALOAD, 1);
        }
        return;
      }

      if (!method.getDeclaringClass().isAssignableFrom(currentClass)
          && (method.getModifiers() & Modifier.STATIC) == 0) {
        cast(method.getDeclaringClass());
      }

      int argumentCounter = 0;
      for (Expression argument : invocation.getArguments()) {
        cast(jitExpression(argument), method.getParameterTypes()[argumentCounter++]);
      }

      invoke(method);
    }
    public Object invoke(Object target, Method method, Object[] params) throws Throwable {
      if (EQUALS_METHOD.equals(method)) {
        Object param = params[0];
        if (param == null || !Proxy.isProxyClass(param.getClass())) {
          return false;
        }
        InvocationHandler other = Proxy.getInvocationHandler(param);
        return equals(other);
      } else if (HASHCODE_METHOD.equals(method)) {
        return hashCode();
      }

      MethodInvocation invocation =
          new MethodInvocation(
              method.getName(),
              method.getReturnType(),
              method.getGenericReturnType(),
              method.getParameterTypes(),
              delegate,
              params);
      invoker.invoke(invocation);
      if (!invocation.found()) {
        String methodName =
            method.getDeclaringClass().getSimpleName() + "." + method.getName() + "()";
        throw Exceptions.unsupportedMethod(methodName);
      }
      return invocation.getResult();
    }
 public Method get(MethodInvocation invocation) {
   Class<?> owner = invocation.getDelegate().getClass();
   String name = invocation.getName();
   Class<?>[] parameterTypes = invocation.getParameterTypes();
   MethodInvocationKey key = new MethodInvocationKey(owner, name, parameterTypes);
   lock.readLock().lock();
   Optional<Method> cached = store.get(key);
   if (cached == null) {
     cacheMiss++;
     lock.readLock().unlock();
     lock.writeLock().lock();
     try {
       cached = store.get(key);
       if (cached == null) {
         cached = lookup(owner, name, parameterTypes);
         if (cacheMiss % 10 == 0) {
           removeDirtyEntries();
         }
         store.put(key, cached);
       }
       lock.readLock().lock();
     } finally {
       lock.writeLock().unlock();
     }
   } else {
     cacheHit++;
   }
   try {
     return cached.orNull();
   } finally {
     lock.readLock().unlock();
   }
 }
 private String getDisplayNameBottomUp(MethodInvocation invocation) {
   if (invocation.parent() == null || !(invocation.parent() instanceof MethodInvocation))
     return invocation.target().toString();
   else
     return getTestNameBottomUp((MethodInvocation) invocation.parent())
         + " "
         + invocation.target().toString();
 }
  public void testNotExcludedMethod() throws Exception {
    BeanInfo info = new BeanInfo(context, MyOtherDummyBean.class);

    Exchange exchange = new DefaultExchange(context);
    MyOtherDummyBean pojo = new MyOtherDummyBean();
    MethodInvocation mi = info.createInvocation(pojo, exchange);
    assertNotNull(mi);
    assertEquals("hello", mi.getMethod().getName());
  }
 @Override
 public void visitMethodInvocation(MethodInvocation methodInvocation) {
   for (ExpressionStatement statement : methodInvocation.getArguments()) {
     statement.accept(this);
   }
   for (FunctionInvocation invocation : methodInvocation.getAnonymousFunctionInvocations()) {
     invocation.accept(this);
   }
 }
 /**
  * Checks whether the given method was called with the arguments given in expectedParamValues.
  *
  * @param name method name
  * @param expectedParamValues parameter values
  * @return true if the method was called with these parameters, false otherwise
  */
 public boolean wasMethodCalled(String name, Object... expectedParamValues) {
   MethodInvocation expected = new MethodInvocation(name, expectedParamValues);
   for (MethodInvocation invocation : invocations) {
     if (invocation.equals(expected)) {
       return true;
     }
   }
   return false;
 }
    public void invoke(MethodInvocation invocation) throws Throwable {
      if (current.get() != null) {
        // Already invoking a method on the mix-in
        return;
      }

      if (instance == null) {
        instance = DirectInstantiator.INSTANCE.newInstance(mixInClass, proxy);
      }
      MethodInvocation beanInvocation =
          new MethodInvocation(
              invocation.getName(),
              invocation.getReturnType(),
              invocation.getGenericReturnType(),
              invocation.getParameterTypes(),
              instance,
              invocation.getParameters());
      current.set(beanInvocation);
      try {
        next.invoke(beanInvocation);
      } finally {
        current.set(null);
      }
      if (beanInvocation.found()) {
        invocation.setResult(beanInvocation.getResult());
      }
    }
Example #11
0
 public boolean execCheckFields() {
   MethodInvocation<Boolean> methodInvocation =
       new MethodInvocation<Boolean>() {
         @Override
         protected void callMethod(IFormExtension<? extends AbstractForm> next) {
           setReturnValue(next.execCheckFields(FormCheckFieldsChain.this));
         }
       };
   callChain(methodInvocation);
   return methodInvocation.getReturnValue();
 }
Example #12
0
 public AbstractFormData execCreateFormData() {
   MethodInvocation<AbstractFormData> methodInvocation =
       new MethodInvocation<AbstractFormData>() {
         @Override
         protected void callMethod(IFormExtension<? extends AbstractForm> next) {
           setReturnValue(next.execCreateFormData(FormCreateFormDataChain.this));
         }
       };
   callChain(methodInvocation);
   return methodInvocation.getReturnValue();
 }
    /**
     * Checks whether the given methods were called in the given order.
     *
     * @param methodInvocations methods that should have been called
     * @return true if the method with the given parameters was called, false otherwise
     */
    public boolean wereMethodsCalledInOrder(MethodInvocation... methodInvocations) {
      if (methodInvocations == null || methodInvocations.length == 0) return true;

      int i = 0;
      for (MethodInvocation invocation : invocations) {
        if (invocation.equals(methodInvocations[i])) {
          i++;
          if (i >= methodInvocations.length) return true;
        }
      }
      return false;
    }
 public IPage<?> execCreateChildPage(final ITableRow row) {
   MethodInvocation<IPage> methodInvocation =
       new MethodInvocation<IPage>() {
         @Override
         protected void callMethod(
             IPageWithTableExtension<
                     ? extends ITable, ? extends AbstractPageWithTable<? extends ITable>>
                 next) {
           setReturnValue(next.execCreateChildPage(PageWithTableCreateChildPageChain.this, row));
         }
       };
   callChain(methodInvocation, row);
   return methodInvocation.getReturnValue();
 }
    public void invoke(MethodInvocation invocation) throws Throwable {
      Method targetMethod = locateMethod(invocation);
      if (targetMethod == null) {
        return;
      }

      Object returnValue;
      try {
        returnValue = targetMethod.invoke(invocation.getDelegate(), invocation.getParameters());
      } catch (InvocationTargetException e) {
        throw e.getCause();
      }

      invocation.setResult(returnValue);
    }
Example #16
0
 @Override
 public void visitMethodInvocation(MethodInvocation methodInvocation) {
   incr();
   space();
   System.out.println(
       "Method invocation: "
           + methodInvocation.getName()
           + ", null safe? -> "
           + methodInvocation.isNullSafeGuarded());
   for (ExpressionStatement argument : methodInvocation.getArguments()) {
     argument.accept(this);
   }
   for (FunctionInvocation invocation : methodInvocation.getAnonymousFunctionInvocations()) {
     invocation.accept(this);
   }
   decr();
 }
 public void execFilterLookupResult(final ILookupCall<T> call, final List<ILookupRow<T>> result)
     throws ProcessingException {
   MethodInvocation<Object> methodInvocation =
       new MethodInvocation<Object>() {
         @Override
         protected void callMethod(
             IRadioButtonGroupExtension<T, ? extends AbstractRadioButtonGroup<T>> next)
             throws ProcessingException {
           next.execFilterLookupResult(
               RadioButtonGroupFilterLookupResultChain.this, call, result);
         }
       };
   callChain(methodInvocation, call, result);
   if (methodInvocation.getException() instanceof ProcessingException) {
     throw (ProcessingException) methodInvocation.getException();
   }
 }
 @Override
 @SuppressWarnings("unchecked")
 public boolean visit(MethodInvocation node) {
   if (this.lscMethodInvocation != null) {
     return false;
   }
   if (comparisonMethods.contains(node.getName().getIdentifier())) {
     List<Expression> arguments = (List<Expression>) node.arguments();
     if (arguments.size() == 1 && arguments.get(0).resolveConstantExpressionValue() != null) {
       this.lscMethodInvocation = node;
       this.stringLiteralExpression = arguments.get(0);
       this.stringVariableExpression = node.getExpression();
       return false;
     }
   }
   return true;
 }
 /*
  * @see ASTVisitor#visit(MethodInvocation)
  */
 @Override
 public boolean visit(MethodInvocation node) {
   if (node.getExpression() != null) {
     node.getExpression().accept(this);
     this.fBuffer.append("."); // $NON-NLS-1$
   }
   if (node.getAST().apiLevel() >= JLS3) {
     if (!node.typeArguments().isEmpty()) {
       this.fBuffer.append("<"); // $NON-NLS-1$
       for (Iterator<Type> it = node.typeArguments().iterator(); it.hasNext(); ) {
         Type t = it.next();
         t.accept(this);
         if (it.hasNext()) {
           this.fBuffer.append(","); // $NON-NLS-1$
         }
       }
       this.fBuffer.append(">"); // $NON-NLS-1$
     }
   }
   node.getName().accept(this);
   this.fBuffer.append("("); // $NON-NLS-1$
   for (Iterator<Expression> it = node.arguments().iterator(); it.hasNext(); ) {
     Expression e = it.next();
     e.accept(this);
     if (it.hasNext()) {
       this.fBuffer.append(","); // $NON-NLS-1$
     }
   }
   this.fBuffer.append(")"); // $NON-NLS-1$
   return false;
 }
Example #20
0
 public ITreeNode execResolveVirtualChildNode(final IVirtualTreeNode node)
     throws ProcessingException {
   MethodInvocation<ITreeNode> methodInvocation =
       new MethodInvocation<ITreeNode>() {
         @Override
         protected void callMethod(ITreeNodeExtension<? extends AbstractTreeNode> next)
             throws ProcessingException {
           setReturnValue(
               next.execResolveVirtualChildNode(
                   TreeNodeResolveVirtualChildNodeChain.this, node));
         }
       };
   callChain(methodInvocation, node);
   if (methodInvocation.getException() instanceof ProcessingException) {
     throw (ProcessingException) methodInvocation.getException();
   }
   return methodInvocation.getReturnValue();
 }
  private List<String> getTestNamesTopDown(MethodInvocation invocation) {
    List<String> results = new ArrayList<String>();
    List<AstNode> nodes = new ArrayList<AstNode>();
    nodes.add(invocation);

    while (nodes.size() > 0) {
      AstNode head = nodes.remove(0);
      if (head instanceof MethodInvocation) {
        MethodInvocation headInvocation = (MethodInvocation) head;
        if (headInvocation.name().equals("in")) {
          String testName = getTestNameBottomUp(headInvocation);
          if (testName != null) {
            results.add(testName);
          }
        } else nodes.addAll(0, Arrays.asList(headInvocation.children()));
      }
    }

    return results;
  }
  public Selection find(AstNode node) {
    Selection result = null;
    while (result == null) {
      if (node instanceof MethodInvocation) {
        MethodInvocation invocation = (MethodInvocation) node;
        String name = invocation.name();
        AstNode parent = invocation.parent();
        if (name.equals("in") && scopeSet.contains(parent.name())) {
          String testName = getTestNameBottomUp(invocation);
          result =
              testName != null
                  ? new Selection(invocation.className(), testName, new String[] {testName})
                  : null;
          if (testName == null) {
            if (node.parent() != null) {
              node = node.parent();
            } else break;
          }
        } else if (scopeSet.contains(name)) {
          String displayName = getDisplayNameBottomUp(invocation);
          List<String> testNames = getTestNamesTopDown(invocation);
          result =
              new Selection(
                  invocation.className(),
                  displayName,
                  testNames.toArray(new String[testNames.size()]));
        }
      }

      if (result == null) {
        if (node.parent() != null) node = node.parent();
        else break;
      }
    }
    return result;
  }
    public void invoke(MethodInvocation method) throws Throwable {
      if (method.isGetter()) {
        if (properties.containsKey(method.getName())) {
          method.setResult(properties.get(method.getName()));
          return;
        }
        if (unknown.contains(method.getName())) {
          return;
        }

        Object value;
        next.invoke(method);
        if (!method.found()) {
          unknown.add(method.getName());
          return;
        }
        value = method.getResult();
        properties.put(method.getName(), value);
        return;
      }

      next.invoke(method);
    }
    public void invoke(MethodInvocation invocation) throws Throwable {
      Matcher matcher = IS_SUPPORT_METHOD.matcher(invocation.getName());
      if (!matcher.matches()) {
        next.invoke(invocation);
        return;
      }

      String getterName = String.format("get%s", matcher.group(1));
      MethodInvocation getterInvocation =
          new MethodInvocation(
              getterName,
              invocation.getReturnType(),
              invocation.getGenericReturnType(),
              new Class[0],
              invocation.getDelegate(),
              EMPTY);
      next.invoke(getterInvocation);
      invocation.setResult(getterInvocation.found());
    }
Example #25
0
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    MethodInvocation mi = new ReflectiveMethodInvocation(target, method, args, interceptors);
    return mi.proceed();
  }
 public void invoke(MethodInvocation method) throws Throwable {
   for (int i = 0; !method.found() && i < invokers.length; i++) {
     MethodInvoker invoker = invokers[i];
     invoker.invoke(method);
   }
 }
 private String getTestNameBottomUp(MethodInvocation invocation) {
   String result = "";
   while (invocation != null) {
     MethodInvocation nameInvocation = invocation;
     if (invocation.target().name().equals("taggedAs")
         && invocation.target() instanceof MethodInvocation) {
       nameInvocation = (MethodInvocation) invocation.target();
     }
     if (!nameInvocation.target().canBePartOfTestName()
         || (!invocation.name().equals("in") && invocation.canBePartOfTestName())) return null;
     String targetText =
         (nameInvocation.name().equals("in") || nameInvocation.name().equals("taggedAs"))
             ? nameInvocation.target().toString()
             : (nameInvocation.target().toString() + " " + nameInvocation.name());
     result = targetText + " " + result;
     if (invocation.parent() != null && invocation.parent() instanceof MethodInvocation)
       invocation = (MethodInvocation) invocation.parent();
     else invocation = null;
   }
   return result.trim();
 }
  public void generate(String inputFileName) throws Exception {
    List<MetaClass> metaClasses = new ArrayList<>();
    List<LifeLine> lifeLines = new ArrayList<>();
    List<MethodInvocation> rootMessages = new ArrayList<>();
    MethodInvocation parentMessage = new MethodInvocation();
    GsonBuilder builder = new GsonBuilder();
    List<MethodInvocation> methodInvocations = new ArrayList<>();
    Package mainPackage = new Package();
    List<Guard> listOfGuards = new ArrayList<>();
    Map<Guard, Instruction> guardToCFMap = new HashMap<>();
    List<Instruction> combinedFragments = new ArrayList<Instruction>();
    List<Operation> operationsList = new ArrayList<>();

    builder.registerTypeAdapter(RefObject.class, new RefObjectJsonDeSerializer());
    Gson gson = builder.create();

    Element myTypes = gson.fromJson(new FileReader(inputFileName), Element.class);
    if (myTypes._type.equals("Project")) {
      List<Element> umlElements =
          myTypes
              .ownedElements
              .stream()
              .filter(f -> f._type.equals("UMLModel"))
              .collect(Collectors.toList());
      if (umlElements.size() > 0) { // There has be to atleast one UMLModel package
        Element element = umlElements.get(0);
        // package that the classes are supposed to be in
        mainPackage.setName(element.name);
        List<Element> umlPackages =
            element
                .ownedElements
                .stream()
                .filter(g -> g._type.equals("UMLPackage"))
                .collect(Collectors.toList());
        if (umlPackages.size()
            > 1) { // There has to be two packages- one for class one for behaviour
          Element classes = umlPackages.get(0);
          Element behaviour = umlPackages.get(1);
          // *--------------------------CLASSES-------------------------------*//
          // in the first pass, get all classes that are defined in the diagram
          // get details that can be directly inferred from the json like, fields and operations,
          // which do not refer to other classes
          for (Element umlClass : classes.getOwnedElements()) {
            MetaClass metaClass = new MetaClass(umlClass.name, umlClass._id);

            // check if class is interface or not because there is no distinction in json
            if (umlClass._type.equals("UMLClass")) {
              metaClass.setInterface(false);
            } else {
              metaClass.setInterface(true);
            }
            if (umlClass.operations != null) {
              metaClass.setOperations(umlClass.operations);
              operationsList.addAll(metaClass.operations);
            }
            if (umlClass.attributes != null) {
              metaClass.setFields(umlClass.attributes);
            }
            metaClasses.add(metaClass);
          }

          // in second pass, define associations and generalizations for these classes
          for (Element umlClass : classes.getOwnedElements()) {
            if (umlClass.ownedElements != null) {
              // find corresponding metaclass, then populate the secondary inferences
              List<MetaClass> correspondingMetaClassList =
                  metaClasses
                      .stream()
                      .filter(f -> f._id.equals(umlClass._id))
                      .collect(Collectors.toList());
              MetaClass correspondingMetaClass = correspondingMetaClassList.get(0);
              List<Element> umlAssociations =
                  umlClass
                      .ownedElements
                      .stream()
                      .filter(f -> f._type.equals("UMLAssociation"))
                      .collect(Collectors.toList());

              if (umlAssociations.size() > 0) {
                correspondingMetaClass.setAssociations(metaClasses, umlAssociations);
              }
              List<Element> umlGeneralization =
                  umlClass
                      .ownedElements
                      .stream()
                      .filter(f -> f._type.equals("UMLGeneralization"))
                      .collect(Collectors.toList());
              if (umlGeneralization.size() > 0) {
                correspondingMetaClass.setGeneralizations(metaClasses, umlGeneralization);
              }
              List<Element> umlRealization =
                  umlClass
                      .ownedElements
                      .stream()
                      .filter(f -> f._type.equals("UMLInterfaceRealization"))
                      .collect(Collectors.toList());
              if (umlRealization.size() > 0) {
                correspondingMetaClass.setInterfaceRealization(metaClasses, umlRealization);
              }
            }
          }

          // *--------------------------CLASSES-------------------------------*//

          // *-----------------------  BEHAVIOUR---------------------------------*//
          for (Element umlCollaboration : behaviour.getOwnedElements()) {
            // Role to Class mapping
            ArrayList<Element> attributes = umlCollaboration.attributes;
            HashMap<String, MetaClass> roleToClassMap = new HashMap<>();
            if (attributes != null) {
              for (Element attribute : attributes) {
                List<MetaClass> roleClass =
                    metaClasses
                        .stream()
                        .filter(f -> f._id.equals(attribute.type.$ref))
                        .collect(Collectors.toList());
                roleToClassMap.put(attribute._id, roleClass.get(0));
              }
            }

            for (Element umlInteraction : umlCollaboration.ownedElements) {

              // mapping lifelines to the classes they correspond
              ArrayList<Element> participants = umlInteraction.participants;
              if (participants != null && participants.size() > 0) {
                for (Element participant : participants) {
                  MetaClass participantClass = roleToClassMap.get(participant.represent.$ref);
                  LifeLine lifeLine = new LifeLine();
                  lifeLine.setName(participant.name);
                  lifeLine.setId(participant._id);
                  lifeLine.setMetaClass(participantClass);
                  lifeLines.add(lifeLine);
                }
              }
              // first parse all the combined fragments and get ready
              if (umlInteraction.fragments != null) {
                for (Element fragment :
                    umlInteraction.fragments) { // depending on the fragment set the class
                  Instruction instruction = null;
                  if (fragment.interactionOperator.equals("loop")) {
                    Loop loop = new Loop();
                    loop.setId(fragment._id);
                    loop.setWeight(0);
                    Guard guard = new Guard(fragment.operands.get(0)._id);
                    // loop can have only one condition--- one condition-- condition is made up of
                    // AND or OR's
                    guard.setCondition(fragment.operands.get(0).guard);
                    loop.setGuard(guard);
                    instruction = loop;
                    combinedFragments.add(loop);
                    listOfGuards.add(guard);
                    guardToCFMap.put(guard, loop);
                  }

                  if (fragment.interactionOperator.equals("alt")) {
                    Conditional c = new Conditional();
                    c.setId(fragment._id);
                    c.setWeight(0);
                    instruction = c;
                    combinedFragments.add(c);

                    Guard consequence = new Guard(fragment.operands.get(0)._id);
                    consequence.setCondition(fragment.operands.get(0).guard);
                    c.setCons(consequence);
                    listOfGuards.add(consequence);
                    guardToCFMap.put(consequence, c);
                    consequence.setConsequence(true);

                    if (fragment.operands.size() > 1) {
                      Guard alternate = new Guard(fragment.operands.get(1)._id);
                      alternate.setCondition(fragment.operands.get(1).guard);
                      c.setAlt(alternate);
                      listOfGuards.add(alternate);
                      guardToCFMap.put(alternate, c);
                      alternate.setAlternative(true);
                    }
                  }

                  if (fragment.tags != null) {
                    for (Element tag : fragment.tags) {
                      if (tag.name.equals("parent")) {
                        List<Instruction> instructionList =
                            combinedFragments
                                .stream()
                                .filter(e -> e.getId().equals(tag.reference.$ref))
                                .collect(Collectors.toList());
                        if (instructionList.size() > 0) {
                          instructionList.get(0).getBlock().add(instruction);
                          instruction.setParent(instructionList.get(0));
                        }
                      }
                    }
                  }
                }
              }

              // parsing the messages and make nodes out them to later build a tree from the
              // lifelines
              ArrayList<Element> messages = umlInteraction.messages;
              Element startMessage = messages.get(0);
              String sourceRef = startMessage.source.$ref;
              String targetRef = startMessage.target.$ref;
              Element endMessage = null;

              LifeLine sourceLifeLine = getLifeLine(lifeLines, sourceRef);
              LifeLine targetLifeLine = getLifeLine(lifeLines, targetRef);

              // First message processing
              parentMessage = new MethodInvocation();
              parentMessage.setAssignmentTarget(startMessage.assignmentTarget);
              parentMessage.setMessageSort(startMessage.messageSort);
              parentMessage.setSource(sourceLifeLine.getMetaClass());
              parentMessage.setTarget(targetLifeLine.getMetaClass());
              parentMessage.setName(startMessage.name);
              parentMessage.setId(startMessage._id);
              if (sourceLifeLine.getId().equals(targetLifeLine.getId())) {
                parentMessage.setCallerObject("this");
              } else {
                parentMessage.setCallerObject(targetLifeLine.getName());
              }
              int weight = 0;
              parentMessage.setWeight(weight++);
              if (startMessage.signature != null) {
                parentMessage.setSignature(startMessage.signature.$ref);
              }

              if (startMessage.tags != null) {
                for (Element tag : startMessage.tags) {
                  //                                    if (tag.name.equals("CF")) {
                  //                                        parentMessage.setInCF(true);
                  //
                  // parentMessage.setCfID(tag.reference.$ref);
                  //                                    }
                  if (tag.name.equals("operand")) {
                    parentMessage.setOperandId(tag.reference.$ref);
                  }
                }
              }

              MethodInvocation rootMessage = parentMessage;
              methodInvocations.add(rootMessage);
              rootMessages.add(rootMessage);
              Iterator<Element> iter = messages.iterator();
              while (iter.hasNext()) {
                if (iter.next() == endMessage) {
                  continue;
                }

                iter.remove();
                List<Element> childMessages = getChildMessages(messages, targetRef);
                for (Element child : childMessages) {

                  LifeLine childSource = getLifeLine(lifeLines, child.source.$ref);
                  LifeLine childTarget = getLifeLine(lifeLines, child.target.$ref);

                  MethodInvocation childMessage = new MethodInvocation();
                  childMessage.setMessageSort(child.messageSort);
                  childMessage.setSource(childSource.getMetaClass());
                  childMessage.setTarget(childTarget.getMetaClass());
                  childMessage.setAssignmentTarget(child.assignmentTarget);
                  childMessage.setName(child.name);
                  childMessage.setId(child._id);
                  childMessage.setWeight(weight++);
                  childMessage.setArguments(child.arguments);

                  if (childSource.getId().equals(childTarget.getId())) {
                    childMessage.setCallerObject("this");
                  } else {
                    childMessage.setCallerObject(childTarget.getName());
                  }

                  if (child.signature != null) {
                    childMessage.setSignature(child.signature.$ref);
                  }

                  if (child.tags != null) {
                    for (Element tag : child.tags) {
                      //                                            if (tag.name.equals("CF")) {
                      //                                                childMessage.setInCF(true);
                      //
                      // childMessage.setCfID(tag.reference.$ref);
                      //                                            }
                      if (tag.name.equals("operand")) {
                        childMessage.setOperandId(tag.reference.$ref);
                      }
                    }
                  }

                  parentMessage.childNodes.add(childMessage);
                  methodInvocations.add(childMessage);
                }

                if (childMessages.size() > 0) {
                  List<MethodInvocation> nextMessage =
                      parentMessage
                          .childNodes
                          .stream()
                          .filter(f -> !f.source.equals(f.target))
                          .collect(Collectors.toList());
                  List<Element> startMessageNext =
                      childMessages
                          .stream()
                          .filter(f -> !f.source.$ref.equals(f.target.$ref))
                          .collect(Collectors.toList());
                  startMessage = startMessageNext.get(0);
                  targetRef = startMessage.target.$ref;
                  sourceRef = startMessage.source.$ref;

                  parentMessage = nextMessage.get(0);

                  if (childMessages.size() > 1) {
                    endMessage = childMessages.get(childMessages.size() - 1);
                  }
                }
              }
            }

            for (MethodInvocation methodInvocation : methodInvocations) {
              List<Operation> matchingOperation =
                  operationsList
                      .stream()
                      .filter(f -> f._id.equals(methodInvocation.getSignature()))
                      .collect(Collectors.toList());
              if (matchingOperation.size() > 0) {
                operationMap.put(methodInvocation, matchingOperation.get(0)._id);
                methodInvocation.setOperation(matchingOperation.get(0));
              }
            }

            Stack stack = new Stack();
            for (MethodInvocation root : methodInvocations) {
              stack.push(root);
              while (!stack.empty()) {
                MethodInvocation methodInvocation = (MethodInvocation) stack.pop();
                Operation currentOperation = methodInvocation.getOperation();

                if (currentOperation != null) {
                  // all child nodes of this node make up its body
                  List<MethodInvocation> childNodes = methodInvocation.childNodes;
                  for (MethodInvocation child : childNodes) {
                    stack.push(child);
                  }
                  for (MethodInvocation childNode : childNodes) {
                    if (childNode.getOperandId() != null) {
                      List<Instruction> combinedFragmentsList =
                          combinedFragments
                              .stream()
                              .filter(f -> f.getId().equals(childNode.getCfID()))
                              .collect(Collectors.toList());

                      List<Guard> guardList =
                          listOfGuards
                              .stream()
                              .filter(f -> f.id.equals(childNode.getOperandId()))
                              .collect(Collectors.toList());

                      if (guardList.size() > 0) {
                        Guard currentGuard = guardList.get(0);
                        Instruction instruction = guardToCFMap.get(guardList.get(0));
                        // get the topmost CF if it is in a tree
                        Instruction parent = instruction.getParent();

                        while (instruction.getParent() != null) {
                          instruction = instruction.getParent();
                        }

                        if (currentGuard.isConsequence) {
                          Conditional conditional = (Conditional) instruction;
                          if (!conditional.getConsequence().contains(childNode)) {
                            conditional.getConsequence().add(childNode);
                          }
                        }
                        if (currentGuard.isAlternative) {
                          Conditional conditional = (Conditional) instruction;
                          if (!conditional.getAlternative().contains(childNode)) {
                            conditional.getAlternative().add(childNode);
                          }
                        }
                        if (!currentGuard.isAlternative && !currentGuard.isConsequence) {
                          Loop loop = (Loop) instruction;
                          loop.getBlock().add(childNode);
                        } else {
                          if (!currentOperation.getBlock().contains(instruction)) {
                            currentOperation.getBlock().add(instruction);
                          }
                        }
                      }
                    } else {
                      if (!currentOperation.getBlock().contains(childNode)) {
                        currentOperation.getBlock().add(childNode);
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    //
    ////        printAllData(metaClasses);
    //        while (parentMessage.childNodes != null || parentMessage.childNodes.size() > 0) {
    //            System.out.println("parent " + parentMessage.name);
    //            for (com.cbpro.main.MethodInvocation child : parentMessage.childNodes) {
    //                System.out.println("child " + child.name);
    //            }
    //            if (parentMessage.childNodes.size() > 0) {
    //                parentMessage = parentMessage.childNodes.get(0);
    //            } else {
    //                break;
    //            }
    //        }

    mainPackage.print();
    File dir = new File("/home/ramyashenoy/Desktop/DemoFolder/" + mainPackage.getName());

    boolean successful = dir.mkdir();
    if (successful) {
      System.out.println("directory was created successfully");
      for (MetaClass metaClass : metaClasses) {
        if (metaClass.name.equals("Main")) {
          continue;
        } else {
          String data = metaClass.print();
          BufferedWriter out = null;
          try {
            FileWriter fstream =
                new FileWriter(
                    dir.getPath() + "/" + metaClass.name + ".java",
                    true); // true tells to append data.
            out = new BufferedWriter(fstream);
            out.write(data);
          } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
          } finally {
            if (out != null) {
              out.close();
            }
          }
        }
      }
    } else {
      // creating the directory failed
      System.out.println("failed trying to create the directory");
    }

    mainPackage.setClasses(metaClasses);
  }
    public void invoke(MethodInvocation invocation) throws Throwable {
      next.invoke(invocation);
      if (invocation.found() || invocation.getParameterTypes().length != 1) {
        return;
      }

      if (!invocation.isIsOrGet()) {
        return;
      }

      MethodInvocation getterInvocation =
          new MethodInvocation(
              invocation.getName(),
              invocation.getReturnType(),
              invocation.getGenericReturnType(),
              EMPTY_CLASS_ARRAY,
              invocation.getDelegate(),
              EMPTY);
      next.invoke(getterInvocation);
      if (getterInvocation.found() && getterInvocation.getResult() != null) {
        invocation.setResult(getterInvocation.getResult());
      } else {
        invocation.setResult(invocation.getParameters()[0]);
      }
    }
 /**
  * Checks whether the given method was called - allows distinguishing between overloads by
  * specifying the parameter types.
  *
  * @param name method name
  * @param paramTypes method parameters
  * @return true if the method with the given parameters was called, false otherwise
  */
 public boolean wasMethodCalled(String name, Class<?>... paramTypes) {
   for (MethodInvocation invocation : invocations) {
     if (invocation.method.equals(name) && invocation.paramTypesMatch(paramTypes)) return true;
   }
   return false;
 }