示例#1
0
  /**
   * Copy in-scope namespace declarations of the decl node to the decl node itself so that this move
   * won't change the in-scope namespace bindings.
   */
  private void copyInscopeNSAttributes(Element e) {
    Element p = e;
    Set<String> inscopes = new HashSet<String>();
    while (true) {
      NamedNodeMap atts = p.getAttributes();
      for (int i = 0; i < atts.getLength(); i++) {
        Attr a = (Attr) atts.item(i);
        if (Constants.NS_XMLNS.equals(a.getNamespaceURI())) {
          String prefix;
          if (a.getName().indexOf(':') == -1) prefix = "";
          else prefix = a.getLocalName();

          if (inscopes.add(prefix) && p != e) {
            // if this is the first time we see this namespace bindings,
            // copy the declaration.
            // if p==decl, there's no need to. Note that
            // we want to add prefix to inscopes even if p==Decl

            e.setAttributeNodeNS((Attr) a.cloneNode(true));
          }
        }
      }

      if (p.getParentNode() instanceof Document) break;

      p = (Element) p.getParentNode();
    }

    if (!inscopes.contains("")) {
      // if the default namespace was undeclared in the context of decl,
      // it must be explicitly set to "" since the new environment might
      // have a different default namespace URI.
      e.setAttributeNS(Constants.NS_XMLNS, "xmlns", "");
    }
  }
  private String deleteComponentBindingFromXML(
      String componentXML, Integer entityId, String entityName) throws Exception {
    String entityNameTrigger = "Content";
    if (entityName.equals(SiteNode.class.getName())) entityNameTrigger = "SiteNode";

    Document document = XMLHelper.readDocumentFromByteArray(componentXML.getBytes("UTF-8"));
    String componentPropertyXPath =
        "//component/properties/property/binding[@entityId='" + entityId + "']";
    // logger.info("componentPropertyXPath:" + componentPropertyXPath);
    String modifiedXML = null;

    NodeList anl =
        org.apache.xpath.XPathAPI.selectNodeList(
            document.getDocumentElement(), componentPropertyXPath);
    // logger.info("anl:" + anl.getLength());
    for (int i = 0; i < anl.getLength(); i++) {
      Element component = (Element) anl.item(i);
      String entity = component.getAttribute("entity");
      if (entity != null && entity.equalsIgnoreCase(entityNameTrigger)) {
        Element property = (Element) component.getParentNode();
        if (property.getChildNodes().getLength() > 1) {
          property.removeChild(component);
        } else {
          if (property != null && property.getParentNode() != null) {
            property.getParentNode().removeChild(property);
          }
        }
      }
    }

    modifiedXML = XMLHelper.serializeDom(document, new StringBuffer()).toString();

    return modifiedXML;
  }
 @Override
 public ServiceCreationConfiguration<TransactionManagerProvider> parseServiceCreationConfiguration(
     Element fragment) {
   String localName = fragment.getLocalName();
   if ("jta-tm".equals(localName)) {
     String transactionManagerProviderConfigurationClassName =
         fragment.getAttribute("transaction-manager-lookup-class");
     try {
       ClassLoader defaultClassLoader = ClassLoading.getDefaultClassLoader();
       Class<?> aClass =
           Class.forName(
               transactionManagerProviderConfigurationClassName, true, defaultClassLoader);
       return new LookupTransactionManagerProviderConfiguration(
           (Class<? extends TransactionManagerLookup>) aClass);
     } catch (Exception e) {
       throw new XmlConfigurationException("Error configuring XA transaction manager", e);
     }
   } else {
     throw new XmlConfigurationException(
         String.format(
             "XML configuration element <%s> in <%s> is not supported",
             fragment.getTagName(),
             (fragment.getParentNode() == null
                 ? "null"
                 : fragment.getParentNode().getLocalName())));
   }
 }
  public String getCheckedId(Element e, String id) {
    String idChecked = id;

    if (e.getParentNode() instanceof Element) {

      NodeList nl = ((Element) e.getParentNode()).getElementsByTagName(e.getTagName());
      boolean checked = false;

      int i = 1;

      while (!checked) {
        checked = true;

        for (int j = 0; j < nl.getLength(); j++) {
          Element e2 = (Element) nl.item(j);
          if (e2.getAttribute("id").equals(idChecked) && e != e2) {
            i++;
            idChecked = id + i;
            checked = false;
            break;
          }
        }
      }
    }

    return idChecked;
  }
示例#5
0
  // @Override
  protected void parseChild(
      Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    // Not sure if this is required. Adding for now for backwards compatability
    if (element.getParentNode().getNodeName().equals("chaining-router")
        || element.getParentNode().getNodeName().equals("exception-based-router")) {
      builder.addPropertyValue(AbstractEndpointBuilder.PROPERTY_REMOTE_SYNC, Boolean.TRUE);
    }

    super.parseChild(element, parserContext, builder);
  }
示例#6
0
  /**
   * Carries out preprocessing that makes JEuclid handle the document better.
   *
   * @param doc Document
   */
  static void preprocessForJEuclid(Document doc) {
    // underbrace and overbrace
    NodeList list = doc.getElementsByTagName("mo");
    for (int i = 0; i < list.getLength(); i++) {
      Element mo = (Element) list.item(i);
      String parentName = ((Element) mo.getParentNode()).getTagName();
      if (parentName == null) {
        continue;
      }
      if (parentName.equals("munder") && isTextChild(mo, "\ufe38")) {
        mo.setAttribute("stretchy", "true");
        mo.removeChild(mo.getFirstChild());
        mo.appendChild(doc.createTextNode("\u23df"));
      } else if (parentName.equals("mover") && isTextChild(mo, "\ufe37")) {
        mo.setAttribute("stretchy", "true");
        mo.removeChild(mo.getFirstChild());
        mo.appendChild(doc.createTextNode("\u23de"));
      }
    }

    // menclose for long division doesn't allow enough top padding. Oh, and
    // <mpadded> isn't implemented. And there isn't enough padding to left of
    // the bar either. Solve by adding an <mover> with just an <mspace> over#
    // the longdiv, contained within an mrow that adds a <mspace> before it.
    list = doc.getElementsByTagName("menclose");
    for (int i = 0; i < list.getLength(); i++) {
      Element menclose = (Element) list.item(i);
      // Only for longdiv
      if (!"longdiv".equals(menclose.getAttribute("notation"))) {
        continue;
      }
      Element mrow = doc.createElementNS(WebMathsService.NS, "mrow");
      Element mover = doc.createElementNS(WebMathsService.NS, "mover");
      Element mspace = doc.createElementNS(WebMathsService.NS, "mspace");
      Element mspaceW = doc.createElementNS(WebMathsService.NS, "mspace");
      boolean previousElement = false;
      for (Node previous = menclose.getPreviousSibling();
          previous != null;
          previous = previous.getPreviousSibling()) {
        if (previous.getNodeType() == Node.ELEMENT_NODE) {
          previousElement = true;
          break;
        }
      }
      if (previousElement) {
        mspaceW.setAttribute("width", "4px");
      }
      menclose.getParentNode().insertBefore(mrow, menclose);
      menclose.getParentNode().removeChild(menclose);
      mrow.appendChild(mspaceW);
      mrow.appendChild(mover);
      mover.appendChild(menclose);
      mover.appendChild(mspace);
    }
  }
  private boolean indentBeforeElementOpen(Element element, int depth) {
    if (isMarkupElement(element)) {
      return false;
    }

    if (element.getParentNode().getNodeType() == Node.ELEMENT_NODE
        && keepElementAsSingleLine(depth - 1, (Element) element.getParentNode())) {
      return false;
    }

    return true;
  }
  private boolean newlineAfterElementClose(Element element, int depth) {
    if (hasBlankLineAbove()) {
      return false;
    }

    if (isMarkupElement(element)) {
      return false;
    }

    return element.getParentNode().getNodeType() == Node.ELEMENT_NODE
        && !keepElementAsSingleLine(depth - 1, (Element) element.getParentNode());
  }
  @Override
  public void endElement(final String uri, final String localName, final String qName) {
    if (current == null) {
      return;
    }

    Node parent = current.getParentNode();
    // If the parent is the document itself, then we're done.
    if (parent.getParentNode() == null) {
      current.normalize();
      current = null;
    } else {
      current = (Element) current.getParentNode();
    }
  }
示例#10
0
    @Override
    public void apply(Element e) {
      if (isNodeWithPrototype(e, nodePrototype)) {
        Element parent = (Element) e.getParentNode();
        String child = e.getAttributeNode("name").getValue();
        removedNodes.add(child);

        List<String> publishedInputs = getParentPublishedInputs(parent, child);
        for (String publishedInput : publishedInputs) removeNodeInput(parent, publishedInput);

        removeConnections(parent, child);
        renameRenderedChildReference(parent, child, null);
        e.getParentNode().removeChild(e);
      }
    }
  /**
   * @param context
   * @param jaxwsBinding
   * @param e
   */
  private void parseParameter(
      com.sun.tools.internal.ws.api.wsdl.TWSDLParserContext context,
      JAXWSBinding jaxwsBinding,
      Element e) {
    String part = XmlUtil.getAttributeOrNull(e, JAXWSBindingsConstants.PART_ATTR);
    Element msgPartElm = evaluateXPathNode(e.getOwnerDocument(), part, new NamespaceContextImpl(e));
    Node msgElm = msgPartElm.getParentNode();
    // MessagePart msgPart = new MessagePart();

    String partName = XmlUtil.getAttributeOrNull(msgPartElm, "name");
    String msgName = XmlUtil.getAttributeOrNull((Element) msgElm, "name");
    if ((partName == null) || (msgName == null)) {
      return;
    }

    String element = XmlUtil.getAttributeOrNull(e, JAXWSBindingsConstants.ELEMENT_ATTR);
    String name = XmlUtil.getAttributeOrNull(e, JAXWSBindingsConstants.NAME_ATTR);

    QName elementName = null;
    if (element != null) {
      String uri = e.lookupNamespaceURI(XmlUtil.getPrefix(element));
      elementName = (uri == null) ? null : new QName(uri, XmlUtil.getLocalPart(element));
    }

    jaxwsBinding.addParameter(new Parameter(msgName, partName, elementName, name));
  }
示例#12
0
 /**
  * Append a sibling element, with text, with the active element of XML object.
  *
  * @param element The name of element to add.
  * @param text The text value of the element to be appended.
  */
 public void addSibling(String element, String text) {
   Element newElement = ownerDoc.createElement(element);
   Node textNode = ownerDoc.createTextNode(text);
   newElement.appendChild(textNode);
   Node parentNode = activeElement.getParentNode();
   parentNode.appendChild(newElement);
 }
示例#13
0
  public static void transform(URL url, OutputStream os) throws Exception {
    // Build dom document
    Document doc = parse(url);
    // Heuristicly retrieve name and version
    String name = getPath(url);
    int idx = name.lastIndexOf('/');
    if (idx >= 0) {
      name = name.substring(idx + 1);
    }
    String[] str = DeployerUtils.extractNameVersionType(name);
    // Create manifest
    Manifest m = new Manifest();
    m.getMainAttributes().putValue("Manifest-Version", "2");
    m.getMainAttributes().putValue(Constants.BUNDLE_MANIFESTVERSION, "2");
    m.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, str[0]);
    m.getMainAttributes().putValue(Constants.BUNDLE_VERSION, str[1]);
    String importPkgs = getImportPackages(analyze(new DOMSource(doc)));
    if (importPkgs != null && importPkgs.length() > 0) {
      m.getMainAttributes().putValue(Constants.IMPORT_PACKAGE, importPkgs);
    }
    m.getMainAttributes().putValue(Constants.DYNAMICIMPORT_PACKAGE, "*");
    // Extract manifest entries from the DOM
    NodeList l = doc.getElementsByTagName("manifest");
    if (l != null) {
      for (int i = 0; i < l.getLength(); i++) {
        Element e = (Element) l.item(i);
        String text = e.getTextContent();
        Properties props = new Properties();
        props.load(new ByteArrayInputStream(text.trim().getBytes()));
        Enumeration en = props.propertyNames();
        while (en.hasMoreElements()) {
          String k = (String) en.nextElement();
          String v = props.getProperty(k);
          m.getMainAttributes().putValue(k, v);
        }
        e.getParentNode().removeChild(e);
      }
    }

    JarOutputStream out = new JarOutputStream(os);
    ZipEntry e = new ZipEntry(JarFile.MANIFEST_NAME);
    out.putNextEntry(e);
    m.write(out);
    out.closeEntry();
    e = new ZipEntry("OSGI-INF/");
    out.putNextEntry(e);
    e = new ZipEntry("OSGI-INF/blueprint/");
    out.putNextEntry(e);
    out.closeEntry();
    // check .xml file extension
    if (!name.endsWith(".xml")) {
      name += ".xml";
    }
    e = new ZipEntry("OSGI-INF/blueprint/" + name);
    out.putNextEntry(e);
    // Copy the new DOM
    XmlUtils.transform(new DOMSource(doc), new StreamResult(out));
    out.closeEntry();
    out.close();
  }
  public void signAssertion(Document samlDocument) throws ProcessingException {
    Element originalAssertionElement =
        org.keycloak.saml.common.util.DocumentUtil.getChildElement(
            samlDocument.getDocumentElement(),
            new QName(
                JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get()));
    if (originalAssertionElement == null) return;
    Node clonedAssertionElement = originalAssertionElement.cloneNode(true);
    Document temporaryDocument;

    try {
      temporaryDocument = org.keycloak.saml.common.util.DocumentUtil.createDocument();
    } catch (ConfigurationException e) {
      throw new ProcessingException(e);
    }

    temporaryDocument.adoptNode(clonedAssertionElement);
    temporaryDocument.appendChild(clonedAssertionElement);

    signDocument(temporaryDocument);

    samlDocument.adoptNode(clonedAssertionElement);

    Element parentNode = (Element) originalAssertionElement.getParentNode();

    parentNode.replaceChild(clonedAssertionElement, originalAssertionElement);
  }
示例#15
0
 private Element levelUp() throws NoSuchElementException {
   if (state != STATE_IN_EMPTY_SET) {
     __current = (Element) __current.getParentNode();
   }
   state = STATE_AT;
   return __current;
 }
  static Element getDocumentElement(Set set) {
    Iterator it = set.iterator();
    Element e = null;
    while (it.hasNext()) {
      Node currentNode = (Node) it.next();
      if (currentNode != null && currentNode.getNodeType() == Node.ELEMENT_NODE) {
        e = (Element) currentNode;
        break;
      }
    }
    List parents = new ArrayList(10);

    // Obtain all the parents of the elemnt
    while (e != null) {
      parents.add(e);
      Node n = e.getParentNode();
      if (n == null || n.getNodeType() != Node.ELEMENT_NODE) {
        break;
      }
      e = (Element) n;
    }
    // Visit them in reverse order.
    ListIterator it2 = parents.listIterator(parents.size() - 1);
    Element ele = null;
    while (it2.hasPrevious()) {
      ele = (Element) it2.previous();
      if (set.contains(ele)) {
        return ele;
      }
    }
    return null;
  }
示例#17
0
  @Override
  protected void changeItem(UntypedItemXml item) {
    Element element = getElement(item, property);
    if (element == null) {
      throw new CliException("Cannot find element: " + property);
    }

    String namespaceURI = element.getNamespaceURI();
    String localName = element.getLocalName();

    Node parentNode = element.getParentNode();
    String parentNamespaceUri = parentNode.getNamespaceURI();
    String parentTag = parentNode.getLocalName();

    String pathKey = parentNamespaceUri + ":" + parentTag + ":" + namespaceURI + ":" + localName;

    if ("http://platformlayer.org/service/platformlayer/v1.0:platformLayerService:http://platformlayer.org/service/platformlayer/v1.0:config"
        .equals(pathKey)) {
      Element newNode = element.getOwnerDocument().createElementNS(NAMESPACE_URI_CORE, "property");
      Element keyNode = element.getOwnerDocument().createElementNS(NAMESPACE_URI_CORE, "key");
      keyNode.setTextContent(key);
      Element valueNode = element.getOwnerDocument().createElementNS(NAMESPACE_URI_CORE, "value");
      valueNode.setTextContent(value);
      newNode.appendChild(keyNode);
      newNode.appendChild(valueNode);

      element.appendChild(newNode);
    } else {
      throw new UnsupportedOperationException();
    }
  }
示例#18
0
 @Override
 public void apply(Element e) {
   if (e.getTagName().equals("property")) {
     Element parent = (Element) e.getParentNode();
     if (parent != null && parent.getTagName().equals("ndbx")) {
       Attr name = e.getAttributeNode("name");
       Attr value = e.getAttributeNode("value");
       if (name != null && name.getValue().equals("oscPort")) {
         if (value != null) {
           Element device = e.getOwnerDocument().createElement("device");
           device.setAttribute("name", "osc1");
           device.setAttribute("type", "osc");
           Element portProperty = e.getOwnerDocument().createElement("property");
           portProperty.setAttribute("name", "port");
           portProperty.setAttribute("value", value.getValue());
           device.appendChild(portProperty);
           Element autostartProperty = e.getOwnerDocument().createElement("property");
           autostartProperty.setAttribute("name", "autostart");
           autostartProperty.setAttribute("value", "true");
           device.appendChild(autostartProperty);
           parent.replaceChild(device, e);
         } else {
           parent.removeChild(e);
         }
       }
     }
   }
 }
示例#19
0
  public ArrayList<Entity> getEntitiesFromFile(String filePath) {
    ArrayList<Entity> entities = new ArrayList<>();
    try {
      d = db.parse(filePath);

      NodeList entityMentions = d.getElementsByTagName("entity_mention");
      for (int i = 0; i < entityMentions.getLength(); i++) {
        Element entityMention = (Element) entityMentions.item(i);
        NodeList heads = entityMention.getElementsByTagName("head");
        Element head = (Element) heads.item(0);
        NodeList charseqs = head.getElementsByTagName("charseq");
        Element charseq = (Element) charseqs.item(0);
        int start = Integer.parseInt(charseq.getAttribute("START"));
        int end = Integer.parseInt(charseq.getAttribute("END"));
        String value = charseq.getFirstChild().getNodeValue();
        // value = value.replaceAll("\n", "");
        String id = entityMention.getAttribute("ID");
        Element entityParent = (Element) entityMention.getParentNode();
        String type = entityParent.getAttribute("TYPE");
        // String subType = entityParent.getAttribute("SUBTYPE");
        Entity entity = new Entity(value, start, end, type, id);
        entities.add(entity);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return entities;
  }
示例#20
0
  public DomReader moveToNextNamed() throws XmlMissingElementException {
    if (!tryMoveToNextNamed())
      throw new XmlMissingElementException(
          current_element.getParentNode(), current_element.getNodeName());

    return this;
  }
示例#21
0
  /** Removes the scripting listeners from the given element. */
  protected void removeScriptingListenersOn(Element elt) {
    String eltNS = elt.getNamespaceURI();
    String eltLN = elt.getLocalName();
    if (SVGConstants.SVG_NAMESPACE_URI.equals(eltNS)
        && SVG12Constants.SVG_HANDLER_TAG.equals(eltLN)) {
      // For this 'handler' element, remove the handler for the given
      // event type.
      AbstractElement tgt = (AbstractElement) elt.getParentNode();
      String eventType =
          elt.getAttributeNS(
              XMLConstants.XML_EVENTS_NAMESPACE_URI, XMLConstants.XML_EVENTS_EVENT_ATTRIBUTE);
      String eventNamespaceURI = XMLConstants.XML_EVENTS_NAMESPACE_URI;
      if (eventType.indexOf(':') != -1) {
        String prefix = DOMUtilities.getPrefix(eventType);
        eventType = DOMUtilities.getLocalName(eventType);
        eventNamespaceURI = ((AbstractElement) elt).lookupNamespaceURI(prefix);
      }

      EventListener listener =
          (EventListener) handlerScriptingListeners.put(eventNamespaceURI, eventType, elt, null);
      tgt.removeEventListenerNS(eventNamespaceURI, eventType, listener, false);
    }

    super.removeScriptingListenersOn(elt);
  }
  @Inject
  BecomeAnyAccountLoginServlet(
      final Provider<WebSession> ws,
      final SchemaFactory<ReviewDb> sf,
      final @CanonicalWebUrl @Nullable Provider<String> up,
      final AccountManager am,
      final ServletContext servletContext)
      throws IOException {
    webSession = ws;
    schema = sf;
    urlProvider = up;
    accountManager = am;

    final String pageName = "BecomeAnyAccount.html";
    final Document doc = HtmlDomUtil.parseFile(getClass(), pageName);
    if (doc == null) {
      throw new FileNotFoundException("No " + pageName + " in webapp");
    }
    if (!IS_DEV) {
      final Element devmode = HtmlDomUtil.find(doc, "gerrit_gwtdevmode");
      if (devmode != null) {
        devmode.getParentNode().removeChild(devmode);
      }
    }
    raw = HtmlDomUtil.toUTF8(doc);
  }
示例#23
0
  public Document nextTableRow(String atts) {

    // peek at current cell - stay with it IF
    //  + it's the first cell in the row
    //  + the current cursor points at the first child (a block)
    //  + the block pointed by cursor is empty
    Element cell = peek("table-cell", "nextTableRow() is not applicable outside enclosing table");
    if (cell.getPreviousSibling() == null
        && cursor == cell.getFirstChild()
        && !cursor.hasChildNodes()) {
      attributes((Element) cell.getParentNode(), atts);
      return this;
    }

    // pop to table
    pop("table", "nextTableRow() is not applicable outside enclosing table");
    Element table = cursor;

    // last child is already table-body?
    if (table.getLastChild().getNodeName().equals("table-body")) {
      cursor = (Element) table.getLastChild();
    } else {
      push("table-body");
    }

    // add row
    push("table-row", atts);

    // add cell
    push("table-cell", "border=" + table.getAttribute("border"));
    push("block");

    // done
    return this;
  }
示例#24
0
    private void setVarFields(Map<Integer, ComponentDef> components, List<Element> elements) {
      for (Element e : elements) {

        Integer index = getOptionalInteger(e, ATTR_INDEX);
        if (index == null) {
          index = Integer.valueOf(getMandatoryAttribute(e, ATTR_TAG));
        }
        ComponentDef existingDef = components.get(index);
        ComponentDef newDef = null;
        if (isCompositeVar(e) || ELEMENT_COMPOSITE_TLV.equals(e.getTagName())) {
          if (existingDef != null) {
            newDef = buildCompositeDef(existingDef, e);
          }
        }

        if (newDef == null) {
          if (ELEMENT_COMPOSITE_TLV.equals(((Element) e.getParentNode()).getTagName())) {
            newDef = buildTlvComponent(e, getOrdinality(e));
          } else {
            newDef = buildComponent(e, getOrdinality(e));
          }
        }

        components.put(index, newDef);
      }
    }
  @Override
  protected void delete() {
    int pos = list.getSelectedIndex();

    if (pos == -1) return;

    Element e = list.getItems().get(pos);

    // delete init_scene attr if the scene to delete is the chapter init_scene
    if (((Element) e.getParentNode())
        .getAttribute(XMLConstants.INIT_SCENE_ATTR)
        .equals(e.getAttribute(XMLConstants.ID_ATTR))) {
      ((Element) e.getParentNode()).removeAttribute(XMLConstants.INIT_SCENE_ATTR);
    }

    super.delete();
  }
示例#26
0
 private Element getParagraph(Element node) {
   Element parent = (Element) node.getParentNode();
   if (parent.getTagName().equals(XMLString.TEXT_P)
       || parent.getTagName().equals(XMLString.TEXT_H)) {
     return parent;
   }
   return getParagraph(parent);
 }
  /**
   * Adds to ns the definitons from the parent elements of el
   *
   * @param el
   * @param ns
   */
  static final void getParentNameSpaces(Element el, NameSpaceSymbTable ns) {
    List parents = new ArrayList();
    Node n1 = el.getParentNode();
    if (!(n1 instanceof Element)) {
      return;
    }
    // Obtain all the parents of the elemnt
    Element parent = (Element) el.getParentNode();
    while (parent != null) {
      parents.add(parent);
      Node n = parent.getParentNode();
      if (!(n instanceof Element)) {
        break;
      }
      parent = (Element) n;
    }
    // Visit them in reverse order.
    ListIterator it = parents.listIterator(parents.size());
    while (it.hasPrevious()) {
      Element ele = (Element) it.previous();
      if (!ele.hasAttributes()) {
        continue;
      }
      NamedNodeMap attrs = ele.getAttributes();
      int attrsLength = attrs.getLength();
      for (int i = 0; i < attrsLength; i++) {
        Attr N = (Attr) attrs.item(i);
        if (!Constants.NamespaceSpecNS.equals(N.getNamespaceURI())) {
          // Not a namespace definition, ignore.
          continue;
        }

        String NName = N.getLocalName();
        String NValue = N.getNodeValue();
        if (XML.equals(NName) && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
          continue;
        }
        ns.addMapping(NName, NValue, N);
      }
    }
    Attr nsprefix;
    if (((nsprefix = ns.getMappingWithoutRendered("xmlns")) != null)
        && "".equals(nsprefix.getValue())) {
      ns.addMappingAndRender("xmlns", "", nullNode);
    }
  }
示例#28
0
  private void moveElementIntoElement(Element parentElement, Element movingElement) {
    // remove element from old parent
    Element oldParent = (Element) movingElement.getParentNode();
    oldParent.removeChild(movingElement);

    // append it into new parent
    parentElement.appendChild(movingElement);
  }
示例#29
0
  /** create node maps so that we can access node faster by their name */
  protected void createNodeMaps() {
    pkgMap = new Hashtable();
    classMap = new Hashtable();
    // create a map index of all packages by their name
    // @todo can be done faster by direct access.
    NodeList packages = report.getElementsByTagName("package");
    final int pkglen = packages.getLength();
    log("Indexing " + pkglen + " packages");
    for (int i = pkglen - 1; i > -1; i--) {
      Element pkg = (Element) packages.item(i);
      String pkgname = pkg.getAttribute("name");

      int nbclasses = 0;
      // create a map index of all classes by their fully
      // qualified name.
      NodeList classes = pkg.getElementsByTagName("class");
      final int classlen = classes.getLength();
      log("Indexing " + classlen + " classes in package " + pkgname);
      for (int j = classlen - 1; j > -1; j--) {
        Element clazz = (Element) classes.item(j);
        String classname = clazz.getAttribute("name");
        if (pkgname != null && pkgname.length() != 0) {
          classname = pkgname + "." + classname;
        }

        int nbmethods = 0;
        NodeList methods = clazz.getElementsByTagName("method");
        final int methodlen = methods.getLength();
        for (int k = methodlen - 1; k > -1; k--) {
          Element meth = (Element) methods.item(k);
          StringBuffer methodname = new StringBuffer(meth.getAttribute("name"));
          methodname.delete(methodname.toString().indexOf("("), methodname.toString().length());
          String signature = classname + "." + methodname + "()";
          if (filters.accept(signature)) {
            log("kept method:" + signature);
            nbmethods++;
          } else {
            clazz.removeChild(meth);
          }
        }
        // if we don't keep any method, we don't keep the class
        if (nbmethods != 0 && classFiles.containsKey(classname)) {
          log("Adding class '" + classname + "'");
          classMap.put(classname, clazz);
          nbclasses++;
        } else {
          pkg.removeChild(clazz);
        }
      }
      if (nbclasses != 0) {
        log("Adding package '" + pkgname + "'");
        pkgMap.put(pkgname, pkg);
      } else {
        pkg.getParentNode().removeChild(pkg);
      }
    }
    log("Indexed " + classMap.size() + " classes in " + pkgMap.size() + " packages");
  }
示例#30
0
  protected void parseChild(
      Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    Element parent = (Element) element.getParentNode();
    String serviceName = parent.getAttribute(ATTRIBUTE_NAME);
    builder.addPropertyReference("service", serviceName);

    // Create a BeanDefinition for the nested object factory and set it a
    // property value for the component
    AbstractBeanDefinition objectFactoryBeanDefinition = new GenericBeanDefinition();
    objectFactoryBeanDefinition.setBeanClass(OBJECT_FACTORY_TYPE);
    objectFactoryBeanDefinition
        .getPropertyValues()
        .addPropertyValue(AbstractObjectFactory.ATTRIBUTE_OBJECT_CLASS, componentInstanceClass);
    objectFactoryBeanDefinition.setInitMethodName(Initialisable.PHASE_NAME);
    objectFactoryBeanDefinition.setDestroyMethodName(Disposable.PHASE_NAME);
    Map props = new HashMap();
    for (int i = 0; i < element.getAttributes().getLength(); i++) {
      Node n = element.getAttributes().item(i);
      props.put(n.getLocalName(), n.getNodeValue());
    }
    String returnData = null;

    NodeList list = element.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
      if ("return-data".equals(list.item(i).getLocalName())) {
        Element rData = (Element) list.item(i);
        if (StringUtils.isNotEmpty(rData.getAttribute("file"))) {
          String file = rData.getAttribute("file");
          try {
            returnData = IOUtils.getResourceAsString(file, getClass());
          } catch (IOException e) {
            throw new BeanCreationException("Failed to load test-data resource: " + file, e);
          }
        } else {
          returnData = rData.getTextContent();
        }
      } else if ("callback".equals(list.item(i).getLocalName())) {
        Element ele = (Element) list.item(i);
        String c = ele.getAttribute("class");
        try {
          EventCallback cb = (EventCallback) ClassUtils.instanciateClass(c);
          props.put("eventCallback", cb);

        } catch (Exception e) {
          throw new BeanCreationException("Failed to load event-callback: " + c, e);
        }
      }
    }

    if (returnData != null) {
      props.put("returnData", returnData);
    }
    objectFactoryBeanDefinition.getPropertyValues().addPropertyValue("properties", props);

    builder.addPropertyValue("objectFactory", objectFactoryBeanDefinition);

    super.parseChild(element, parserContext, builder);
  }