Ejemplo n.º 1
0
  @Test
  public void testMultipleActions() {

    final Conditional conditionalAction = new Conditional();
    conditionalAction.setExpression("1 = 1");

    final TestAction action1 = EasyMock.createMock(TestAction.class);
    final TestAction action2 = EasyMock.createMock(TestAction.class);
    final TestAction action3 = EasyMock.createMock(TestAction.class);

    reset(action1, action2, action3);

    action1.execute(this.context);
    expectLastCall().once();
    action2.execute(this.context);
    expectLastCall().once();
    action3.execute(this.context);
    expectLastCall().once();

    replay(action1, action2, action3);

    final List<TestAction> actionList = new ArrayList<TestAction>();
    actionList.add(action1);
    actionList.add(action2);
    actionList.add(action3);

    conditionalAction.setActions(actionList);

    conditionalAction.execute(this.context);

    verify(action1, action2, action3);
  }
Ejemplo n.º 2
0
  @Test(expectedExceptions = CitrusRuntimeException.class)
  public void testFailingAction() {

    final Conditional conditionalAction = new Conditional();
    conditionalAction.setExpression("1 = 1");

    final TestAction action1 = EasyMock.createMock(TestAction.class);
    final TestAction action2 = EasyMock.createMock(TestAction.class);
    final TestAction action3 = EasyMock.createMock(TestAction.class);

    reset(action1, action2, action3);

    action1.execute(this.context);
    expectLastCall().once();

    replay(action1, action2, action3);

    final List<TestAction> actionList = new ArrayList<TestAction>();
    actionList.add(action1);
    actionList.add(new FailAction());
    actionList.add(action2);
    actionList.add(action3);

    conditionalAction.setActions(actionList);

    conditionalAction.execute(this.context);

    verify(action1, action2, action3);
  }
Ejemplo n.º 3
0
 protected void prettyPrint(
     StringBuilder messageBuffer, MethodContext methodContext, String combineText) {
   messageBuffer.append("(");
   for (Conditional subCond : subConditions) {
     subCond.prettyPrint(messageBuffer, methodContext);
     messageBuffer.append(combineText);
   }
   messageBuffer.append(")");
 }
Ejemplo n.º 4
0
 /** @see jaskell.compiler.JaskellVisitor#visit(Conditional) */
 public Object visit(Conditional conditional) {
   Type iff = (Type) conditional.getIfFalse().visit(this);
   Type ift = (Type) conditional.getIfTrue().visit(this);
   Type tcond = (Type) conditional.getCondition().visit(this);
   tcond = tu.unify(tcond, Primitives.BOOL, typeVariablesMap);
   if (!(tcond.equals(Primitives.BOOL)))
     throw new TypeError("Conditional expression is not of type Bool : " + tcond);
   /* unify false and true parts */
   Type uni = tu.unify(iff, ift, typeVariablesMap);
   conditional.setType(uni);
   return uni;
 }
Ejemplo n.º 5
0
 /**
  * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String,
  *     java.lang.String)
  */
 public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
   if (inModification && charBuf.length() > 0) {
     final String normalized =
         preserveWhitespace
             ? charBuf.toString()
             : charBuf.getNormalizedString(FastStringBuffer.SUPPRESS_BOTH);
     if (normalized.length() > 0) {
       final Text text = doc.createTextNode(charBuf.toString());
       if (stack.isEmpty()) {
         contents.add(text);
       } else {
         final Element last = stack.peek();
         last.appendChild(text);
       }
     }
     charBuf.setLength(0);
   }
   if (XUPDATE_NS.equals(namespaceURI)) {
     if (IF.equals(localName)) {
       final Conditional cond = conditionals.pop();
       modifications.add(cond);
     } else if (localName.equals(ELEMENT)) {
       this.resetWhitespaceHandling(stack.pop());
     } else if (localName.equals(ATTRIBUTE)) {
       inAttribute = false;
     } else if (localName.equals(APPEND)
         || localName.equals(UPDATE)
         || localName.equals(REMOVE)
         || localName.equals(RENAME)
         || localName.equals(REPLACE)
         || localName.equals(INSERT_BEFORE)
         || localName.equals(INSERT_AFTER)) {
       inModification = false;
       modification.setContent(contents);
       modification.setAccessContext(accessCtx);
       if (!conditionals.isEmpty()) {
         final Conditional cond = conditionals.peek();
         cond.addModification(modification);
       } else {
         modifications.add(modification);
       }
       modification = null;
     }
   } else if (inModification) {
     this.resetWhitespaceHandling(stack.pop());
   }
 }
    @Override
    public ConstantValue visitConditional(Conditional expr, Void arg) {
      final ConstantValue conditionValue = expr.getCondition().accept(this, null);
      final ConstantType resultConstantType = typeFactory.newConstantType(expr.getType().get());
      final ConstantValue resultValue;

      if (conditionValue.logicalValue()) {
        resultValue =
            expr.getOnTrueExp().isPresent()
                ? expr.getOnTrueExp().get().accept(this, null)
                : conditionValue;
      } else {
        resultValue = expr.getOnFalseExp().accept(this, null);
      }

      return resultValue.castTo(resultConstantType);
    }
 @Override
 public HearthTreeNode applyEffect(
     PlayerSide targetSide, CharacterIndex targetCharacterIndex, HearthTreeNode boardState) {
   if (condition.isSatisfied(conditionForSide, boardState)) {
     return baseEffect.applyEffect(targetSide, targetCharacterIndex, boardState);
   } else {
     return boardState;
   }
 }
Ejemplo n.º 8
0
    @Override
    public void visit(ExpNode exp) throws ExpError {
      // Note: Below we are passing 'null' as an EvalContext, this is not typically
      // acceptable, but is 'safe enough' when we know the expression is a constant

      if (exp instanceof BinaryOp) {
        BinaryOp bo = (BinaryOp) exp;
        if (bo.lSubExp instanceof Constant) {
          // Just the left is a constant, store it in the binop
          bo.lConstVal = bo.lSubExp.evaluate(null);
        }
        if (bo.rSubExp instanceof Constant) {
          // Just the right is a constant, store it in the binop
          bo.rConstVal = bo.rSubExp.evaluate(null);
        }
      }
      if (exp instanceof Conditional) {
        Conditional cond = (Conditional) exp;
        if (cond.condExp instanceof Constant) {
          cond.constCondRes = cond.condExp.evaluate(null);
        }
        if (cond.trueExp instanceof Constant) {
          cond.constTrueRes = cond.trueExp.evaluate(null);
        }
        if (cond.falseExp instanceof Constant) {
          cond.constFalseRes = cond.falseExp.evaluate(null);
        }
      }
      if (exp instanceof FuncCall) {
        FuncCall fc = (FuncCall) exp;
        for (int i = 0; i < fc.args.size(); ++i) {
          if (fc.args.get(i) instanceof Constant) {
            fc.constResults.set(i, fc.args.get(i).evaluate(null));
          }
        }
      }
    }
Ejemplo n.º 9
0
  @Test(expectedExceptions = IllegalStateException.class)
  public void testConditionFalse() {

    final Conditional conditionalAction = new Conditional();
    conditionalAction.setExpression("1 = 0");

    final TestAction action = EasyMock.createMock(TestAction.class);

    reset(action);

    action.execute(this.context);
    expectLastCall().once();

    replay(action);

    final List<TestAction> actionList = new ArrayList<TestAction>();
    actionList.add(action);
    conditionalAction.setActions(actionList);

    conditionalAction.execute(this.context);

    // must throw IllegalStateException, as the action should never be called
    expectLastCall().once();
  }
Ejemplo n.º 10
0
  public void testBasicBeanOperations() {
    Conditional ix1 = new DefaultConditional("IXIC 2");

    Conditional ix2 = new DefaultConditional("IXIC 3");

    Assert.assertTrue("object not equals", !ix1.equals(ix2));
    Assert.assertTrue("object not equals reverse", !ix2.equals(ix1));

    Assert.assertTrue("hash not equals", ix1.hashCode() != ix2.hashCode());
  }
Ejemplo n.º 11
0
  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);
  }
Ejemplo n.º 12
0
  /**
   * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String,
   *     java.lang.String, org.xml.sax.Attributes)
   */
  public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
      throws SAXException {
    // save accumulated character content
    if (inModification && charBuf.length() > 0) {
      //            String normalized = charBuf.toString();
      final String normalized =
          preserveWhitespace
              ? charBuf.toString()
              : charBuf.getNormalizedString(FastStringBuffer.SUPPRESS_BOTH);

      if (normalized.length() > 0) {
        final Text text = doc.createTextNode(charBuf.toString());
        if (stack.isEmpty()) {
          // LOG.debug("appending text to fragment: " + text.getData());
          contents.add(text);
        } else {
          final Element last = stack.peek();
          last.appendChild(text);
        }
      }
      charBuf.setLength(0);
    }
    if (namespaceURI.equals(XUPDATE_NS)) {
      String select = null;
      if (localName.equals(MODIFICATIONS)) {
        startModifications(atts);
        return;
      } else if (localName.equals(VARIABLE)) {
        // variable declaration
        startVariableDecl(atts);
        return;
      } else if (IF.equals(localName)) {
        if (inModification) {
          throw new SAXException("xupdate:if is not allowed inside a modification");
        }
        select = atts.getValue("test");
        final Conditional cond =
            new Conditional(broker, documentSet, select, namespaces, variables);
        cond.setAccessContext(accessCtx);
        conditionals.push(cond);
        return;
      } else if (VALUE_OF.equals(localName)) {
        if (!inModification) {
          throw new SAXException("xupdate:value-of is not allowed outside a modification");
        }

      } else if (APPEND.equals(localName)
          || INSERT_BEFORE.equals(localName)
          || INSERT_AFTER.equals(localName)
          || REMOVE.equals(localName)
          || RENAME.equals(localName)
          || UPDATE.equals(localName)
          || REPLACE.equals(localName)) {
        if (inModification) {
          throw new SAXException("nested modifications are not allowed");
        }
        select = atts.getValue("select");
        if (select == null) {
          throw new SAXException(localName + " requires a select attribute");
        }
        doc = builder.newDocument();
        contents = new NodeListImpl();
        inModification = true;
      } else if ((ELEMENT.equals(localName)
          || ATTRIBUTE.equals(localName)
          || TEXT.equals(localName)
          || PROCESSING_INSTRUCTION.equals(localName)
          || COMMENT.equals(localName))) {
        if (!inModification) {
          throw new SAXException("creation elements are only allowed inside " + "a modification");
        }
        charBuf.setLength(0);
      } else {
        throw new SAXException("Unknown XUpdate element: " + qName);
      }

      // start a new modification section
      if (APPEND.equals(localName)) {
        final String child = atts.getValue("child");
        modification = new Append(broker, documentSet, select, child, namespaces, variables);
      } else if (UPDATE.equals(localName)) {
        modification = new Update(broker, documentSet, select, namespaces, variables);
      } else if (INSERT_BEFORE.equals(localName)) {
        modification =
            new Insert(broker, documentSet, select, Insert.INSERT_BEFORE, namespaces, variables);
      } else if (INSERT_AFTER.equals(localName)) {
        modification =
            new Insert(broker, documentSet, select, Insert.INSERT_AFTER, namespaces, variables);
      } else if (REMOVE.equals(localName)) {
        modification = new Remove(broker, documentSet, select, namespaces, variables);
      } else if (RENAME.equals(localName)) {
        modification = new Rename(broker, documentSet, select, namespaces, variables);
      } else if (REPLACE.equals(localName)) {
        modification = new Replace(broker, documentSet, select, namespaces, variables);
      }

      // process commands for node creation
      else if (ELEMENT.equals(localName)) {
        String name = atts.getValue("name");
        if (name == null) {
          throw new SAXException("element requires a name attribute");
        }
        final int p = name.indexOf(':');
        String namespace = null;
        String prefix = "";
        if (p != Constants.STRING_NOT_FOUND) {
          prefix = name.substring(0, p);
          if (name.length() == p + 1) {
            throw new SAXException("illegal prefix in qname: " + name);
          }
          name = name.substring(p + 1);
          namespace = atts.getValue("namespace");
          if (namespace == null) {
            namespace = (String) namespaces.get(prefix);
          }
          if (namespace == null) {
            throw new SAXException("no namespace defined for prefix " + prefix);
          }
        }
        Element elem;
        if (namespace != null && namespace.length() > 0) {
          elem = doc.createElementNS(namespace, name);
          elem.setPrefix(prefix);
        } else {
          elem = doc.createElement(name);
        }

        if (stack.isEmpty()) {
          contents.add(elem);
        } else {
          final Element last = stack.peek();
          last.appendChild(elem);
        }
        this.setWhitespaceHandling((Element) stack.push(elem));
      } else if (ATTRIBUTE.equals(localName)) {
        final String name = atts.getValue("name");
        if (name == null) {
          throw new SAXException("attribute requires a name attribute");
        }
        final int p = name.indexOf(':');
        String namespace = null;
        if (p != Constants.STRING_NOT_FOUND) {
          final String prefix = name.substring(0, p);
          if (name.length() == p + 1) {
            throw new SAXException("illegal prefix in qname: " + name);
          }
          namespace = atts.getValue("namespace");
          if (namespace == null) {
            namespace = (String) namespaces.get(prefix);
          }
          if (namespace == null) {
            throw new SAXException("no namespace defined for prefix " + prefix);
          }
        }
        Attr attrib =
            namespace != null && namespace.length() > 0
                ? doc.createAttributeNS(namespace, name)
                : doc.createAttribute(name);
        if (stack.isEmpty()) {
          for (int i = 0; i < contents.getLength(); i++) {
            final Node n = contents.item(i);
            String ns = n.getNamespaceURI();
            final String nname = ns == null ? n.getNodeName() : n.getLocalName();
            if (ns == null) {
              ns = "";
            }
            // check for duplicate attributes
            if (n.getNodeType() == Node.ATTRIBUTE_NODE
                && nname.equals(name)
                && ns.equals(namespace)) {
              throw new SAXException(
                  "The attribute " + attrib.getNodeName() + " cannot be specified twice");
            }
          }
          contents.add(attrib);
        } else {
          final Element last = (Element) stack.peek();
          if (namespace != null && last.hasAttributeNS(namespace, name)
              || namespace == null && last.hasAttribute(name)) {
            throw new SAXException(
                "The attribute "
                    + attrib.getNodeName()
                    + " cannot be specified "
                    + "twice on the same element");
          }
          if (namespace != null) {
            last.setAttributeNodeNS(attrib);
          } else {
            last.setAttributeNode(attrib);
          }
        }
        inAttribute = true;
        currentNode = attrib;

        // process value-of
      } else if (VALUE_OF.equals(localName)) {
        select = atts.getValue("select");
        if (select == null) {
          throw new SAXException("value-of requires a select attribute");
        }
        final Sequence seq = processQuery(select);
        if (LOG.isDebugEnabled()) {
          LOG.debug("Found " + seq.getItemCount() + " items for value-of");
        }
        Item item;
        try {
          for (final SequenceIterator i = seq.iterate(); i.hasNext(); ) {
            item = i.nextItem();
            if (Type.subTypeOf(item.getType(), Type.NODE)) {
              final Node node = NodeSetHelper.copyNode(doc, ((NodeValue) item).getNode());
              if (stack.isEmpty()) {
                contents.add(node);
              } else {
                final Element last = (Element) stack.peek();
                last.appendChild(node);
              }
            } else {
              final String value = item.getStringValue();
              characters(value.toCharArray(), 0, value.length());
            }
          }
        } catch (final XPathException e) {
          throw new SAXException(e.getMessage(), e);
        }
      }
    } else if (inModification) {
      final Element elem =
          namespaceURI != null && namespaceURI.length() > 0
              ? doc.createElementNS(namespaceURI, qName)
              : doc.createElement(qName);
      Attr a;
      for (int i = 0; i < atts.getLength(); i++) {
        final String name = atts.getQName(i);
        final String nsURI = atts.getURI(i);
        if (name.startsWith("xmlns")) {
          // Why are these showing up? They are supposed to be stripped out?
        } else {
          a = nsURI != null ? doc.createAttributeNS(nsURI, name) : doc.createAttribute(name);
          a.setValue(atts.getValue(i));
          if (nsURI != null) {
            elem.setAttributeNodeNS(a);
          } else {
            elem.setAttributeNode(a);
          }
        }
      }
      if (stack.isEmpty()) {
        contents.add(elem);
      } else {
        final Element last = (Element) stack.peek();
        last.appendChild(elem);
      }
      this.setWhitespaceHandling((Element) stack.push(elem));
    }
  }
Ejemplo n.º 13
0
 /*
  * (non-Javadoc)
  *
  * @see jaskell.compiler.JaskellVisitor#visit(jaskell.compiler.core.Conditional)
  */
 public Object visit(Conditional conditional) {
   conditional.setCondition((Expression) conditional.getCondition().visit(this));
   conditional.setIfFalse((Expression) conditional.getIfFalse().visit(this));
   conditional.setIfTrue((Expression) conditional.getIfTrue().visit(this));
   return conditional;
 }
  /** @inheritDoc */
  @Override
  public boolean enter() {
    if (log.isLoggable(PlatformLogger.Level.FINE)) {
      log.fine(
          "enter(): blockingEDT=" + keepBlockingEDT.get() + ", blockingCT=" + keepBlockingCT.get());
    }

    if (!keepBlockingEDT.compareAndSet(false, true)) {
      log.fine("The secondary loop is already running, aborting");
      return false;
    }

    final Runnable run =
        new Runnable() {
          public void run() {
            log.fine("Starting a new event pump");
            if (filter == null) {
              dispatchThread.pumpEvents(condition);
            } else {
              dispatchThread.pumpEventsForFilter(condition, filter);
            }
          }
        };

    // We have two mechanisms for blocking: if we're on the
    // dispatch thread, start a new event pump; if we're
    // on any other thread, call wait() on the treelock

    Thread currentThread = Thread.currentThread();
    if (currentThread == dispatchThread) {
      if (log.isLoggable(PlatformLogger.Level.FINEST)) {
        log.finest("On dispatch thread: " + dispatchThread);
      }
      if (interval != 0) {
        if (log.isLoggable(PlatformLogger.Level.FINEST)) {
          log.finest("scheduling the timer for " + interval + " ms");
        }
        timer.schedule(
            timerTask =
                new TimerTask() {
                  @Override
                  public void run() {
                    if (keepBlockingEDT.compareAndSet(true, false)) {
                      wakeupEDT();
                    }
                  }
                },
            interval);
      }
      // Dispose SequencedEvent we are dispatching on the the current
      // AppContext, to prevent us from hang - see 4531693 for details
      SequencedEvent currentSE =
          KeyboardFocusManager.getCurrentKeyboardFocusManager().getCurrentSequencedEvent();
      if (currentSE != null) {
        if (log.isLoggable(PlatformLogger.Level.FINE)) {
          log.fine("Dispose current SequencedEvent: " + currentSE);
        }
        currentSE.dispose();
      }
      // In case the exit() method is called before starting
      // new event pump it will post the waking event to EDT.
      // The event will be handled after the the new event pump
      // starts. Thus, the enter() method will not hang.
      //
      // Event pump should be privileged. See 6300270.
      AccessController.doPrivileged(
          new PrivilegedAction() {
            public Object run() {
              run.run();
              return null;
            }
          });
    } else {
      if (log.isLoggable(PlatformLogger.Level.FINEST)) {
        log.finest("On non-dispatch thread: " + currentThread);
      }
      synchronized (getTreeLock()) {
        if (filter != null) {
          dispatchThread.addEventFilter(filter);
        }
        try {
          EventQueue eq = dispatchThread.getEventQueue();
          eq.postEvent(new PeerEvent(this, run, PeerEvent.PRIORITY_EVENT));
          keepBlockingCT.set(true);
          if (interval > 0) {
            long currTime = System.currentTimeMillis();
            while (keepBlockingCT.get()
                && ((extCondition != null) ? extCondition.evaluate() : true)
                && (currTime + interval > System.currentTimeMillis())) {
              getTreeLock().wait(interval);
            }
          } else {
            while (keepBlockingCT.get()
                && ((extCondition != null) ? extCondition.evaluate() : true)) {
              getTreeLock().wait();
            }
          }
          if (log.isLoggable(PlatformLogger.Level.FINE)) {
            log.fine("waitDone " + keepBlockingEDT.get() + " " + keepBlockingCT.get());
          }
        } catch (InterruptedException e) {
          if (log.isLoggable(PlatformLogger.Level.FINE)) {
            log.fine("Exception caught while waiting: " + e);
          }
        } finally {
          if (filter != null) {
            dispatchThread.removeEventFilter(filter);
          }
        }
        // If the waiting process has been stopped because of the
        // time interval passed or an exception occurred, the state
        // should be changed
        keepBlockingEDT.set(false);
        keepBlockingCT.set(false);
      }
    }

    return true;
  }