예제 #1
0
  public DataNode(Element node) {

    this.tagName = node.getTagName();

    NamedNodeMap nnm = node.getAttributes();
    attributes.put(tagName, new HashMap<String, String>());
    for (int j = 0; j < nnm.getLength(); j++) {
      attributes.get(tagName).put(nnm.item(j).getNodeName(), nnm.item(j).getNodeValue());
    }

    // TODO: just iterate through all children instead of using predefined list of names?
    for (int j = 0; j < elementNames.length; j++) {
      NodeList elements = node.getElementsByTagName(elementNames[j]);
      if (elements == null || elements.getLength() == 0) {
        continue;
      } else {
        attributes.put(elementNames[j], new HashMap<String, String>());
      }
      Element el = (Element) (elements.item(0));

      String currentTag = el.getTagName();
      nnm = el.getAttributes();
      for (int k = 0; k < nnm.getLength(); k++) {
        attributes.get(currentTag).put(nnm.item(k).getNodeName(), nnm.item(k).getNodeValue());
      }
    }
  }
예제 #2
0
  private final Entry parseEntry(Node n, int entryId, ListContainer list) {
    Node first = n.getFirstChild();
    final Entry entry = new Entry(entryId);

    NamedNodeMap attrs;
    Node att;
    StatsSet set;

    for (n = first; n != null; n = n.getNextSibling()) {
      if ("ingredient".equalsIgnoreCase(n.getNodeName())) {
        attrs = n.getAttributes();
        set = new StatsSet();
        for (int i = 0; i < attrs.getLength(); i++) {
          att = attrs.item(i);
          set.set(att.getNodeName(), att.getNodeValue());
        }
        entry.addIngredient(new Ingredient(set));
      } else if ("production".equalsIgnoreCase(n.getNodeName())) {
        attrs = n.getAttributes();
        set = new StatsSet();
        for (int i = 0; i < attrs.getLength(); i++) {
          att = attrs.item(i);
          set.set(att.getNodeName(), att.getNodeValue());
        }
        entry.addProduct(new Ingredient(set));
      }
    }

    return entry;
  }
예제 #3
0
  /**
   * Removes style attributes from this node and it's children recursively.
   *
   * @param node node being filtered.
   * @param attributeMappings attribute map to be used for filtering.
   */
  private void filter(Node node, Map<String, String> attributeMappings) {
    if (node instanceof Element) {
      Element element = (Element) node;
      String allowedAttributes = attributeMappings.get(element.getNodeName().toLowerCase());
      NamedNodeMap currentAttributes = element.getAttributes();
      if (null == allowedAttributes) {
        // Strip off all attributes.
        while (currentAttributes.getLength() > 0) {
          currentAttributes.removeNamedItem(currentAttributes.item(0).getNodeName());
        }
      } else {
        // Collect those attributes that need to be removed.
        List<String> attributesToBeRemoved = new ArrayList<String>();
        for (int i = 0; i < currentAttributes.getLength(); i++) {
          String attributeName = currentAttributes.item(i).getNodeName();
          String pattern = ATTRIBUTE_SEPARATOR + attributeName.toLowerCase() + ATTRIBUTE_SEPARATOR;
          if (allowedAttributes.indexOf(pattern) == -1) {
            attributesToBeRemoved.add(attributeName);
          }
        }

        // Remove those attributes collected above.
        for (String attribute : attributesToBeRemoved) {
          currentAttributes.removeNamedItem(attribute);
        }
      }
      if (node.hasChildNodes()) {
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
          filter(children.item(i), attributeMappings);
        }
      }
    }
  }
예제 #4
0
 /**
  * 获取该 XML 元素内所有的属性的值,按照Map的形式返回
  *
  * @param ele XML 元素
  * @return 所有属性的值
  */
 public static Map<String, String> getAttrs(Element ele) {
   NamedNodeMap nodeMap = ele.getAttributes();
   Map<String, String> attrs = new HashMap<String, String>(nodeMap.getLength());
   for (int i = 0; i < nodeMap.getLength(); i++) {
     attrs.put(nodeMap.item(i).getNodeName(), nodeMap.item(i).getNodeValue());
   }
   return attrs;
 }
예제 #5
0
  /**
   * Getting Imaging Types used in the Experiment
   *
   * @return a List of Imaging Type entities
   */
  private List<ImagingType> getImagingTypes() {
    List<ImagingType> imagingTypeList = new ArrayList<>();

    // get "Stage loop" nodes
    List<Node> stageLoopNodes = getChildNodeListByAttributeValue(loopNode, "Stage loop");
    // get "Image" nodes
    List<Node> imageNodes = new ArrayList<>();
    for (int i = 0; i < stageLoopNodes.size(); i++) {
      Node imageNode = getChildNodeByAttributeValue(stageLoopNodes.get(i), "Image");
      imageNodes.add(imageNode);
    }

    // create new imaging type entitie(s) and set class members
    for (int i = 0; i < imageNodes.size(); i++) {
      ImagingType imagingType = new ImagingType();
      NodeList imageChildNodes = imageNodes.get(i).getChildNodes();

      // set exposure time value
      NamedNodeMap exposureTimeAttr = imageChildNodes.item(0).getFirstChild().getAttributes();
      for (int j = 0; j < exposureTimeAttr.getLength(); j++) {
        String exposureTimeVal = exposureTimeAttr.item(j).getNodeValue();
        imagingType.setExposureTime(Double.parseDouble(exposureTimeVal));
      }

      // get exposure time unit
      NamedNodeMap exposureTimeUnitAttr = imageChildNodes.item(1).getFirstChild().getAttributes();
      for (int j = 0; j < exposureTimeUnitAttr.getLength(); j++) {
        String nodeValue = exposureTimeUnitAttr.item(j).getNodeValue();
        String expTimeUnit =
            findCycleTimeUnitByValue(Integer.parseInt(nodeValue))
                .toString()
                .toLowerCase(Locale.ENGLISH);
        imagingType.setExposureTimeUnit(expTimeUnit);
      }

      // set name
      NamedNodeMap imageTypeAttr = imageChildNodes.item(4).getFirstChild().getAttributes();
      for (int j = 0; j < imageTypeAttr.getLength(); j++) {
        String imageTypeName = imageTypeAttr.item(j).getNodeValue();
        imagingType.setName(imageTypeName);
      }

      // set light intensity
      Node lampNode = getChildNodeByAttributeValue(loopNode, "ucb.0-lamp_transm.0");
      Node intensityNode = getChildNodeByAttributeValue(lampNode, "intensity");
      NamedNodeMap intensityAttr = intensityNode.getFirstChild().getAttributes();
      for (int j = 0; j < intensityAttr.getLength(); j++) {
        String intensity = intensityAttr.item(j).getNodeValue();
        imagingType.setLightIntensity(Double.parseDouble(intensity) / 10);
      }

      // add imaging type entity to the list
      imagingTypeList.add(imagingType);
    }
    return imagingTypeList;
  }
예제 #6
0
 XmlNode[] getAttributes() {
   NamedNodeMap attrs = this.dom.getAttributes();
   //    TODO    Or could make callers handle null?
   if (attrs == null) throw new IllegalStateException("Must be element.");
   XmlNode[] rv = new XmlNode[attrs.getLength()];
   for (int i = 0; i < attrs.getLength(); i++) {
     rv[i] = createImpl(attrs.item(i));
   }
   return rv;
 }
예제 #7
0
 public static Map<String, String> getAttributes(Node node) {
   NamedNodeMap attributeMap = node.getAttributes();
   HashMap<String, String> attributes = new HashMap<String, String>(attributeMap.getLength());
   for (int i = 0; i < attributeMap.getLength(); i++) {
     Node attr = attributeMap.item(i);
     if (attr instanceof Attr) {
       attributes.put(((Attr) attr).getName(), ((Attr) attr).getValue());
     }
   }
   return attributes;
 }
 /**
  * Initialize a Map of attributes available from the underlying ImageMetadata.
  *
  * @param reader
  */
 private void buildAttributesMap(SpatioTemporalImageReader reader) {
   attributesMap = new HashMap<String, String>();
   IIOMetadata metadata;
   final int imageIndex = getImageIndex();
   try {
     metadata = reader.getImageMetadata(imageIndex);
     if (metadata instanceof GRIB1ImageMetadata) {
       Node root = metadata.getAsTree(GRIB1ImageMetadata.nativeMetadataFormatName);
       if (root != null) {
         Node gdsNode = root.getFirstChild();
         if (gdsNode != null) {
           final NamedNodeMap attributes = gdsNode.getAttributes();
           if (attributes != null) {
             final int numAttributes = attributes.getLength();
             for (int i = 0; i < numAttributes; i++) {
               final Node node = attributes.item(i);
               if (node != null) {
                 attributesMap.put(node.getNodeName(), node.getNodeValue());
               }
             }
           }
         }
         final Node pdsNode = gdsNode.getNextSibling();
         if (pdsNode != null) {
           final NamedNodeMap attributes = pdsNode.getAttributes();
           if (attributes != null) {
             final int numAttributes = attributes.getLength();
             for (int i = 0; i < numAttributes; i++) {
               Node node = attributes.item(i);
               if (node != null) {
                 attributesMap.put(node.getNodeName(), node.getNodeValue());
               }
             }
           }
         }
         final Node pdsLevelNode = pdsNode.getNextSibling();
         if (pdsLevelNode != null) {
           final NamedNodeMap attributes = pdsLevelNode.getAttributes();
           if (attributes != null) {
             final int numAttributes = attributes.getLength();
             for (int i = 0; i < numAttributes; i++) {
               Node node = attributes.item(i);
               if (node != null) {
                 attributesMap.put(node.getNodeName(), node.getNodeValue());
               }
             }
           }
         }
       }
     }
   } catch (IOException e) {
     throw new IllegalArgumentException("Unable parsing metadata");
   }
 }
예제 #9
0
 /** check if two XML nodes are the same, when pattern1 is replaced by pattothersern2 * */
 boolean comparable(Node node1, Node node2, String pattern1, String pattern2) {
   // compare name
   if (!node1.getNodeName().equals(node2.getNodeName())) {
     return false;
   }
   // compare text
   if (!node1.getTextContent().trim().equals(node2.getTextContent().trim())) {
     return false;
   }
   // compare attributes
   NamedNodeMap atts = node1.getAttributes();
   NamedNodeMap atts2 = node2.getAttributes();
   if (atts.getLength() != atts2.getLength()) {
     return false;
   }
   for (int i = 0; i < atts.getLength(); i++) {
     Attr attr = (Attr) atts.item(i);
     String name = attr.getName();
     String valueString = attr.getValue();
     Node att = atts2.getNamedItem(name);
     if (att == null) {
       return false;
     }
     String valueString2 = ((Attr) att).getValue();
     if (!valueString.equals(valueString2)) {
       valueString = valueString.replaceAll(pattern1, "\\$\\(n\\)");
       valueString2 = valueString2.replaceAll(pattern2, "\\$\\(n\\)");
       if (!valueString.equals(valueString2)) {
         return false;
       }
     }
   }
   // compare children
   NodeList children = node1.getChildNodes();
   NodeList children2 = node2.getChildNodes();
   for (int childIndex = 0; childIndex < children.getLength(); childIndex++) {
     Node child = children.item(childIndex);
     if (child.getNodeType() == Node.ELEMENT_NODE) {
       String name = child.getNodeName();
       boolean isMatch = false;
       for (int childIndex2 = 0; !isMatch && childIndex2 < children2.getLength(); childIndex2++) {
         Node child2 = children2.item(childIndex2);
         if (child2.getNodeType() == Node.ELEMENT_NODE && name.equals(child2.getNodeName())) {
           isMatch = comparable(child, child2, pattern1, pattern2);
         }
       }
       if (!isMatch) {
         return false;
       }
     }
   }
   return true;
 } // comparable
예제 #10
0
  public static List<Attr> attributes(Element element) {
    NamedNodeMap attributeMap = element.getAttributes();
    if ((attributeMap == null) || (attributeMap.getLength() == 0)) {
      return Collections.emptyList();
    }

    List<Attr> attributes = new ArrayList<Attr>();
    for (int i = 0; i < attributeMap.getLength(); i++) {
      attributes.add((Attr) attributeMap.item(i));
    }

    return attributes;
  }
  /**
   * Read the attributes of the node state.
   *
   * @param element The element to get the attributes from.
   * @param node The node state to fill.
   */
  private static void readAttributes(org.w3c.dom.Node element, Node node) {
    if (element.getAttributes() != null && element.getAttributes().getLength() != 0) {
      NamedNodeMap attributes = element.getAttributes();

      Collection<NodeAttribute> nodeAttributes = CollectionUtils.newList(attributes.getLength());

      for (int i = 0; i < attributes.getLength(); i++) {
        nodeAttributes.add(
            new NodeAttribute(
                attributes.item(i).getNodeName(), attributes.item(i).getTextContent()));
      }

      node.setAttributes(nodeAttributes);
    }
  }
예제 #12
0
 /**
  * Check SOS response for xsi:schemaLocation, remove attribute and add attribute to SOAP message
  *
  * @param xmlObject
  * @param soapResponseMessage SOAP response message
  * @throws SOAPException If an error occurs
  */
 private void addAndRemoveSchemaLocationForSOAP(
     XmlObject xmlObject, SOAPMessage soapResponseMessage) throws SOAPException {
   String value = null;
   Node nodeToRemove = null;
   NamedNodeMap attributeMap = xmlObject.getDomNode().getFirstChild().getAttributes();
   for (int i = 0; i < attributeMap.getLength(); i++) {
     Node node = attributeMap.item(i);
     if (node.getLocalName().equals(W3CConstants.AN_SCHEMA_LOCATION)) {
       value = node.getNodeValue();
       nodeToRemove = node;
     }
   }
   if (nodeToRemove != null) {
     attributeMap.removeNamedItem(nodeToRemove.getNodeName());
   }
   SOAPEnvelope envelope = soapResponseMessage.getSOAPPart().getEnvelope();
   StringBuilder string = new StringBuilder();
   string.append(envelope.getNamespaceURI());
   string.append(BLANK_CHAR);
   string.append(envelope.getNamespaceURI());
   if (value != null && !value.isEmpty()) {
     string.append(BLANK_CHAR);
     string.append(value);
   }
   envelope.addAttribute(N52XmlHelper.getSchemaLocationQNameWithPrefix(), string.toString());
 }
예제 #13
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", "");
    }
  }
 /*
  * @see com.sun.org.apache.xml.internal.utils.PrefixResolverDefault
  */
 protected String inferNamespaceURI(String prefix) {
   Node parent = namespaceContext;
   String namespace = null;
   int type;
   while ((null != parent)
       && (null == namespace)
       && (((type = parent.getNodeType()) == Node.ELEMENT_NODE)
           || (type == Node.ENTITY_REFERENCE_NODE))) {
     if (type == Node.ELEMENT_NODE) {
       if (parent.getNodeName().indexOf(prefix + ":") == 0) {
         return parent.getNamespaceURI();
       }
       NamedNodeMap nnm = parent.getAttributes();
       for (int i = 0; i < nnm.getLength(); i++) {
         Node attr = nnm.item(i);
         String aname = attr.getNodeName();
         boolean isPrefix = aname.startsWith("xmlns:");
         if (isPrefix || aname.equals("xmlns")) {
           int index = aname.indexOf(':');
           String p = isPrefix ? aname.substring(index + 1) : "";
           if (p.equals(prefix)) {
             namespace = attr.getNodeValue();
             break;
           }
         }
       }
     }
     parent = parent.getParentNode();
   }
   return namespace;
 }
예제 #15
0
 /**
  * Internal method used to copy from manifest Application to PhoneLabApplication class instance
  *
  * @param app
  * @param element
  */
 private void copyApp(PhoneLabApplication app, Element element) {
   NamedNodeMap map = element.getAttributes();
   for (int i = 0; i < map.getLength(); i++) {
     Node attr = map.item(i);
     if (attr.getNodeName().equals("intent_name")) {
       app.setIntentName(attr.getNodeValue());
     } else if (attr.getNodeName().equals("package_name")) {
       app.setPackageName(attr.getNodeValue());
     } else if (attr.getNodeName().equals("name")) {
       app.setName(attr.getNodeValue());
     } else if (attr.getNodeName().equals("description")) {
       app.setDescription(attr.getNodeValue());
     } else if (attr.getNodeName().equals("type")) {
       app.setType(attr.getNodeValue());
     } else if (attr.getNodeName().equals("participantinitiated")) {
       if (attr.getNodeValue().equals("yes")) app.setParticipantInitiated(true);
       else app.setParticipantInitiated(false);
     } else if (attr.getNodeName().equals("download")) {
       app.setDownload(attr.getNodeValue());
     } else if (attr.getNodeName().equals("version")) {
       app.setVersion(attr.getNodeValue());
     } else if (attr.getNodeName().equals("action")) {
       app.setAction(attr.getNodeValue());
     }
   }
 }
예제 #16
0
  void displayMetadata(Node node, int level) {
    // print open tag of element
    indent(level);
    System.out.print("<" + node.getNodeName());
    NamedNodeMap map = node.getAttributes();
    if (map != null) {

      // print attribute values
      int length = map.getLength();
      for (int i = 0; i < length; i++) {
        Node attr = map.item(i);
        System.out.print(" " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"");
      }
    }

    Node child = node.getFirstChild();
    if (child == null) {
      // no children, so close element and return
      System.out.println("/>");
      return;
    }

    // children, so close current tag
    System.out.println(">");
    while (child != null) {
      // print children recursively
      displayMetadata(child, level + 1);
      child = child.getNextSibling();
    }

    // print close tag of element
    indent(level);
    System.out.println("</" + node.getNodeName() + ">");
  }
예제 #17
0
  public static void Clone(Element root, Element src) {
    Document doc = root.getOwnerDocument();
    NodeList nodes = src.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
      Node node = nodes.item(i);
      int nodeType = node.getNodeType();
      switch (nodeType) {
        case Node.TEXT_NODE:
          root.appendChild(doc.createTextNode(node.getNodeValue()));
          break;
        case Node.ELEMENT_NODE:
          Element _element = doc.createElement(node.getNodeName());
          // clone attribute
          NamedNodeMap attrs = node.getAttributes();
          for (int j = 0; j < attrs.getLength(); j++) {
            Node attr = attrs.item(j);
            _element.setAttribute(attr.getNodeName(), attr.getNodeValue());
          }

          // clone children
          Clone(_element, (Element) node);
          root.appendChild(_element);
          break;
      }
    }
  }
예제 #18
0
  private void gatherNamespaces(Element element, List<URI> namespaceSources) throws SAXException {
    NamedNodeMap attributes = element.getAttributes();
    int attributeCount = attributes.getLength();

    for (int i = 0; i < attributeCount; i++) {
      Attr attribute = (Attr) attributes.item(i);
      String namespace = attribute.getNamespaceURI();

      if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespace)) {
        try {
          namespaceSources.add(new URI(attribute.getValue()));
        } catch (URISyntaxException e) {
          throw new SAXException(
              "Cannot validate this document with this class.  Namespaces must be valid URIs.  Found Namespace: '"
                  + attribute.getValue()
                  + "'.",
              e);
        }
      }
    }

    NodeList childNodes = element.getChildNodes();
    int childCount = childNodes.getLength();
    for (int i = 0; i < childCount; i++) {
      Node child = childNodes.item(i);

      if (child.getNodeType() == Node.ELEMENT_NODE) {
        gatherNamespaces((Element) child, namespaceSources);
      }
    }
  }
예제 #19
0
 @Override
 public void init(Element element) {
   final Element settingsElement = (Element) element.getElementsByTagName("settings").item(0);
   final NamedNodeMap attributes = settingsElement.getAttributes();
   for (int i = 0; i < attributes.getLength(); i++) {
     final Node node = attributes.item(i);
     if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
       final Attr attr = (Attr) node;
       this.params.put(attr.getName(), Float.parseFloat(attr.getValue()));
     }
   }
   final float top = this.params.get("top");
   final float left = this.params.get("left");
   final float bottom = this.params.get("bottom");
   final float right = this.params.get("right");
   final float bWidth = this.params.get("blockWidth");
   final float bHeight = this.params.get("blockHeight");
   final List<XYZItem> truc = new LinkedList<XYZItem>();
   for (float x = left; x < right; x += bWidth) {
     for (float y = bottom; y < top; y += bHeight) {
       truc.add(new XYZItem(x, y, getZValue(x, y)));
     }
   }
   this.map = new double[3][truc.size()];
   int i = 0;
   for (XYZItem item : truc) {
     this.map[0][i] = item.getXValue();
     this.map[1][i] = item.getYValue();
     this.map[2][i] = item.getZValue();
     i++;
   }
 }
예제 #20
0
  // Walk the tree from a specified element,
  // inserting data from a DicomObject where required.
  private static String getElementText(Element element, DicomObject dicomObject) {

    if (dicomTag(element)) return getDicomElementText(element, dicomObject);

    if (element.getTagName().equals("block")) return getBlockText(element, dicomObject);

    StringBuffer sb = new StringBuffer();
    sb.append("<" + element.getTagName());
    NamedNodeMap attributes = element.getAttributes();
    Attr attr;
    for (int i = 0; i < attributes.getLength(); i++) {
      attr = (Attr) attributes.item(i);
      String attrValue = attr.getValue().trim();
      if (dicomTag(attrValue)) {
        attrValue = getDicomElementText(attrValue, dicomObject);
      }
      sb.append(" " + attr.getName() + "=\"" + attrValue + "\"");
    }
    sb.append(">");
    if (element.getTagName().equals("table")) sb.append(getTableText(element, dicomObject));
    else if (element.getTagName().equals("publication-date")) sb.append(StringUtil.getDate());
    else sb.append(getChildrenText(element, dicomObject));
    sb.append("</" + element.getTagName() + ">");
    return sb.toString();
  }
예제 #21
0
    Shuttle(Shuttle cp, Element e) {
      this.node = e;
      this.g = cp.g;
      this.svgRoot = cp.svgRoot;
      this.shape = cp.shape;
      this.clip = cp.clip;
      this.fontSize = cp.fontSize;
      this.fontFamily = cp.fontFamily;
      this.stroke = cp.stroke;
      this.fill = cp.fill;
      this.strokeWidth = cp.strokeWidth;
      this.transform = new AffineTransform(cp.transform);
      this.opacity = cp.opacity;
      if (e.hasAttributes()) {
        NamedNodeMap atts = e.getAttributes();
        for (int i = 0; i < atts.getLength(); ++i) {

          Attr att = Attr.class.cast(atts.item(i));
          if (att.getNamespaceURI() != null) continue;
          String s = att.getName();
          String value = att.getValue();
          if (s.equals("style")) {
            for (String styles : value.split("[;]+")) {
              int j = styles.indexOf(':');
              if (j != -1) {
                applyStyle(styles.substring(0, j).trim(), styles.substring(j + 1).trim());
              }
            }

          } else {
            applyStyle(s, att.getValue());
          }
        }
      }
    }
예제 #22
0
  @Override
  public void relink_namespace(ThreadContext context) {
    Element e = (Element) node;

    e.getOwnerDocument().renameNode(e, e.lookupNamespaceURI(e.getPrefix()), e.getNodeName());

    if (e.hasAttributes()) {
      NamedNodeMap attrs = e.getAttributes();

      for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr = (Attr) attrs.item(i);
        String nsUri = "";
        String prefix = attr.getPrefix();
        String nodeName = attr.getNodeName();
        if ("xml".equals(prefix)) {
          nsUri = "http://www.w3.org/XML/1998/namespace";
        } else if ("xmlns".equals(prefix) || nodeName.equals("xmlns")) {
          nsUri = "http://www.w3.org/2000/xmlns/";
        } else {
          nsUri = attr.lookupNamespaceURI(nodeName);
        }

        e.getOwnerDocument().renameNode(attr, nsUri, nodeName);
      }
    }

    if (e.hasChildNodes()) {
      ((XmlNodeSet) children(context)).relink_namespace(context);
    }
  }
예제 #23
0
  /**
   * Returns a sorted list of attributes.
   *
   * @param attrs Description of the Parameter
   * @return Description of the Return Value
   */
  protected Attr[] sortAttributes(NamedNodeMap attrs) {

    int len = (attrs != null) ? attrs.getLength() : 0;
    Attr array[] = new Attr[len];
    for (int i = 0; i < len; i++) {
      array[i] = (Attr) attrs.item(i);
    }

    for (int i = 0; i < len - 1; i++) {
      String name = array[i].getNodeName();
      int index = i;
      for (int j = i + 1; j < len; j++) {
        String curName = array[j].getNodeName();
        if (curName.compareTo(name) < 0) {
          name = curName;
          index = j;
        }
      }
      if (index != i) {
        Attr temp = array[i];
        array[i] = array[index];
        array[index] = temp;
      }
    }

    return array;
  }
예제 #24
0
  /**
   * Convert a <table> node from the xml into an HTableDescriptor (with its column families)
   */
  private HTableDescriptor getTable(Node tableNode) {
    NamedNodeMap tableAttributes = tableNode.getAttributes();
    String tableName = tableAttributes.getNamedItem(TABLE_NAME_ATTRIBUTE).getNodeValue();
    HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);
    for (int x = 0; x < tableAttributes.getLength(); x++) {
      Node attr = tableAttributes.item(x);
      if (!attr.getNodeName().equalsIgnoreCase(TABLE_NAME_ATTRIBUTE)) { // skip name, already got it
        setAttributeValue(tableDescriptor, attr.getNodeName(), attr.getNodeValue());
      }
    }

    applyMissingTableDefaults(tableDescriptor);

    // parse the column families
    NodeList tableChildren = tableNode.getChildNodes();
    for (int x = 0; x < tableChildren.getLength(); x++) {
      Node tableChild = tableChildren.item(x);
      if (tableChild.getNodeName().equals(COLUMN_FAMILIES_ELEMENT)) {
        for (HColumnDescriptor family : getColumnFamilies(tableChild)) {
          tableDescriptor.addFamily(family);
        }
      }
    }

    // push this entire subtree of the xml file into the table metadata as the table's schema
    tableDescriptor.setValue(FULL_SCHEMA_PROPERTY, getFullXML(tableNode));

    validateTableDefinition(tableDescriptor);

    return tableDescriptor;
  }
  /**
   * Show a node as a string
   *
   * @param node
   * @param tabs
   * @return
   */
  String toString(Node node) {
    StringBuilder sb = new StringBuilder();

    // ---
    // Get name & value
    // ---
    String name = node.getNodeName();
    String value = node.getNodeValue();
    if (value != null) value = value.replace('\n', ' ').trim();
    sb.append(name);

    // ---
    // Get attributes
    // ---
    NamedNodeMap map = node.getAttributes();
    if (map != null) {
      sb.append("( ");
      for (int i = 0; i < map.getLength(); i++) {
        Node attr = map.item(i);
        String aname = attr.getNodeName();
        String aval = attr.getNodeValue();

        if (i > 0) sb.append(", ");
        sb.append(aname + "='" + aval + "'");
      }
      sb.append(" )");
    }

    if (value != null) sb.append(" = '" + value + "'\n");

    return sb.toString();
  }
예제 #26
0
  /** Convert a <columnFamilies> node to a set of HColumnDescriptors */
  private Set<HColumnDescriptor> getColumnFamilies(Node columnFamiliesNode) {
    final Set<HColumnDescriptor> result = new HashSet<HColumnDescriptor>();

    NodeList columnFamilies = columnFamiliesNode.getChildNodes();
    for (int x = 0; x < columnFamilies.getLength(); x++) {
      Node columnFamily = columnFamilies.item(x);
      if (columnFamily.getNodeName().equals(COLUMN_FAMILY_ELEMENT)) {
        NamedNodeMap columnFamilyAttributes = columnFamily.getAttributes();
        String familyName =
            columnFamilyAttributes.getNamedItem(COLUMN_FAMILY_NAME_ATTRIBUTE).getNodeValue();
        HColumnDescriptor cf = new HColumnDescriptor(familyName);
        for (int y = 0; y < columnFamilyAttributes.getLength(); y++) {
          Node attr = columnFamilyAttributes.item(y);
          if (!attr.getNodeName()
              .equalsIgnoreCase(COLUMN_FAMILY_NAME_ATTRIBUTE)) { // skip name, already got it
            setAttributeValue(cf, attr.getNodeName(), attr.getNodeValue());
          }
        }
        applyMissingColumnFamilyDefaults(cf);
        validateColumnFamily(cf);
        result.add(cf);
      }
    }
    return result;
  }
예제 #27
0
 private String nodeToString(final Element elem) {
   final StringBuffer stringBuffer = new StringBuffer();
   stringBuffer.append(Constants.LESS_THAN).append(elem.getNodeName());
   final NamedNodeMap namedNodeMap = elem.getAttributes();
   for (int i = 0; i < namedNodeMap.getLength(); i++) {
     stringBuffer
         .append(Constants.STRING_BLANK)
         .append(namedNodeMap.item(i).getNodeName())
         .append(Constants.EQUAL)
         .append(Constants.QUOTATION + namedNodeMap.item(i).getNodeValue() + Constants.QUOTATION);
   }
   stringBuffer.append(Constants.GREATER_THAN);
   final NodeList nodeList = elem.getChildNodes();
   for (int i = 0; i < nodeList.getLength(); i++) {
     final Node node = nodeList.item(i);
     if (node.getNodeType() == Node.ELEMENT_NODE) {
       // If the type of current node is ELEMENT_NODE, process it
       stringBuffer.append(nodeToString((Element) node));
     }
     if (node.getNodeType() == Node.TEXT_NODE) {
       stringBuffer.append(node.getNodeValue());
     }
   }
   stringBuffer.append("</").append(elem.getNodeName()).append(Constants.GREATER_THAN);
   return stringBuffer.toString();
 }
  /**
   * Check if the attribute of a tag is in a list of allowed attribute names.
   *
   * @param element the tag element
   * @param attributeNames the allowed attribute names
   * @throws EoulsanException if an attribute of the tag in not in the allowed attribute list
   */
  private static void checkAllowedAttributes(final Element element, String... attributeNames)
      throws EoulsanException {

    final List<String> attributeList = Arrays.asList(attributeNames);

    final NamedNodeMap nnm = element.getAttributes();

    for (int i = 0; i < nnm.getLength(); i++) {

      final Node n = nnm.item(i);

      if (n.getNodeType() == Node.ATTRIBUTE_NODE) {

        final String attributeName = n.getNodeName();

        if (!attributeList.contains(attributeName)) {
          throw new EoulsanException(
              "the \""
                  + element.getNodeName()
                  + "\" tag contains an unknown attribute: "
                  + attributeName
                  + ".");
        }
      }
    }
  }
예제 #29
0
  void handleParent(Element e, NameSpaceSymbTable ns) {
    if (!e.hasAttributes()) {
      return;
    }
    xmlattrStack.push(-1);
    NamedNodeMap attrs = e.getAttributes();
    int attrsLength = attrs.getLength();
    for (int i = 0; i < attrsLength; i++) {
      Attr N = (Attr) attrs.item(i);
      if (Constants.NamespaceSpecNS != N.getNamespaceURI()) {
        // Not a namespace definition, ignore.
        if (XML_LANG_URI == N.getNamespaceURI()) {
          xmlattrStack.addXmlnsAttr(N);
        }
        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);
    }
  }
예제 #30
0
  public static void readXpath()
      throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("D:\\temp\\test_2\\screen_2.xml");
    XPath xpath = XPathFactory.newInstance().newXPath();
    // XPath Query for showing all nodes value
    // XPathExpression expr = xpath
    // .compile("//Screens/Screen[@number='1']/Button[@number='1']/Action[@type='onclick']/*");
    String xpathStr = "//Screen[@number='2007']/Button[@number='87'][@h='1']";
    XPathExpression expr = xpath.compile(xpathStr);

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
      NamedNodeMap nodeMap = nodes.item(i).getAttributes();
      String attrName = "";
      for (int j = 0; j < nodeMap.getLength(); j++) {
        attrName = xpathStr.substring(xpathStr.lastIndexOf('@') + 1, xpathStr.lastIndexOf("="));
        if (nodes.item(i).getAttributes().item(j).getNodeName().equals(attrName)) {
          System.out.println(nodes.item(i).getAttributes().item(j).getNodeValue());
        }
      }
    }
  }