Exemplo n.º 1
0
  /**
   * Returns a sibling element that matches a given definition, or <tt>null</tt> if no match is
   * found.
   *
   * @param sibling the sibling DOM element to begin the search
   * @param target the node to search for
   * @return the matching element, or <tt>null</tt> if not found
   */
  public static Element findSibling(Element sibling, XmlNode target) {
    String xmlName = target.getLocalName();
    String xmlNamespace = target.getNamespace();

    Node node = sibling;
    if (node == null) {
      return null;
    }

    while ((node = node.getNextSibling()) != null) {
      if (node.getNodeType() != Node.ELEMENT_NODE) {
        continue;
      }
      Element element = (Element) node;
      if (!element.getLocalName().equals(xmlName)) {
        continue;
      }
      if (target.isNamespaceAware()) {
        String ns = element.getNamespaceURI();
        if (ns == null) {
          if (xmlNamespace != null) {
            continue;
          }
        } else {
          if (!ns.equals(xmlNamespace)) {
            continue;
          }
        }
      }
      return element;
    }
    return null;
  }
Exemplo n.º 2
0
  @JRubyMethod(name = "root=")
  public IRubyObject root_set(ThreadContext context, IRubyObject newRoot_) {
    // in case of document fragment, temporary root node should be deleted.

    // Java can't have a root whose value is null. Instead of setting null,
    // the method sets user data so that other methods are able to know the root
    // should be nil.
    if (newRoot_ instanceof RubyNil) {
      getDocument().getDocumentElement().setUserData(NokogiriHelpers.VALID_ROOT_NODE, false, null);
      return newRoot_;
    }
    XmlNode newRoot = asXmlNode(context, newRoot_);

    IRubyObject root = root(context);
    if (root.isNil()) {
      Node newRootNode;
      if (getDocument() == newRoot.getOwnerDocument()) {
        newRootNode = newRoot.node;
      } else {
        // must copy otherwise newRoot may exist in two places
        // with different owner document.
        newRootNode = getDocument().importNode(newRoot.node, true);
      }
      add_child_node(context, getCachedNodeOrCreate(context.getRuntime(), newRootNode));
    } else {
      Node rootNode = asXmlNode(context, root).node;
      ((XmlNode) getCachedNodeOrCreate(context.getRuntime(), rootNode))
          .replace_node(context, newRoot);
    }

    return newRoot;
  }
Exemplo n.º 3
0
  public RegexpDef(XmlNode xmlNode) {
    super(xmlNode, false);

    this.max = (String) xmlNode.get("max");
    this.replace = (String) xmlNode.get("replace");

    XmlNode regexpPatternDefNode = (XmlNode) xmlNode.get("regexp-pattern[0]");
    DefinitionResolver.validate(regexpPatternDefNode);
    regexpPatternDef =
        regexpPatternDefNode == null
            ? null
            : new BaseElementDef(regexpPatternDefNode, "regexp-pattern");

    XmlNode regexpSourceDefNode = (XmlNode) xmlNode.get("regexp-source[0]");
    DefinitionResolver.validate(regexpSourceDefNode);
    regexpSourceDef =
        regexpSourceDefNode == null
            ? null
            : new BaseElementDef(regexpSourceDefNode, "regexp-source");

    XmlNode regexpResultDefNode = (XmlNode) xmlNode.get("regexp-result[0]");
    DefinitionResolver.validate(regexpResultDefNode);
    regexpResultDef =
        regexpResultDefNode == null
            ? null
            : new BaseElementDef(regexpResultDefNode, "regexp-result");
  }
Exemplo n.º 4
0
  @Override
  public void saveContent(ThreadContext context, SaveContext ctx) {
    if (!ctx.noDecl()) {
      ctx.append("<?xml version=\"");
      ctx.append(getDocument().getXmlVersion());
      ctx.append("\"");
      //            if(!cur.encoding(context).isNil()) {
      //                ctx.append(" encoding=");
      //                ctx.append(cur.encoding(context).asJavaString());
      //            }

      String encoding = ctx.getEncoding();

      if (encoding == null && !encoding(context).isNil()) {
        encoding = encoding(context).convertToString().asJavaString();
      }

      if (encoding != null) {
        ctx.append(" encoding=\"");
        ctx.append(encoding);
        ctx.append("\"");
      }

      // ctx.append(" standalone=\"");
      // ctx.append(getDocument().getXmlStandalone() ? "yes" : "no");
      ctx.append("?>\n");
    }

    IRubyObject maybeRoot = root(context);
    if (maybeRoot.isNil()) throw context.getRuntime().newRuntimeError("no root document");

    XmlNode root = (XmlNode) maybeRoot;
    root.saveContent(context, ctx);
    ctx.append("\n");
  }
  public void testPlaceholders() throws ParserConfigurationException, SAXException, IOException {

    String xml =
        ""
            + "<manifest\n"
            + "    xmlns:android=\"http://schemas.android.com/apk/res/android\">\n"
            + "    <activity android:name=\"activityOne\"\n"
            + "         android:attr1=\"${landscapePH}\"\n"
            + "         android:attr2=\"prefix.${landscapePH}\"\n"
            + "         android:attr3=\"${landscapePH}.suffix\"\n"
            + "         android:attr4=\"prefix${landscapePH}suffix\">\n"
            + "    </activity>\n"
            + "</manifest>";

    XmlDocument refDocument =
        TestUtils.xmlDocumentFromString(
            TestUtils.sourceFile(getClass(), "testPlaceholders#xml"), xml);

    PlaceholderHandler handler = new PlaceholderHandler();
    handler.visit(
        ManifestMerger2.MergeType.APPLICATION,
        refDocument,
        new KeyBasedValueResolver<String>() {
          @Override
          public String getValue(@NonNull String key) {
            return "newValue";
          }
        },
        mBuilder);

    Optional<XmlElement> activityOne =
        refDocument
            .getRootNode()
            .getNodeByTypeAndKey(ManifestModel.NodeTypes.ACTIVITY, ".activityOne");
    assertTrue(activityOne.isPresent());
    assertEquals(5, activityOne.get().getAttributes().size());
    // check substitution.
    assertEquals(
        "newValue",
        activityOne.get().getAttribute(XmlNode.fromXmlName("android:attr1")).get().getValue());
    assertEquals(
        "prefix.newValue",
        activityOne.get().getAttribute(XmlNode.fromXmlName("android:attr2")).get().getValue());
    assertEquals(
        "newValue.suffix",
        activityOne.get().getAttribute(XmlNode.fromXmlName("android:attr3")).get().getValue());
    assertEquals(
        "prefixnewValuesuffix",
        activityOne.get().getAttribute(XmlNode.fromXmlName("android:attr4")).get().getValue());

    for (XmlAttribute xmlAttribute : activityOne.get().getAttributes()) {
      // any attribute other than android:name should have been injected.
      if (!xmlAttribute.getName().toString().contains("name")) {
        verify(mActionRecorder)
            .recordAttributeAction(
                xmlAttribute, SourcePosition.UNKNOWN, Actions.ActionType.INJECTED, null);
      }
    }
  }
Exemplo n.º 6
0
  private static XmlNode mapNodeToXmlNode(Node node) {

    XmlNode xmlNode = new XmlNode();
    if (node != null) {
      xmlNode.setNodeText(node.getNodeText());
    }

    return xmlNode;
  }
 @Override
 public void evaluatePre(int depth, OutputManager out) {
   // Here we will get the event listener
   // This should be derived at the semantic analyzer using a library or something of the sort
   XmlNode parent = (XmlNode) this.getParent();
   out.setCurrentToActivity();
   out.writeEvent(
       Node.stripQuotes(parent.getAttributes().get("id"))
           + "."
           + SemanticManager.getEventMethodHeader(Node.stripQuotes(this.data))
           + "\n");
 }
Exemplo n.º 8
0
  public TryDef(XmlNode xmlNode) {
    super(xmlNode, false);

    XmlNode tryBodyDefNode = (XmlNode) xmlNode.get("body[0]");
    DefinitionResolver.validate(tryBodyDefNode);
    this.tryBodyDef = tryBodyDefNode == null ? null : new BaseElementDef(tryBodyDefNode, "body");

    XmlNode catchValueDefNode = (XmlNode) xmlNode.get("catch[0]");
    DefinitionResolver.validate(catchValueDefNode);
    this.catchValueDef =
        catchValueDefNode == null ? null : new BaseElementDef(catchValueDefNode, "catch");
  }
Exemplo n.º 9
0
  /**
   * @param prefix a namespace prefix
   * @param node an xml node
   * @return if the namespace is valid according to the node hierarchy
   */
  protected static boolean isParentNamespace(final String prefix, final XmlNode node) {
    boolean result = false;

    if ((node != null) && (node.getContent().isElement())) {
      for (XmlAttribute attr : node.getParent().getContent().getNamespaceAttributes()) {
        if (attr.getName().equals(prefix)) {
          result = true;
          break;
        }
      }
    }

    return result;
  }
Exemplo n.º 10
0
  private void getProperties(NamedNodeMap attributes) throws MessageException {
    if (attributes.getNamedItem("name") != null) {
      setName(attributes.getNamedItem("name").getNodeValue());
    }

    String identifier = xmlNode.getChildStringValue("identifier");
    setIdentifier(identifier);
    String identifierType = xmlNode.getChildStringValue("identifierType");
    setIdentifierType(identifierType);

    String type = xmlNode.getChildStringValue("type");
    setType(type);
    String text = xmlNode.getChildStringValue("text");
    setText(text);
    String interaction = xmlNode.getChildStringValue("interaction");
    setInteraction(interaction);
    String value = xmlNode.getChildStringValue("value");
    setValue(value);
    Integer timeout = xmlNode.getChildIntegerValue("timeout");
    setTimeout(timeout);
    String selectBy = xmlNode.getChildStringValue("selectBy");
    if (!selectBy.equals("")) {
      setSelectBy(selectBy);
    }
  }
  @Override
  protected final void writeListString(String str) {
    final Element parent = property().element();
    final XmlElement parentXmlElement = ((XmlResource) parent.resource()).getXmlElement(true);
    final XmlNode listXmlNode = parentXmlElement.getChildNode(this.path, false);

    if (str == null) {
      if (listXmlNode != null) {
        listXmlNode.remove();
      }
    } else {
      parentXmlElement.setChildNodeText(this.path, str, false);
    }
  }
Exemplo n.º 12
0
  private static Node mapXmlNodeToNode(XmlNode xmlNode) {

    Node node = new Node();

    node.setNodeText(xmlNode.getNodeText());
    return node;
  }
  @Override
  protected final String readListString() {
    final Element parent = property().element();
    final XmlElement parentXmlElement = ((XmlResource) parent.resource()).getXmlElement();

    if (parentXmlElement == null) {
      return null;
    }

    final XmlNode listXmlNode = parentXmlElement.getChildNode(this.path, false);

    if (listXmlNode == null) {
      return null;
    }

    return listXmlNode.getText();
  }
Exemplo n.º 14
0
  public static XMLDocument document(Object... objects) throws ThinklabException {

    XmlNode root = null;
    ArrayList<String> namespaces = null;

    for (Object o : objects) {
      if (o instanceof String) {

        /*
         * namespace
         */
        if (namespaces == null) namespaces = new ArrayList<String>();

        // namespaces.add((String)o);

      } else if (o instanceof XmlNode) {

        /*
         * must be only root node
         */
        if (root != null)
          throw new ThinklabValidationException("XML document: non-unique root node");
        root = (XmlNode) o;
      }
    }

    if (root == null) throw new ThinklabValidationException("XML.document: no root node specified");

    XMLDocument doc = new XMLDocument(root.tag);

    if (namespaces != null) {
      for (String ns : namespaces) {
        String[] nss = ns.split("=");
        if (nss.length != 2)
          throw new ThinklabValidationException(
              "XML.document: bad namespace specification: must be name=uri: " + ns);
        doc.addNamespace(nss[0], nss[1]);
      }
    }

    root.define(doc.root(), doc.dom);

    return doc;
  }
Exemplo n.º 15
0
 @Override
 public void accept(ThreadContext context, SaveContextVisitor visitor) {
   visitor.enter((Element) node);
   XmlNodeSet xmlNodeSet = (XmlNodeSet) children(context);
   if (xmlNodeSet.length() > 0) {
     RubyArray array = (RubyArray) xmlNodeSet.to_a(context);
     for (int i = 0; i < array.getLength(); i++) {
       Object item = array.get(i);
       if (item instanceof XmlNode) {
         XmlNode cur = (XmlNode) item;
         cur.accept(context, visitor);
       } else if (item instanceof XmlNamespace) {
         XmlNamespace cur = (XmlNamespace) item;
         cur.accept(context, visitor);
       }
     }
   }
   visitor.leave((Element) node);
 }
Exemplo n.º 16
0
  /**
   * Finds the Nth matching child of a DOM element.
   *
   * @param parent the parent DOM node
   * @param target the node to search for
   * @param offset the occurrence of the matching node
   * @return the matching element, or <tt>null</tt> if no match is found
   */
  public static Element findChild(Node parent, XmlNode target, int offset) {
    Node node = parent;
    if (node != null) {
      node = node.getFirstChild();
    }
    if (node == null) {
      return null;
    }

    String xmlName = target.getLocalName();
    String xmlNamespace = target.getNamespace();

    int count = 0;
    do {
      if (node.getNodeType() != Node.ELEMENT_NODE) {
        continue;
      }
      Element element = (Element) node;
      if (!element.getLocalName().equals(xmlName)) {
        continue;
      }
      if (target.isNamespaceAware()) {
        String ns = element.getNamespaceURI();
        if (ns == null) {
          if (xmlNamespace != null && xmlNamespace.length() != 0) {
            continue;
          }
        } else {
          if (!ns.equals(xmlNamespace)) {
            continue;
          }
        }
      }
      if (count == offset) {
        return element;
      }
      ++count;

    } while ((node = node.getNextSibling()) != null);

    return null;
  }
Exemplo n.º 17
0
 @JRubyMethod(name = "node_set")
 public IRubyObject node_set(ThreadContext context) {
   try {
     NodeList nodes = (NodeList) xpath.evaluate(this.context, XPathConstants.NODESET);
     XmlNodeSet result = new XmlNodeSet(context.getRuntime(), nodes);
     //            result.relink_namespace(context);
     result.setInstanceVariable("@document", contextNode.document(context));
     return result;
   } catch (XPathExpressionException xpee) {
     throw new RaiseException(XmlSyntaxError.getXPathSyntaxError(context));
   }
 }
Exemplo n.º 18
0
  /*
   * used only to implement derived classes such as HTML or GeoRSS
   */
  protected static XmlNode node(XmlNode ret, String tag, Object... objects)
      throws ThinklabException {

    ret.tag = tag;

    if (objects == null) return ret;

    for (Object o : objects) {
      ret.contents.add(o);
    }

    return ret;
  }
Exemplo n.º 19
0
 private void removeNamespceRecursively(ThreadContext context, XmlNode xmlNode) {
   Node node = xmlNode.node;
   if (node.getNodeType() == Node.ELEMENT_NODE) {
     node.setPrefix(null);
     node.getOwnerDocument().renameNode(node, null, node.getLocalName());
   }
   XmlNodeSet nodeSet = (XmlNodeSet) xmlNode.children(context);
   for (long i = 0; i < nodeSet.length(); i++) {
     XmlNode childNode =
         (XmlNode) nodeSet.slice(context, RubyFixnum.newFixnum(context.getRuntime(), i));
     removeNamespceRecursively(context, childNode);
   }
 }
Exemplo n.º 20
0
  public XmlXpath(Ruby ruby, RubyClass rubyClass, XPathExpression xpath, XmlNode context) {
    super(ruby, rubyClass);
    this.xpath = xpath;

    this.contextNode = context;

    this.context = context.getNode();

    //        //TODO: Refactor.
    //        if(context.getNode() instanceof Document) {
    //            this.context = context.getNode();
    //        } else {
    //            this.context = context.getNode().getParentNode();
    //        }
  }
Exemplo n.º 21
0
  /**
   * Returns the value of an attribute for an element.
   *
   * @param element the element to check
   * @param definition the definition of the attribute to retrieve from the element
   * @return the defined attribute value, or <tt>null</tt> if the attribute was not found on the
   *     element
   */
  public static String getAttribute(Element element, XmlNode definition) {
    if (element == null) {
      return null;
    }

    if (definition.isNamespaceAware()) {
      if (element.hasAttributeNS(definition.getNamespace(), definition.getLocalName())) {
        return element.getAttributeNS(definition.getNamespace(), definition.getLocalName());
      }
    } else {
      if (element.hasAttribute(definition.getLocalName())) {
        return element.getAttribute(definition.getLocalName());
      }
    }
    return null;
  }
Exemplo n.º 22
0
  public FunctionDef(XmlNode xmlNode) {
    super(xmlNode);

    this.name = xmlNode.getAttribute("name");
  }
Exemplo n.º 23
0
 public static XmlStructure create(String id) {
   return new XmlStructure(XmlNode.of(Document.get().getElementById(XmlNode.quoteId(id))));
 }
Exemplo n.º 24
0
  public HtmlToXmlDef(XmlNode xmlNode) {
    super(xmlNode);

    this.outputType = (String) xmlNode.get("outputtype");
    this.advancedXmlEscape = (String) xmlNode.get("advancedxmlescape");
    this.useCdataForScriptAndStyle = (String) xmlNode.get("usecdata");
    this.translateSpecialEntities = (String) xmlNode.get("specialentities");
    this.recognizeUnicodeChars = (String) xmlNode.get("unicodechars");
    this.omitUnknownTags = (String) xmlNode.get("omitunknowntags");
    this.treatUnknownTagsAsContent = (String) xmlNode.get("treatunknowntagsascontent");
    this.omitDeprecatedTags = (String) xmlNode.get("omitdeprtags");
    this.treatDeprecatedTagsAsContent = (String) xmlNode.get("treatdeprtagsascontent");
    this.omitComments = (String) xmlNode.get("omitcomments");
    this.omitHtmlEnvelope = (String) xmlNode.get("omithtmlenvelope");
    this.allowMultiWordAttributes = (String) xmlNode.get("allowmultiwordattributes");
    this.allowHtmlInsideAttributes = (String) xmlNode.get("allowhtmlinsideattributes");
    this.namespacesAware = (String) xmlNode.get("namespacesaware");
    this.prunetags = (String) xmlNode.get("prunetags");
  }
Exemplo n.º 25
0
 @Override
 public XmlNode getNode(String id) {
   return XmlNode.of(Document.get().getElementById(XmlNode.quoteId(id)));
 }