Example #1
0
    @Override
    public boolean isEqualTo(Node o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        return true;
    }
Example #2
0
 /**
  * Gets a node in this result that is an instance of the specified class. The node returned is the
  * last node in the list (ordered parent to child) of nodes in this pick result that is an
  * instance of the specified class. If no such node exists, this method returns null.
  *
  * @return the node; null, if none.
  */
 public Node getNode(Class<?> nodeClass) {
   for (int i = _nodes.length - 1; i >= 0; --i) {
     Node node = _nodes[i];
     if (nodeClass.isAssignableFrom(node.getClass())) return node;
   }
   return null;
 }
  public void process(int depth, Node node) {
    if (depth == 0) {
      references.traverse(node);
    }

    Processor processor = processors().get(node.getClass());
    if (processor == null) {
      log.warn("No processor defined for type {}", node.getClass());
      processor = processorDefault;
    }

    treeNavigation.push(node);

    dumpProcessor(depth, node, processor);
    processor.process(depth, node, this);

    treeNavigation.pop();
  }
Example #4
0
 /**
  * Allocate a new node
  *
  * @return
  */
 @SuppressWarnings({"unchecked"})
 protected Node newNode() {
   try {
     Node u = (Node) sampleNode.getClass().newInstance();
     u.parent = u.child[0] = u.child[1] = null;
     return u;
   } catch (Exception e) {
     return null;
   }
 }
Example #5
0
  public void testBasicNode() {
    Node node;

    node = new Node("n");
    assertEquals("node-", node.getClass().getSimpleName().compareTo("Node"), 0);
    assertEquals("name_", node.name_, "n");
    assertEquals("nextNode_", node.nextNode_, null);
    node.nextNode_ = node;
    assertEquals("nextNode_ (after setting)", node.nextNode_, node);
  }
Example #6
0
 public static boolean isValueNode(Node node) {
   Class nodeClass = node.getClass();
   return nodeClass == Node.class
       || nodeClass == ApplicationNode.class
       || nodeClass == ArrayNode.class
       || node instanceof PrimitiveNode
       || nodeClass == XMLNode.class
       || nodeClass == XMLListNode.class
       || nodeClass == ModelNode.class
       || nodeClass == InlineComponentNode.class;
 }
Example #7
0
 /**
  * Determines if the object is a Literal or Resource and returns an iTQL representation.
  *
  * <p>Throws an Exception if the ObjectNode is a BlankNode
  *
  * @param node ObjectNode
  * @return String
  */
 protected String asString(Node node) {
   if (node == null) {
     throw new IllegalArgumentException("Node is null");
   }
   // determine type and convert to String
   if (node instanceof URIReference) {
     return " <" + ((URIReference) node).getURI() + ">";
   } else if (node instanceof Literal) {
     return " '" + escape(((Literal) node).getLexicalForm()) + "'";
   } else {
     // probably a BlankNode
     throw new IllegalArgumentException("Unsupported Node type: " + node.getClass().getName());
   }
 }
 @Override
 public String toString() {
   if (problemNode == null && getMessage() == null) return "ResolutionException (unknown cause)";
   if (problemNode == null) return "AstException: " + getMessage();
   String nodeDescription =
       problemNode == null ? "(null)" : (problemNode.getClass().getName() + "(toString failed)");
   try {
     nodeDescription = problemNode.toString();
   } catch (Throwable ignore) {
     // throwing exceptions in toString() is bad.
   }
   if (getMessage() == null) return "ResolutionException at " + nodeDescription;
   return String.format("ResolutionException: %s (at %s)", getMessage(), nodeDescription);
 }
Example #9
0
 @Override
 public boolean jjtCompareTo(Node node) {
   boolean result;
   ASTObjectList simpleNode = null;
   if (this.getClass() == node.getClass()) {
     simpleNode = (ASTObjectList) node;
     if (this.jjtGetNumChildren() == simpleNode.jjtGetNumChildren()) {
       if (this.jjtGetNumChildren() != 0) {
         for (int i = 0; i < this.jjtGetNumChildren(); i++) {
           result = this.jjtGetChild(i).jjtCompareTo(simpleNode.jjtGetChild(i));
           if (result) {
             continue;
           } else return false;
         }
         return true;
       } else return true;
     } else return false;
   } else return false;
 }
 private Node replaceNormalNode(
     Node normalNode, GKInstance diseaseEntity, Boolean needDashedBorder) {
   Node diseaseNode = normalToDiseaseNode.get(normalNode);
   if (diseaseNode != null) return diseaseNode;
   try {
     // If a node exists already, it should use
     for (Renderable r : diseaseComps) {
       if (diseaseEntity.getDBID().equals(r.getReactomeId()) && r instanceof Node) {
         // This is rather arbitrary: if two nodes are very close,
         // use the existing one.
         int dx = Math.abs(r.getPosition().x - normalNode.getPosition().x);
         int dy = Math.abs(r.getPosition().y - normalNode.getPosition().y);
         if (dx < 10 && dy < 10) {
           // We don't need to create a new Node if it exists already
           normalToDiseaseNode.put(normalNode, (Node) r);
           overlaidObjects.add(r); // Add it to overlaid object to cover edges
           return (Node) r;
         }
       }
     }
     diseaseNode = normalNode.getClass().newInstance();
     RenderUtility.copyRenderInfo(normalNode, diseaseNode);
     // The following should NOT be called since NodeAttachment is
     // related to disease entity only.
     // TODO: Need to support this. Currently it is not supported!!! See example
     // in PI3/AKT cancer pathway.
     // diseaseNode.setNodeAttachmentsLocally(node.getNodeAttachments());
     diseaseNode.setDisplayName(diseaseEntity.getDisplayName());
     diseaseNode.setReactomeId(diseaseEntity.getDBID());
     diseaseNode.invalidateBounds();
     diseaseNode.setRenderer(normalNode.getRenderer());
     diseaseNode.setLineColor(DefaultRenderConstants.DEFAULT_DISEASE_BACKGROUND);
     diseaseNode.setNeedDashedBorder(needDashedBorder);
     RenderUtility.hideCompartmentInNodeName(diseaseNode);
     overlaidObjects.add(diseaseNode);
     displayedObject.addComponent(diseaseNode);
     normalToDiseaseNode.put(normalNode, diseaseNode);
     return diseaseNode;
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
Example #11
0
  public void invoke(Node node) {
    Class nodeClass = node.getClass();

    if (nodeClass == Node.class || nodeClass == ApplicationNode.class) {
      componentNode(node);
    } else if (nodeClass == ArrayNode.class) {
      arrayNode((ArrayNode) node);
    } else if (node instanceof PrimitiveNode) {
      primitiveNode((PrimitiveNode) node);
    } else if (nodeClass == XMLNode.class) {
      xmlNode((XMLNode) node);
    } else if (nodeClass == XMLListNode.class) {
      xmlListNode((XMLListNode) node);
    } else if (nodeClass == ModelNode.class) {
      modelNode((ModelNode) node);
    } else if (nodeClass == InlineComponentNode.class) {
      inlineComponentNode((InlineComponentNode) node);
    } else {
      assert !isValueNode(node) : "value node class not handled by invoke()";
      unknown(node);
    }
  }
Example #12
0
  /**
   * Resolve a constraint against an RDF/XML document.
   *
   * <p>Resolution is by filtration of a URL stream, and thus very slow.
   */
  public Resolution resolve(Constraint constraint) throws QueryException {
    if (logger.isDebugEnabled()) {
      logger.debug("Resolve " + constraint);
    }

    // Validate "constraint" parameter
    if (constraint == null) {
      throw new IllegalArgumentException("Null \"constraint\" parameter");
    }

    if (!(constraint.getModel() instanceof LocalNode)) {
      if (logger.isDebugEnabled()) logger.debug("Ignoring solutions for " + constraint);
      return new EmptyResolution(constraint, false);
    }

    if (!(constraint.getElement(1) instanceof LocalNode)
        || !(constraint.getElement(2) instanceof LocalNode)) {
      throw new QueryException(
          "Prefix resolver can only be used for fixed prefixes: " + constraint);
    }

    try {

      long property = ((LocalNode) constraint.getElement(1)).getValue();
      LocalNode object = (LocalNode) constraint.getElement(2);
      Node prefixNode = resolverSession.globalize(object.getValue());

      // check the constraint for consistency
      if ((property != mulgaraPrefix && property != mulgaraStringPrefix)
          || !(prefixNode instanceof Literal || prefixNode instanceof URIReference)) {
        logger.debug("property = " + property + ", mulgaraPrefix = " + mulgaraPrefix);
        logger.debug("element(2): " + prefixNode + " [" + prefixNode.getClass().getName() + "]");
        throw new QueryException(
            "Prefix resolver can only be used for prefix constraints: " + constraint);
      }

      if (logger.isDebugEnabled()) {
        logger.debug(
            "Evaluating " + constraint.getElement(0) + " has prefix " + constraint.getElement(2));
      }

      ConstraintElement node = constraint.getElement(0);
      assert node != null;

      Tuples tuples;

      if (node instanceof Variable) {

        // convert the prefix into a string pool object
        SPObjectFactory spoFact = SPObjectFactoryImpl.getInstance();
        SPObject startPrefixObj = getStartObject(spoFact, prefixNode, property);
        SPObject endPrefixObj = getEndObject(spoFact, prefixNode, property);

        // get the extents of the prefix from the string pool
        tuples = resolverSession.findStringPoolRange(startPrefixObj, true, endPrefixObj, false);
        assert tuples != null;
        // rename variables away from subject, predicate and object
        tuples.renameVariables(constraint);

        long resultSize;
        try {
          // Get the size of the final result.
          resultSize = tuples.getRowCount();
        } catch (TuplesException e) {
          throw new QueryException("Unable to build result", e);
        }

        if (logger.isDebugEnabled()) {
          try {
            logger.debug(
                "tuples size = " + tuples.getRowCount() + " (should be " + resultSize + ")");
          } catch (TuplesException e) {
            logger.debug("Error getting the length of the tuples object");
          }
        }

        return new TuplesWrapperResolution(tuples, constraint);

      } else { // if (node instanceof Variable)

        // node must therefore be an instanceof LocalNode
        // we can shortcut the process here
        assert node instanceof LocalNode;
        LocalNode n = (LocalNode) node;

        // get the node out of the string pool
        SPObject spo = resolverSession.findStringPoolObject(n.getValue());

        // check that the node exists
        if (spo == null) {
          tuples = TuplesOperations.empty();
        } else {

          // see if the node starts with the required prefix

          String prefix;
          // extract the string from the literal
          if (prefixNode instanceof Literal) {
            prefix = ((Literal) prefixNode).getLexicalForm();
          } else {
            prefix = ((URIReference) prefixNode).getURI().toString();
          }
          if (spo.getLexicalForm().startsWith(prefix)) {
            tuples = TuplesOperations.unconstrained();
          } else {
            tuples = TuplesOperations.empty();
          }
        }
      }

      // convert the tuples to a resolution
      return new TuplesWrapperResolution(tuples, constraint);

    } catch (GlobalizeException ge) {
      throw new QueryException("Couldn't convert internal data into a string", ge);
    } catch (StringPoolException e) {
      throw new QueryException("Couldn't query constraint", e);
    }
  }
  /**
   * Read Node config from file config.nodeConfigFileName, including available nodes and their
   * possible connections
   */
  public NodeFactory(Config config, ProblemData problemData) {
    this.config = config;
    this.problemData = problemData;
    try {
      FileInputStream in = new FileInputStream(config.nodeConfigFileName);
      Properties props = new Properties();
      props.load(in);
      in.close();

      String separator = "\\s*,\\s*";

      String tmp = props.getProperty("sets");
      String[] sets = tmp.split(separator);

      nodeSets = new NodeSet[sets.length];

      int i, j, k;
      for (i = 0; i < sets.length; i++) {
        nodeSets[i] = new NodeSet(sets[i]);
        String[] nodes;
        tmp = props.getProperty(sets[i] + "Functions");
        if (tmp == null)
          Logger.log(
              "Warning: when reading "
                  + config.nodeConfigFileName
                  + ", no functions found for set "
                  + sets[i]);
        else {
          nodes = tmp.split(separator);
          for (j = 0; j < nodes.length; j++) {
            Class cl = Class.forName("gpalta.nodes." + nodes[j]);
            java.lang.reflect.Constructor co = cl.getConstructor();
            nodeSets[i].addFunction((Node) co.newInstance());
          }
        }
        tmp = props.getProperty(sets[i] + "Terminals");
        if (tmp == null)
          Logger.log(
              "Warning: when reading "
                  + config.nodeConfigFileName
                  + ", no terminals found for set "
                  + sets[i]);
        else {
          nodes = tmp.split(separator);
          for (j = 0; j < nodes.length; j++) {
            Class cl = Class.forName("gpalta.nodes." + nodes[j]);
            if (nodes[j].contains("Var")) {
              for (k = 0; k < problemData.nVars; k++) {
                java.lang.reflect.Constructor[] co = cl.getConstructors();
                nodeSets[i].addTerminal((Node) co[0].newInstance(k + 1));
              }
            } else if (nodes[j].contains("Angle")) {
              for (k = 0; k < problemData.nVars - 1; k++) {
                java.lang.reflect.Constructor[] co = cl.getConstructors();
                nodeSets[i].addTerminal((Node) co[0].newInstance(k + 1));
              }
            } else {
              java.lang.reflect.Constructor co = cl.getConstructor();
              nodeSets[i].addTerminal((Node) co.newInstance());
            }
          }
        }
      }

      for (i = 0; i < nodeSets.length; i++) {
        for (Node n : nodeSets[i].getAll()) {
          n.setType(nodeSets[i]);
        }
      }

      for (i = 0; i < nodeSets.length; i++) {
        for (Node n : nodeSets[i].getAll()) {
          tmp = props.getProperty("kids" + n.getClass().getSimpleName());
          if (tmp != null) {
            String[] kids = tmp.split(separator);
            if (kids.length != n.nKids()) {
              Logger.log(
                  "Error reading "
                      + config.nodeConfigFileName
                      + ": must specify "
                      + n.nKids()
                      + " kids for "
                      + n.getClass().getSimpleName());
            }
            for (j = 0; j < n.nKids(); j++) {
              for (k = 0; k < nodeSets.length; k++) {
                if (nodeSets[k].getName().equals(kids[j])) {
                  n.setTypeOfKids(j, nodeSets[k]);
                  break;
                }
              }
              if (k == nodeSets.length)
                Logger.log(
                    "Error reading "
                        + config.nodeConfigFileName
                        + ": Setting kids for "
                        + n.getClass().getSimpleName()
                        + ", "
                        + kids[j]
                        + " doesn't match any set name");
            }
          } else for (j = 0; j < n.nKids(); j++) n.setTypeOfKids(j, nodeSets[i]);
        }
      }
      tmp = props.getProperty("treeRoot");
      if (tmp == null) {
        Logger.log(
            "Error reading " + config.nodeConfigFileName + ": property \"treeRoot\" not present");
      }
      for (i = 0; i < nodeSets.length; i++) {
        if (nodeSets[i].getName().equals(tmp)) {
          treeRoot = nodeSets[i];
          break;
        }
      }
      if (i == nodeSets.length)
        Logger.log(
            "Error reading "
                + config.nodeConfigFileName
                + ": Setting treeRoot, "
                + tmp
                + " doesn't match any set name");
    } catch (IOException e) {
      Logger.log("Error reading " + config.nodeConfigFileName + ":");
      Logger.log(e);
    } catch (ClassNotFoundException e) {
      Logger.log("Error reading " + config.nodeConfigFileName + ":");
      Logger.log(e);
    } catch (NoSuchMethodException e) {
      Logger.log("Error reading " + config.nodeConfigFileName + ":");
      Logger.log(e);
    } catch (InstantiationException e) {
      Logger.log("Error reading " + config.nodeConfigFileName + ":");
      Logger.log(e);
    } catch (IllegalAccessException e) {
      Logger.log("Error reading " + config.nodeConfigFileName + ":");
      Logger.log(e);
    } catch (InvocationTargetException e) {
      Logger.log("Error reading " + config.nodeConfigFileName + ":");
      Logger.log(e);
    }
  }
 public void defaultCase(Node node) {
   if (logger.isDebugEnabled())
     logger.debug("Found node in pred builder: " + node + "::" + node.getClass());
 }
  private static List<Node> doInsert(
      Node insertionNode,
      List<Node> clonedNodes,
      XFormsInstance modifiedInstance,
      boolean doDispatch) {
    final List<Node> insertedNodes = new ArrayList<Node>(clonedNodes.size());
    if (insertionNode instanceof Element) {
      // Insert inside an element
      final Element insertContextElement = (Element) insertionNode;

      int otherNodeIndex = 0;
      for (Node clonedNode : clonedNodes) {

        if (clonedNode != null) { // NOTE: we allow passing some null nodes so we check on null
          if (clonedNode instanceof Attribute) {
            // Add attribute to element

            // NOTE: In XML, attributes are unordered. dom4j handles them as a list so has order,
            // but the
            // XForms spec shouldn't rely on attribute order. We could try to keep the order, but it
            // is harder
            // as we have to deal with removing duplicate attributes and find a reasonable insertion
            // strategy.
            final Attribute clonedAttribute = (Attribute) clonedNode;
            final Attribute existingAttribute =
                insertContextElement.attribute(clonedAttribute.getQName());

            if (existingAttribute != null) insertContextElement.remove(existingAttribute);

            insertContextElement.add(clonedAttribute);

            if (existingAttribute != null) {

              // Dispatch xxforms-replace event if required and possible
              // NOTE: For now, still dispatch xforms-insert for backward compatibility.
              if (doDispatch && modifiedInstance != null) {
                final DocumentWrapper documentWrapper =
                    (DocumentWrapper) modifiedInstance.documentInfo();

                Dispatch.dispatchEvent(
                    new XXFormsReplaceEvent(
                        modifiedInstance,
                        documentWrapper.wrap(existingAttribute),
                        documentWrapper.wrap(clonedAttribute)));
              }
            }

            insertedNodes.add(clonedAttribute);

          } else if (!(clonedNode instanceof Document)) {
            // Add other node to element
            insertContextElement.content().add(otherNodeIndex++, clonedNode);
            insertedNodes.add(clonedNode);
          } else {
            // "If a cloned node cannot be placed at the target location due to a node type
            // conflict, then the
            // insertion for that particular clone node is ignored."
          }
        }
      }
      return insertedNodes;
    } else if (insertionNode instanceof Document) {
      final Document insertContextDocument = (Document) insertionNode;

      // "If there is more than one cloned node to insert, only the first node that does not cause a
      // conflict is
      // considered."
      for (Node clonedNode : clonedNodes) {
        // Only an element can be inserted at the root of an instance
        if (clonedNode instanceof Element) {

          final Element formerRootElement = insertContextDocument.getRootElement();
          insertContextDocument.setRootElement((Element) clonedNode);

          // Dispatch xxforms-replace event if required and possible
          // NOTE: For now, still dispatch xforms-insert for backward compatibility.
          if (doDispatch && modifiedInstance != null) {
            final DocumentWrapper documentWrapper =
                (DocumentWrapper) modifiedInstance.documentInfo();

            Dispatch.dispatchEvent(
                new XXFormsReplaceEvent(
                    modifiedInstance,
                    documentWrapper.wrap(formerRootElement),
                    documentWrapper.wrap(insertContextDocument.getRootElement())));
          }

          insertedNodes.add(clonedNode);
          return insertedNodes;
        }
      }

      // NOTE: The spec does not allow inserting comments and PIs at the root of an instance
      // document at this
      // point.

      return insertedNodes;
    } else {
      throw new OXFException(
          "Unsupported insertion node type: " + insertionNode.getClass().getName());
    }
  }