Exemplo n.º 1
0
  @Override
  public void parseDocument(Document doc, File f) {
    try {
      int id = Integer.parseInt(f.getName().replaceAll(".xml", ""));
      int entryId = 1;
      Node att;
      final ListContainer list = new ListContainer(id);

      for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ("list".equalsIgnoreCase(n.getNodeName())) {
          att = n.getAttributes().getNamedItem("applyTaxes");
          list.setApplyTaxes((att != null) && Boolean.parseBoolean(att.getNodeValue()));

          att = n.getAttributes().getNamedItem("useRate");
          if (att != null) {
            try {

              list.setUseRate(Double.valueOf(att.getNodeValue()));
              if (list.getUseRate() <= 1e-6) {
                throw new NumberFormatException(
                    "The value cannot be 0"); // threat 0 as invalid value
              }
            } catch (NumberFormatException e) {
              try {
                list.setUseRate(Config.class.getField(att.getNodeValue()).getDouble(Config.class));
              } catch (Exception e1) {
                LOG.warn(
                    "{}: Unable to parse {}", getClass().getSimpleName(), doc.getLocalName(), e1);
                list.setUseRate(1.0);
              }

            } catch (DOMException e) {
              LOG.warn("{}: Unable to parse {}", getClass().getSimpleName(), doc.getLocalName(), e);
            }
          }

          att = n.getAttributes().getNamedItem("maintainEnchantment");
          list.setMaintainEnchantment((att != null) && Boolean.parseBoolean(att.getNodeValue()));

          for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
            if ("item".equalsIgnoreCase(d.getNodeName())) {
              Entry e = parseEntry(d, entryId++, list);
              list.getEntries().add(e);
            } else if ("npcs".equalsIgnoreCase(d.getNodeName())) {
              for (Node b = d.getFirstChild(); b != null; b = b.getNextSibling()) {
                if ("npc".equalsIgnoreCase(b.getNodeName())) {
                  if (Util.isDigit(b.getTextContent())) {
                    list.allowNpc(Integer.parseInt(b.getTextContent()));
                  }
                }
              }
            }
          }
        }
      }
      _entries.put(id, list);
    } catch (Exception e) {
      LOG.error("{}: Error in file {}", getClass().getSimpleName(), f, e);
    }
  }
Exemplo n.º 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;
  }
  /**
   * 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();
  }
Exemplo n.º 4
0
  /**
   * Handle text node during validation.
   *
   * @param received
   * @param source
   */
  private void doText(Node received, Node source) {
    if (log.isDebugEnabled()) {
      log.debug("Validating node value for element: " + received.getParentNode());
    }

    if (received.getNodeValue() != null) {
      Assert.isTrue(
          source.getNodeValue() != null,
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              null,
              received.getNodeValue().trim()));

      Assert.isTrue(
          received.getNodeValue().trim().equals(source.getNodeValue().trim()),
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              source.getNodeValue().trim(),
              received.getNodeValue().trim()));
    } else {
      Assert.isTrue(
          source.getNodeValue() == null,
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              source.getNodeValue().trim(),
              null));
    }

    if (log.isDebugEnabled()) {
      log.debug("Node value '" + received.getNodeValue().trim() + "': OK");
    }
  }
Exemplo n.º 5
0
  /**
   * Writes a DOM tree to a stream.
   *
   * @param element the Root DOM element of the tree
   * @param out where to send the output
   * @param indent number of
   * @param indentWith string that should be used to indent the corresponding tag.
   * @throws IOException if an error happens while writing to the stream.
   */
  public void write(Element element, Writer out, int indent, String indentWith) throws IOException {

    // Write child elements and text
    NodeList children = element.getChildNodes();
    boolean hasChildren = (children.getLength() > 0);
    boolean hasChildElements = false;
    openElement(element, out, indent, indentWith, hasChildren);

    if (hasChildren) {
      for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);

        switch (child.getNodeType()) {
          case Node.ELEMENT_NODE:
            hasChildElements = true;
            if (i == 0) {
              out.write(lSep);
            }
            write((Element) child, out, indent + 1, indentWith);
            break;

          case Node.TEXT_NODE:
            out.write(encode(child.getNodeValue()));
            break;

          case Node.COMMENT_NODE:
            out.write("<!--");
            out.write(encode(child.getNodeValue()));
            out.write("-->");
            break;

          case Node.CDATA_SECTION_NODE:
            out.write("<![CDATA[");
            encodedata(out, ((Text) child).getData());
            out.write("]]>");
            break;

          case Node.ENTITY_REFERENCE_NODE:
            out.write('&');
            out.write(child.getNodeName());
            out.write(';');
            break;

          case Node.PROCESSING_INSTRUCTION_NODE:
            out.write("<?");
            out.write(child.getNodeName());
            String data = child.getNodeValue();
            if (data != null && data.length() > 0) {
              out.write(' ');
              out.write(data);
            }
            out.write("?>");
            break;
          default:
            // Do nothing
        }
      }
      closeElement(element, out, indent, indentWith, hasChildElements);
    }
  }
Exemplo n.º 6
0
  public String GetChildPlainContent(Node myNode) {
    String parsedString = "";
    try {
      if (myNode.hasChildNodes()) {
        NodeList subNodes = myNode.getChildNodes();
        for (int c = 0; c < subNodes.getLength(); c++) {
          Node innerNode = subNodes.item(c);
          if (innerNode.getNodeName().equalsIgnoreCase("#text")) {
            parsedString += innerNode.getNodeValue().toString();
          }
          if (innerNode.hasChildNodes()) {
            if (innerNode.getFirstChild().getNodeName().equalsIgnoreCase("#text")) {
              parsedString += innerNode.getFirstChild().getNodeValue().toString();
            }
          }
        }
      }

      if (myNode.getNodeName().equalsIgnoreCase("#text")) {
        parsedString += myNode.getNodeValue().toString();
      }
      // parsedString = c.replaceAll(parsedString, "\r", "");
      // parsedString = c.replaceAll(parsedString, "\n", "");
      return parsedString;

    } catch (Exception e) {
      return parsedString;
    }
  }
Exemplo n.º 7
0
  /** Get value of a given node. */
  public static String getNodeValue(final Element node) {
    if (node == null) return null;
    final String result = node.getNodeValue();
    if (result != null) return result;

    final NodeList list = node.getChildNodes();
    if (list == null || list.getLength() == 0) return null;
    final StringBuffer buff = new StringBuffer();
    boolean counter = false;

    for (int k = 0, listCount = list.getLength(); k < listCount; k++) {
      final Node child = list.item(k);
      if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) {
        buff.append(child.getNodeValue());
        counter = true;
      } else if (child.getNodeType() == Node.ENTITY_REFERENCE_NODE
          || child.getNodeType() == Node.ENTITY_NODE) {
        final Node child2 = child.getFirstChild();
        if (child2 != null && child2.getNodeValue() != null) buff.append(child2.getNodeValue());
        counter = true;
      }
    }

    if (counter == false) return null;
    return buff.toString();
  }
Exemplo n.º 8
0
  /**
   * This method evaluates the xpath expression on the supplied node. The result can either be a
   * document fragment, a text node value or null if the expression references a missing part of the
   * document.
   *
   * @param xpath The xpath expression
   * @param node The node
   * @return The result, or null if not found (which may be due to an expression error)
   */
  public static String evaluate(String xpath, Object node) {
    Node domNode = getNode(node);

    if (domNode == null) {
      log.severe("Unable to evaluate non DOM Node object");
      return null;
    }

    // If no xpath expression, then serialize
    if (xpath == null || xpath.trim().length() == 0) {
      return serialize(node);
    }

    // TODO: HWKBTM-104 Investigate caching compiled xpath expressions
    try {
      xpath = getExpression(xpath);
      XPath xp = XPathFactory.newInstance().newXPath();
      Node result = (Node) xp.evaluate(xpath, domNode, XPathConstants.NODE);

      if (result != null) {
        if (result.getNodeType() == Node.TEXT_NODE) {
          return result.getNodeValue();
        } else if (result.getNodeType() == Node.ATTRIBUTE_NODE) {
          return result.getNodeValue();
        }
        return serialize(result);
      }
    } catch (Exception e) {
      log.log(Level.SEVERE, "Failed to evaluate xpath '" + xpath + "'", e);
    }

    return null;
  }
Exemplo n.º 9
0
  protected void transferAttributes(
      Element source, Element result, java.util.List nonTransferList) {
    boolean debug = false;
    NamedNodeMap sourceAttrNodeMap = source.getAttributes();
    if (sourceAttrNodeMap == null) return;

    NamedNodeMap resultAttrNodeMap = result.getAttributes();

    for (int index = 0; index < sourceAttrNodeMap.getLength(); index++) {
      Node sourceAttrNode = sourceAttrNodeMap.item(index);
      if (!this.canTransferAttribute(sourceAttrNode.getNodeName(), nonTransferList)) continue;
      if (!isValidAttributeToTransfer(
          sourceAttrNode.getNodeName(), getAttributeListForElement(result.getTagName()))) continue;
      if (resultAttrNodeMap == null) {
        Attr addAttr = result.getOwnerDocument().createAttribute(sourceAttrNode.getNodeName());
        addAttr.setValue(sourceAttrNode.getNodeValue());
        result.setAttributeNode(addAttr);
      } else {
        Node resultAttrNode = resultAttrNodeMap.getNamedItem(sourceAttrNode.getNodeName());
        if (resultAttrNode != null) {
          resultAttrNode.setNodeValue(sourceAttrNode.getNodeValue());
          // result.setAttributeNode((Attr)resultAttrNode);
        } else {
          Attr addAttr = result.getOwnerDocument().createAttribute(sourceAttrNode.getNodeName());
          addAttr.setValue(sourceAttrNode.getNodeValue());
          result.setAttributeNode(addAttr);
        }
      }
    }
  }
Exemplo n.º 10
0
 private void prepareByFile(final File file) throws Exception {
   NodeList sourceDocChildNodes = getDocumentBuilder(file);
   for (int i = 0; i < sourceDocChildNodes.getLength(); i++) {
     NodeList childNodes2 = sourceDocChildNodes.item(i).getChildNodes();
     for (int j = 0; j < childNodes2.getLength(); j++) {
       NamedNodeMap attributes = childNodes2.item(j).getAttributes();
       if (attributes != null && attributes.getNamedItem("name") != null) {
         Node node = childNodes2.item(j).getAttributes().getNamedItem("name");
         Node clone = childNodes2.item(j).cloneNode(true);
         String keyMatch = getKeyMatchingNode(node, config.getKeys());
         String keyException = getKeysByValue(config.getExceptions(), node.getNodeValue());
         String addKey = MergeConfig.COMMON_XSD;
         if (isMatchingNodeBase(node, config.getBase())) {
           addKey = MergeConfig.DATATYPE_XSD;
         } else if (isMatchingDateTime(node)) {
           addKey = MergeConfig.DATETIME_XSD;
         } else if (StringUtils.isNotBlank(keyException)) {
           addKey = keyException;
         } else if (isMatchingCode(node)) {
           addKey = MergeConfig.CODETYPE_XSD;
         } else if (isMatchingAdress(node)) {
           addKey = MergeConfig.ADDRTYPE_XSD;
         } else if (keyMatch != null) {
           addKey = keyMatch;
         }
         mapNodes.get(addKey).addNode(node.getNodeValue(), clone, null);
         mapNodesKey.put(node.getNodeValue(), getPrefixByKey(addKey));
       }
     }
   }
 }
Exemplo n.º 11
0
  private void encodeElements(String encoding, Element element, boolean applyBase64) {
    if (element.hasChildNodes()) {

      NodeList childNodes = element.getChildNodes();

      for (int i = 0; i < childNodes.getLength(); i++) {
        Node node = childNodes.item(i);
        if (node.getNodeType() == node.ELEMENT_NODE) {
          this.encodeElements(encoding, (Element) node, applyBase64);
        } else if (node.getNodeType() == node.TEXT_NODE) {
          if (applyBase64) {
            try {
              byte[] bytes = base64.decode(node.getNodeValue());
              String decodedString = new String(bytes, encoding);
              node.setNodeValue(decodedString);
            } catch (Exception exp) {
            }
          } else {
            try {
              byte[] bytes = node.getNodeValue().getBytes(encoding);
              String decodedString = new String(bytes);
              node.setNodeValue(decodedString);
            } catch (Exception epx) {
            }
          }
        }
      }
    }
  }
  /**
   * Reads XML that contains the specifications of a given device.
   *
   * @return {@link LayoutDevicesType} representing the device read.
   * @throws ParserConfigurationException
   * @throws SAXException
   * @throws IOException
   */
  public LayoutDevicesType read() throws ParserConfigurationException, SAXException, IOException {
    LayoutDevicesType layoutDevicesType = ObjectFactory.getInstance().createLayoutDevicesType();

    NodeList deviceList = document.getElementsByTagName(D_DEVICE);
    for (int i = 0; i < deviceList.getLength(); i++) {
      Node deviceNode = deviceList.item(i);
      NamedNodeMap deviceNodeAttrs = deviceNode.getAttributes();

      Node deviceIdAtr = deviceNodeAttrs.getNamedItem("id");
      if ((deviceIdAtr != null) && !deviceIdAtr.getNodeValue().trim().equals("")) // $NON-NLS-1$
      {
        // add device
        Device dev = new Device();
        dev.setId(deviceIdAtr.getNodeValue());

        dev.setName(extractValueFromAttributes(deviceNodeAttrs, "name"));
        dev.setProvider(extractValueFromAttributes(deviceNodeAttrs, "provider"));

        NodeList defaultOrConfigList = deviceNode.getChildNodes();
        for (int j = 0; j < defaultOrConfigList.getLength(); j++) {
          Node defaultOrConfigNode = defaultOrConfigList.item(j);
          if ((defaultOrConfigNode != null)
              && (defaultOrConfigNode.getNodeType() == Node.ELEMENT_NODE)) {
            if (defaultOrConfigNode.getNodeName().equalsIgnoreCase(D_SUPPORTED_FEATURES)) {
              NodeList paramsList = defaultOrConfigNode.getChildNodes();
              for (int z = 0; z < paramsList.getLength(); z++) {
                Node supportedFeatureNode = paramsList.item(z);
                if ((supportedFeatureNode != null)
                    && (supportedFeatureNode.getNodeType() == Node.ELEMENT_NODE)) {
                  Node valueNode = supportedFeatureNode.getFirstChild();
                  String supportedFeatureValue = valueNode.getNodeValue();
                  if ((supportedFeatureValue != null) && !supportedFeatureValue.equals("")) {
                    dev.getSupportedFeatures().add(new Feature(supportedFeatureValue));
                  }
                }
              }
            } else {
              boolean isDefault = defaultOrConfigNode.getNodeName().equalsIgnoreCase(D_DEFAULT);
              ParametersType paramTypes = extractParamTypes(defaultOrConfigNode, isDefault);
              if (!(paramTypes instanceof ConfigType)) {
                // default
                dev.setDefault(paramTypes);
              } else {
                // config
                NamedNodeMap configAttrs = defaultOrConfigNode.getAttributes();
                Node configAtr = configAttrs.getNamedItem("name");
                if ((configAtr != null) && !configAtr.getNodeValue().trim().equals("")) {
                  ConfigType type = (ConfigType) paramTypes;
                  type.setName(configAtr.getNodeValue());
                  dev.addConfig(type);
                }
              }
            }
          }
        }
        layoutDevicesType.getDevices().add(dev);
      }
    }
    return layoutDevicesType;
  }
Exemplo n.º 13
0
 /**
  * Read a Map from the given input stream . The returned Map will always have a String key and a
  * List of one or more mapped values (also Strings).
  *
  * @param input An InputStream.
  * @return A Map read from the input stream.
  * @throws IOException If any I/O error occures.
  * @throws ParserConfigurationException
  * @throws SAXException
  */
 public static Map readMap(InputSource input)
     throws IOException, ParserConfigurationException, SAXException {
   Map map = new HashMap();
   DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   Document dom = builder.parse(input);
   NodeList keys = dom.getElementsByTagName(MapXMLWriter.KEY_TAG);
   for (int i = 0; i < keys.getLength(); i++) {
     Node node = keys.item(i);
     NamedNodeMap attributes = node.getAttributes();
     if (attributes != null) {
       Node keyName = attributes.getNamedItem(MapXMLWriter.NAME_TAG);
       if (keyName != null) {
         String key = keyName.getNodeValue();
         NodeList values = node.getChildNodes();
         List valuesList = new ArrayList(values.getLength());
         for (int j = 0; j < values.getLength(); j++) {
           Node valueNode = values.item(j);
           if (valueNode.getNodeType() == Node.ELEMENT_NODE) {
             valueNode = valueNode.getFirstChild();
             if (valueNode != null) {
               valuesList.add(valueNode.getNodeValue());
             }
           }
         }
         map.put(key, valuesList);
       }
     }
   }
   return map;
 }
Exemplo n.º 14
0
  private static final boolean GetBooleanTagValue(
      final org.w3c.dom.Element eTag, final java.lang.String strTag) throws java.lang.Exception {
    if (null == eTag || null == strTag || null == eTag.getElementsByTagName(strTag))
      throw new java.lang.Exception("Cannot get bool value for <" + strTag + ">");

    org.w3c.dom.NodeList nl = eTag.getElementsByTagName(strTag);

    if (null == nl.item(0) || !(nl.item(0) instanceof org.w3c.dom.Element))
      throw new java.lang.Exception("Cannot get bool value for <" + strTag + ">");

    org.w3c.dom.Element elem = (org.w3c.dom.Element) nl.item(0);

    if (null == elem
        || null == elem.getChildNodes()
        || null == elem.getChildNodes().item(0)
        || !(elem.getChildNodes().item(0) instanceof org.w3c.dom.Node))
      throw new java.lang.Exception("Cannot get bool value for <" + strTag + ">");

    org.w3c.dom.Node node = elem.getChildNodes().item(0);

    if (null == node || null == node.getNodeValue())
      throw new java.lang.Exception("Cannot get bool value for <" + strTag + ">");

    return new java.lang.Boolean(node.getNodeValue()).booleanValue();
  }
Exemplo n.º 15
0
  TableMeta(Node tableNode) {
    NamedNodeMap attribs = tableNode.getAttributes();

    name = attribs.getNamedItem("name").getNodeValue();

    Node commentNode = attribs.getNamedItem("comments");
    if (commentNode != null) {
      String tmp = commentNode.getNodeValue().trim();
      comments = tmp.length() == 0 ? null : tmp;
    } else {
      comments = null;
    }

    Node remoteSchemaNode = attribs.getNamedItem("remoteSchema");
    if (remoteSchemaNode != null) {
      remoteSchema = remoteSchemaNode.getNodeValue().trim();
    } else {
      remoteSchema = null;
    }

    logger.fine(
        "Found XML table metadata for "
            + name
            + " remoteSchema: "
            + remoteSchema
            + " comments: "
            + comments);

    NodeList columnNodes = ((Element) tableNode.getChildNodes()).getElementsByTagName("column");

    for (int i = 0; i < columnNodes.getLength(); ++i) {
      Node colNode = columnNodes.item(i);
      columns.add(new TableColumnMeta(colNode));
    }
  }
 private ControlSegment processControlSegment(Node control) {
   ControlSegment segment = new ControlSegment();
   processObjectSegment(segment, control, "o."); // $NON-NLS-1$
   Node fill = control.getAttributes().getNamedItem("fill"); // $NON-NLS-1$
   if (fill != null) {
     String value = fill.getNodeValue();
     boolean doFill = value.equalsIgnoreCase("true"); // $NON-NLS-1$
     segment.setFill(doFill);
   }
   try {
     Node width = control.getAttributes().getNamedItem("width"); // $NON-NLS-1$
     if (width != null) {
       String value = width.getNodeValue();
       int doWidth = Integer.parseInt(value);
       segment.setWidth(doWidth);
     }
     Node height = control.getAttributes().getNamedItem("height"); // $NON-NLS-1$
     if (height != null) {
       String value = height.getNodeValue();
       int doHeight = Integer.parseInt(value);
       segment.setHeight(doHeight);
     }
   } catch (NumberFormatException e) {
     // ignore invalid width or height
   }
   return segment;
 }
Exemplo n.º 17
0
 public static Date getDate(final Node node, final String attributeName) {
   Node attributeNode = node.getAttributes().getNamedItem(attributeName);
   if (attributeNode == null) {
     LOG.warn("Failed to parse attribute from node: {} > {}", node.getNodeName(), attributeName);
     return new Date();
   }
   String dTemp = null;
   SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
   Date date = null;
   try {
     dTemp = attributeNode.getNodeValue();
     date = format.parse(dTemp);
   } catch (ParseException ex) {
   }
   try {
     dTemp = attributeNode.getNodeValue();
     date = new Date(Long.parseLong(dTemp));
   } catch (NumberFormatException ex) {
   }
   if (date != null) {
     return date;
   } else {
     LOG.warn(
         "Failed to convert string to date: {} from node: {} > {}",
         new Object[] {dTemp, node.getNodeName(), attributeName});
     return new Date();
   }
 }
Exemplo n.º 18
0
 @Override
 public void FromXMLNode(Node ANode) throws Exception {
   super.FromXMLNode(ANode);
   // . Width
   Node _Node = TMyXML.SearchNode(ANode, "Width");
   if (_Node != null) {
     Node ValueNode = _Node.getFirstChild();
     if (ValueNode != null) Width = Integer.parseInt(ValueNode.getNodeValue());
   }
   // . Height
   _Node = TMyXML.SearchNode(ANode, "Height");
   if (_Node != null) {
     Node ValueNode = _Node.getFirstChild();
     if (ValueNode != null) Height = Integer.parseInt(ValueNode.getNodeValue());
   }
   // . FrameRate
   _Node = TMyXML.SearchNode(ANode, "FrameRate");
   if (_Node != null) {
     Node ValueNode = _Node.getFirstChild();
     if (ValueNode != null) FrameRate = Integer.parseInt(ValueNode.getNodeValue());
   }
   // . BitRate
   _Node = TMyXML.SearchNode(ANode, "BitRate");
   if (_Node != null) {
     Node ValueNode = _Node.getFirstChild();
     if (ValueNode != null) BitRate = Integer.parseInt(ValueNode.getNodeValue());
   }
 }
Exemplo n.º 19
0
 static {
   try {
     DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
     DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
     Document document = dbBuilder.parse(PROPERTIES_FILE_PATH);
     Node root = document.getFirstChild();
     if (root != null && "properties".equals(root.getNodeName())) {
       NodeList childNodes = root.getChildNodes();
       for (int i = 0; i < childNodes.getLength(); i++) {
         Node node = childNodes.item(i);
         if ("property".equals(node.getNodeName())) {
           NamedNodeMap attributes = node.getAttributes();
           Node keyNode = attributes.getNamedItem("key");
           Node valueNode = attributes.getNamedItem("value");
           if (keyNode != null && valueNode != null) {
             String key = keyNode.getNodeValue();
             String value = valueNode.getNodeValue();
             if (key != null && !key.isEmpty() && value != null && !value.isEmpty()) {
               PROPERTIES_FILE.put(key, value);
             }
           }
         }
       }
     }
   } catch (ParserConfigurationException | SAXException | IOException ex) {
   }
 }
Exemplo n.º 20
0
  //	 This method recursively traverses the XML Tree (starting from currElement)
  public void traverseXML(Node currNode) {
    // If it's an Element, spit out the Name
    if (currNode.getNodeType() == Node.ELEMENT_NODE) {
      System.out.print(currNode.getNodeName() + ": ");
      // If it's a "Text" node, take the value
      // These will come one after another and therefore appear in the right order
    } else if (currNode.getNodeType() == Node.TEXT_NODE) {
      System.out.println(currNode.getNodeValue().trim());
    }

    // Display any attributes
    if (currNode.hasAttributes()) {
      NamedNodeMap attributes = currNode.getAttributes();
      for (int i = 0; i < attributes.getLength(); i++) {
        Node attr = attributes.item(i);
        System.out.println("  " + attr.getNodeName() + ": " + attr.getNodeValue());
      }
    }

    // Check any children
    if (currNode.hasChildNodes()) {
      // Get the list of children
      NodeList children = currNode.getChildNodes();
      // Go through all the chilrden
      for (int i = 0; i < children.getLength(); i++) {
        // Search each Node
        Node n = children.item(i);
        traverseXML(n);
      }
    }
  }
Exemplo n.º 21
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;
      }
    }
  }
Exemplo n.º 22
0
      public void onDocument(Document document, String xpath) throws XmlParserException {
        if (xpath.equals(XPATH_IPEAK)) {
          Node node = document.getFirstChild();

          // check whether we're getting the correct ipeak
          Node typeattribute = node.getAttributes().getNamedItem(PeakMLWriter.TYPE);
          if (typeattribute == null)
            throw new XmlParserException("Failed to locate the type attribute.");
          if (!typeattribute.getNodeValue().equals(PeakMLWriter.TYPE_BACKGROUNDION))
            throw new XmlParserException(
                "IPeak ("
                    + typeattribute.getNodeValue()
                    + ") is not of type: '"
                    + PeakMLWriter.TYPE_BACKGROUNDION
                    + "'");

          // parse this node as a mass chromatogram
          BackgroundIon<? extends Peak> backgroundion = parseBackgroundIon(node);
          if (backgroundion != null) peaks.add(backgroundion);

          //
          if (_listener != null && result.header != null && result.header.getNrPeaks() != 0)
            _listener.update((100. * index++) / result.header.getNrPeaks());
        } else if (xpath.equals(XPATH_HEADER)) {
          result.header = parseHeader(document.getFirstChild());
        }
      }
  public void setConfigNode(NodeList p) {
    String sel = "Default";
    System.out.println("Config has " + p.getLength());
    for (int i = 0; i < p.getLength(); i++) {
      Node nNode = p.item(i);
      if (nNode.getNodeType() == Node.ELEMENT_NODE) {
        Element eElement = (Element) nNode;
        System.out.println("Element = " + eElement);
        try {
          sel = XmlFactory.getTagValue("selected", eElement);
        } catch (Exception ex) {
          // ex.printStackTrace();
        }
        try {
          NodeList nlList = eElement.getElementsByTagName("file");
          System.out.println("Have files # " + nlList.getLength());
          for (int j = 0; j < nlList.getLength(); j++) {
            Node nValue = ((NodeList) nlList.item(j)).item(0);
            System.out.println("Value = " + nValue.getNodeValue());
            addAvailibleFile(new File(nValue.getNodeValue()));
          }
          // System.out.println("\t\t"+sTag+" = "+nValue.getNodeValue());

        } catch (Exception ex) {
          // ex.printStackTrace();
        }
      } else {
        System.out.println("Not Element Node");
      }
    }

    setSelectedFile(sel);
  }
Exemplo n.º 24
0
  private void getConnectionProperties(final Node node) {
    final NodeList childNodes = node.getChildNodes();

    for (int i = 0; i < childNodes.getLength(); ++i) {
      final Node childNode = childNodes.item(i);

      if (childNode.getNodeType() == Node.ELEMENT_NODE) {
        final String nodeName = childNode.getNodeName();
        if (nodeName.equals("property")) {
          final NamedNodeMap attributes = childNode.getAttributes();

          Node n = attributes.getNamedItem("name");
          ThreadContext.assertError(
              n != null,
              "DbAnalyse-options/connection-properties/property must contain a 'name' attribute");
          final String name = n.getNodeValue();

          n = attributes.getNamedItem("value");
          ThreadContext.assertError(
              n != null,
              "DbAnalyse-options/connection-properties/property must contain a 'value' attribute");
          final String value = n.getNodeValue();

          m_options.m_connectionProperties.add(E2.of(name, value));
        } else {
          ThreadContext.assertError(
              false, "[%s] unknown option element [%s]", getClass().getSimpleName(), nodeName);
        }
      }
    }
  }
  /**
   * Request the renderer that suits the given value type and for the given tree.
   *
   * @param tree The source tree this node comes from
   * @param value The DOMTreeNode to be rendered
   * @param selected True if the node is selected
   * @param expanded True if expanded
   * @param row The row this node is on
   * @param hasFocus True if the node currently has focus
   */
  public Component getTreeCellRendererComponent(
      JTree tree,
      Object value,
      boolean selected,
      boolean expanded,
      boolean leaf,
      int row,
      boolean hasFocus) {

    this.selected = selected;
    this.focused = hasFocus;

    Node node = ((DOMTreeNode) value).getNode();
    String name = (String) nodeNameMap.get(node.getNodeType());
    setIcon(null);

    switch (node.getNodeType()) {
      case Node.ATTRIBUTE_NODE:
        setText(node.getNodeName() + "=" + node.getNodeValue());
        break;

      case Node.TEXT_NODE:
      case Node.COMMENT_NODE:
      case Node.CDATA_SECTION_NODE:
        StringBuffer txt = new StringBuffer(name);
        txt.append(" \"");
        txt.append(node.getNodeValue());
        txt.append('\"');
        setText(txt.toString());
        break;

      case Node.DOCUMENT_FRAGMENT_NODE:
      case Node.DOCUMENT_NODE:
        // I'd really like to put the name of the document here.
        setText(name);
        break;

      case Node.DOCUMENT_TYPE_NODE:
      case Node.ENTITY_NODE:
      case Node.ENTITY_REFERENCE_NODE:
      case Node.NOTATION_NODE:
      case Node.PROCESSING_INSTRUCTION_NODE:
        setText(node.getNodeName());
        break;

      case Node.ELEMENT_NODE:
        String nn = node.getNodeName();
        setText(nn);

        // Check to see if we have an icon too.
        Icon icon = IconLoader.loadIcon(nn, null);
        if (icon != null) setIcon(icon);
    }

    setComponentOrientation(tree.getComponentOrientation());

    return this;
  }
Exemplo n.º 26
0
 private static void compareLists(ArrayList<Node> list1, ArrayList<Node> list2) {
   for (Node node1 : list1) {
     for (Node node2 : list2) {
       if (node1.getNodeValue().equals(node2.getNodeValue())) {
         System.out.println(node2.getNodeValue());
       }
     }
   }
 }
  private Paragraph processListItem(Node listItem, boolean expandURLs) {
    NodeList children = listItem.getChildNodes();
    NamedNodeMap atts = listItem.getAttributes();
    Node addSpaceAtt = atts.getNamedItem("addVerticalSpace"); // $NON-NLS-1$
    Node styleAtt = atts.getNamedItem("style"); // $NON-NLS-1$
    Node valueAtt = atts.getNamedItem("value"); // $NON-NLS-1$
    Node indentAtt = atts.getNamedItem("indent"); // $NON-NLS-1$
    Node bindentAtt = atts.getNamedItem("bindent"); // $NON-NLS-1$
    int style = BulletParagraph.CIRCLE;
    int indent = -1;
    int bindent = -1;
    String text = null;
    boolean addSpace = true;

    if (addSpaceAtt != null) {
      String value = addSpaceAtt.getNodeValue();
      addSpace = value.equalsIgnoreCase("true"); // $NON-NLS-1$
    }
    if (styleAtt != null) {
      String value = styleAtt.getNodeValue();
      if (value.equalsIgnoreCase("text")) { // $NON-NLS-1$
        style = BulletParagraph.TEXT;
      } else if (value.equalsIgnoreCase("image")) { // $NON-NLS-1$
        style = BulletParagraph.IMAGE;
      } else if (value.equalsIgnoreCase("bullet")) { // $NON-NLS-1$
        style = BulletParagraph.CIRCLE;
      }
    }
    if (valueAtt != null) {
      text = valueAtt.getNodeValue();
      if (style == BulletParagraph.IMAGE) text = "i." + text; // $NON-NLS-1$
    }
    if (indentAtt != null) {
      String value = indentAtt.getNodeValue();
      try {
        indent = Integer.parseInt(value);
      } catch (NumberFormatException e) {
      }
    }
    if (bindentAtt != null) {
      String value = bindentAtt.getNodeValue();
      try {
        bindent = Integer.parseInt(value);
      } catch (NumberFormatException e) {
      }
    }

    BulletParagraph p = new BulletParagraph(addSpace);
    p.setIndent(indent);
    p.setBulletIndent(bindent);
    p.setBulletStyle(style);
    p.setBulletText(text);

    processSegments(p, children, expandURLs);
    return p;
  }
 private ParametersType extractParamTypes(Node node, boolean isDefaultNode) {
   // add parameters
   ParametersType paramTypes =
       isDefaultNode
           ? ObjectFactory.getInstance().createParametersType()
           : ObjectFactory.getInstance().createConfigType();
   NodeList paramsList = node.getChildNodes();
   for (int z = 0; z < paramsList.getLength(); z++) {
     Node paramNode = paramsList.item(z);
     if ((paramNode != null) && (paramNode.getNodeType() == Node.ELEMENT_NODE)) {
       String paramName = paramNode.getNodeName();
       Node valueNode = paramNode.getFirstChild();
       String paramValue = valueNode.getNodeValue();
       if (paramName.equalsIgnoreCase("d:country-code")) {
         paramTypes.setCountryCode(Float.parseFloat(paramValue));
       } else if (paramName.equalsIgnoreCase("d:network-code")) {
         paramTypes.setNetworkCode(Float.parseFloat(paramValue));
       } else if (paramName.equalsIgnoreCase("d:screen-size")) {
         paramTypes.setScreenSize(paramValue);
       } else if (paramName.equalsIgnoreCase("d:screen-ratio")) {
         paramTypes.setScreenRatio(paramValue);
       } else if (paramName.equalsIgnoreCase("d:screen-orientation")) {
         paramTypes.setScreenOrientation(paramValue);
       } else if (paramName.equalsIgnoreCase("d:pixel-density")) {
         paramTypes.setPixelDensity(paramValue);
       } else if (paramName.equalsIgnoreCase("d:touch-type")) {
         paramTypes.setTouchType(paramValue);
       } else if (paramName.equalsIgnoreCase("d:keyboard-state")) {
         paramTypes.setKeyboardState(paramValue);
       } else if (paramName.equalsIgnoreCase("d:text-input-method")) {
         paramTypes.setTextInputMethod(paramValue);
       } else if (paramName.equalsIgnoreCase("d:nav-state")) {
         paramTypes.setNavState(paramValue);
       } else if (paramName.equalsIgnoreCase("d:nav-method")) {
         paramTypes.setNavMethod(paramValue);
       } else if (paramName.equalsIgnoreCase("d:screen-dimension")) {
         ScreenDimension dim = ObjectFactory.getInstance().createParametersTypeScreenDimension();
         NodeList dimensionList = paramNode.getChildNodes();
         for (int w = 0; w < dimensionList.getLength(); w++) {
           Node dimensionNode = dimensionList.item(w);
           if ((dimensionNode != null) && (dimensionNode.getNodeType() == Node.ELEMENT_NODE)) {
             Node sizeNode = dimensionNode.getFirstChild();
             String dimValue = sizeNode.getNodeValue();
             dim.addSize(Integer.parseInt(dimValue));
           }
         }
         paramTypes.setScreenDimension(dim);
       } else if (paramName.equalsIgnoreCase("d:xdpi")) {
         paramTypes.setXdpi(Float.parseFloat(paramValue));
       } else if (paramName.equalsIgnoreCase("d:ydpi")) {
         paramTypes.setYdpi(Float.parseFloat(paramValue));
       }
     }
   }
   return paramTypes;
 }
Exemplo n.º 29
0
 private static IPeak parseIPeak(Node parent) throws XmlParserException {
   Node type = parent.getAttributes().getNamedItem(PeakMLWriter.TYPE);
   if (type == null) return null;
   else if (type.getNodeValue().equals(PeakMLWriter.TYPE_PEAKSET)) return parsePeakSet(parent);
   else if (type.getNodeValue().equals(PeakMLWriter.TYPE_BACKGROUNDION))
     return parseBackgroundIon(parent);
   else if (type.getNodeValue().equals(PeakMLWriter.TYPE_MASSCHROMATOGRAM))
     return parseMassChromatogram(parent);
   else return null;
 }
Exemplo n.º 30
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());
     }
   }
 }