@Test
  public void testValidateHasMultiplePrimaryAttributeNames() {
    Document document = DocumentHelper.createDocument();

    Element element = document.addElement("execute");

    element.addAttribute("function", "Click");
    element.addAttribute("selenium", "click");

    List<String> attributeNames = new ArrayList<>();

    List<Attribute> attributes = element.attributes();

    for (Attribute attribute : attributes) {
      attributeNames.add(attribute.getName());
    }

    PoshiRunnerValidation.validateHasMultiplePrimaryAttributeNames(
        element,
        attributeNames,
        Arrays.asList("function", "selenium"),
        "ValidateHasMultiplePrimaryAttributeNames.macro");

    Assert.assertEquals(
        "validateHasMultiplePrimaryAttributeNames is failing", "", getExceptionMessage());

    document = DocumentHelper.createDocument();

    element = document.addElement("execute");

    element.addAttribute("function", "Click");
    element.addAttribute("locator1", "//here");

    attributeNames = new ArrayList<>();

    attributes = element.attributes();

    for (Attribute attribute : attributes) {
      attributeNames.add(attribute.getName());
    }

    PoshiRunnerValidation.validateHasMultiplePrimaryAttributeNames(
        element,
        attributeNames,
        Arrays.asList("function", "selenium"),
        "ValidateHasMultiplePrimaryAttributeNames.macro");

    Assert.assertEquals(
        "validateHasMultiplePrimaryAttributeNames is failing",
        "Too many attributes",
        getExceptionMessage());
  }
 public void visit(Attribute attr) {
   try {
     if (null == attr.getText() || attr.getText().isEmpty()) {
       BeanUtils.copyProperty(object, attr.getName(), attr.getValue());
     } else {
       BeanUtils.copyProperty(object, attr.getName(), attr.getText());
     }
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   } catch (InvocationTargetException e) {
     e.printStackTrace();
   }
 }
Пример #3
0
  @Override
  protected void readData(Element rootElement) throws Exception {
    for (Iterator<Element> iterator = rootElement.elementIterator(); iterator.hasNext(); ) {
      Element e = iterator.next();
      if ("fish".equals(e.getName())) {
        MultiValueSet<String> map = new MultiValueSet<String>();
        for (Iterator<Attribute> attributeIterator = e.attributeIterator();
            attributeIterator.hasNext(); ) {
          Attribute attribute = attributeIterator.next();
          map.put(attribute.getName(), attribute.getValue());
        }

        getHolder().addFish(new FishTemplate(map));
      } else if ("lure".equals(e.getName())) {
        MultiValueSet<String> map = new MultiValueSet<String>();
        for (Iterator<Attribute> attributeIterator = e.attributeIterator();
            attributeIterator.hasNext(); ) {
          Attribute attribute = attributeIterator.next();
          map.put(attribute.getName(), attribute.getValue());
        }

        Map<FishGroup, Integer> chances = new HashMap<FishGroup, Integer>();
        for (Iterator<Element> elementIterator = e.elementIterator(); elementIterator.hasNext(); ) {
          Element chanceElement = elementIterator.next();
          chances.put(
              FishGroup.valueOf(chanceElement.attributeValue("type")),
              Integer.parseInt(chanceElement.attributeValue("value")));
        }
        map.put("chances", chances);
        getHolder().addLure(new LureTemplate(map));
      } else if ("distribution".equals(e.getName())) {
        int id = Integer.parseInt(e.attributeValue("id"));

        for (Iterator<Element> forLureIterator = e.elementIterator(); forLureIterator.hasNext(); ) {
          Element forLureElement = forLureIterator.next();

          LureType lureType = LureType.valueOf(forLureElement.attributeValue("type"));
          Map<FishGroup, Integer> chances = new HashMap<FishGroup, Integer>();

          for (Iterator<Element> chanceIterator = forLureElement.elementIterator();
              chanceIterator.hasNext(); ) {
            Element chanceElement = chanceIterator.next();
            chances.put(
                FishGroup.valueOf(chanceElement.attributeValue("type")),
                Integer.parseInt(chanceElement.attributeValue("value")));
          }
          getHolder().addDistribution(id, lureType, chances);
        }
      }
    }
  }
Пример #4
0
  /**
   * 遍历整个XML文件,获取所有节点的值与其属性的值,并放入HashMap中
   *
   * @param filename String 待遍历的XML文件(相对路径或者绝对路径)
   * @param hm HashMap 存放遍历结果,格式:<nodename,nodevalue>或者<nodename+attrname,attrvalue>
   */
  public void iterateWholeXML(String filename, HashMap<String, String> hm) {
    SAXReader saxReader = new SAXReader();
    try {
      Document document = saxReader.read(new File(filename));
      Element root = document.getRootElement();
      // 用于记录学生编号的变量
      int num = -1;
      // 遍历根结点(students)的所有孩子节点(肯定是student节点)
      for (Iterator iter = root.elementIterator(); iter.hasNext(); ) {
        Element element = (Element) iter.next();
        num++;
        // 获取person节点的age属性的值
        Attribute ageAttr = element.attribute("age");
        if (ageAttr != null) {
          String age = ageAttr.getValue();
          if (age != null && !age.equals("")) {
            hm.put(element.getName() + "-" + ageAttr.getName() + num, age);
          } else {
            hm.put(element.getName() + "-" + ageAttr.getName() + num, "20");
          }
        } else {
          hm.put(element.getName() + "-age" + num, "20");
        }
        // 遍历student结点的所有孩子节点(即name,college,telphone,notes),并进行处理
        for (Iterator iterInner = element.elementIterator(); iterInner.hasNext(); ) {
          Element elementInner = (Element) iterInner.next();
          if (elementInner.getName().equals("college")) {
            hm.put(elementInner.getName() + num, elementInner.getText());
            // 获取college节点的leader属性的值
            Attribute leaderAttr = elementInner.attribute("leader");
            if (leaderAttr != null) {
              String leader = leaderAttr.getValue();
              if (leader != null && !leader.equals("")) {
                hm.put(elementInner.getName() + "-" + leaderAttr.getName() + num, leader);
              } else {
                hm.put(elementInner.getName() + "-" + leaderAttr.getName() + num, "leader");
              }
            } else {
              hm.put(elementInner.getName() + "-leader" + num, "leader");
            }
          } else {
            hm.put(elementInner.getName() + num, elementInner.getText());
          }
        }
      }

    } catch (DocumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 /**
  * @方法功能描述:得到指定节点的所有属性及属性值 @方法名:getNodeAttrMap
  *
  * @return 属性集合 @返回类型:Map<String,String>
  */
 public static Map<String, String> getNodeAttrMap(Element e) {
   Map<String, String> attrMap = new HashMap<String, String>();
   if (e == null) {
     return null;
   }
   List<Attribute> attributes = getAttributeList(e);
   if (attributes == null) {
     return null;
   }
   for (Attribute attribute : attributes) {
     String attrValueString = attrValue(e, attribute.getName());
     attrMap.put(attribute.getName(), attrValueString);
   }
   return attrMap;
 }
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    SAXReader reader = new SAXReader();
    try {
      Document document = reader.read(new File("books.xml"));
      Element bookStore = document.getRootElement();

      Iterator it = bookStore.elementIterator();

      while (it.hasNext()) {
        Element book = (Element) it.next();
        List<org.dom4j.Attribute> bootAttrs = book.attributes();

        for (org.dom4j.Attribute attr : bootAttrs) {
          System.out.println("node name: " + attr.getName() + " - node value: " + attr.getValue());
        }
        Iterator itt = book.elementIterator();
        while (itt.hasNext()) {
          Element bookChild = (Element) itt.next();
          System.out.println(
              "sub node name: "
                  + bookChild.getName()
                  + " - sub node value: "
                  + bookChild.getStringValue());
        }
        System.out.println();
      }

    } catch (DocumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Пример #7
0
 /**
  * 修改xml某节点的值
  *
  * @param inputXml 原xml文件
  * @param nodes 要修改的节点
  * @param attributename 属性名称
  * @param value 新值
  * @param outXml 输出文件路径及文件名 如果输出文件为null,则默认为原xml文件
  */
 public static void modifyDocument(
     File inputXml, String nodes, String attributename, String value, String outXml) {
   try {
     SAXReader saxReader = new SAXReader();
     Document document = saxReader.read(inputXml);
     List list = document.selectNodes(nodes);
     Iterator iter = list.iterator();
     while (iter.hasNext()) {
       Attribute attribute = (Attribute) iter.next();
       if (attribute.getName().equals(attributename)) attribute.setValue(value);
     }
     XMLWriter output;
     if (outXml != null) { // 指定输出文件
       output = new XMLWriter(new FileWriter(new File(outXml)));
     } else { // 输出文件为原文件
       output = new XMLWriter(new FileWriter(inputXml));
     }
     output.write(document);
     output.close();
   } catch (DocumentException e) {
     System.out.println(e.getMessage());
   } catch (IOException e) {
     System.out.println(e.getMessage());
   }
 }
  /**
   * 获取 HotelGeo 节点的版本。三个节点:Districts CommericalLocations LandmarkLocations
   *
   * @param hotelGeoElement
   * @return
   */
  public String getHotelGeoVersion(Element hotelGeoElement) {
    StringBuffer sb = new StringBuffer("");
    if (null == hotelGeoElement) {
      return "";
    }
    List<Element> hgElement =
        hotelGeoElement.elements(); // 包括 Districts  CommericalLocations LandmarkLocations
    if (null != hgElement && hgElement.size() > 0) {
      for (int i = 0; i < hgElement.size(); i++) {
        Element elment = hgElement.get(i);
        if (null != elment && null != elment.elements()) {
          for (int j = 0; j < elment.elements().size(); j++) {
            Element node = (Element) elment.elements().get(j);
            if (null != node && null != node.attributes()) {
              for (int a = 0; a < node.attributes().size(); a++) {
                Attribute att = (Attribute) node.attributes().get(a);
                sb.append(att.getName()).append(att.getValue());
              }
            }
          }
        }
      }
    }

    try {
      return MD5.encode(sb.toString());
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return "";
  }
Пример #9
0
 /**
  * 解析consumer属性值
  *
  * @param Consumer consumer consumer对象
  * @param List<Attribute> attrs consumer属性值集合
  * @return Consumer
  */
 private Consumer parseAttributes(Consumer consumer, List<Attribute> attrs) {
   for (Attribute attr : attrs) {
     String name = attr.getName();
     String value = attr.getValue();
     consumer = (Consumer) this.callSetterMethodByNameAndValue(consumer, name, value);
   }
   return consumer;
 }
Пример #10
0
  public static List<org.pentaho.ui.xul.dom.Attribute> convertAttributes(List<Attribute> inList) {
    List<org.pentaho.ui.xul.dom.Attribute> outList =
        new ArrayList<org.pentaho.ui.xul.dom.Attribute>();

    for (Attribute attr : inList) {
      outList.add(new org.pentaho.ui.xul.dom.Attribute(attr.getName(), attr.getValue()));
    }
    return outList;
  }
Пример #11
0
  /**
   * Method parseUsingCondition.
   *
   * @param element Element
   * @return Condition
   */
  private Condition parseUsingCondition(Element element) {
    Condition cond = null;

    for (Iterator<Attribute> iterator = element.attributeIterator(); iterator.hasNext(); ) {
      Attribute attribute = iterator.next();
      String name = attribute.getName();
      String value = attribute.getValue();

      if (name.equalsIgnoreCase("slotitem")) {
        StringTokenizer st = new StringTokenizer(value, ";");
        int id = Integer.parseInt(st.nextToken().trim());
        int slot = Integer.parseInt(st.nextToken().trim());
        int enchant = 0;

        if (st.hasMoreTokens()) {
          enchant = Integer.parseInt(st.nextToken().trim());
        }

        cond = joinAnd(cond, new ConditionSlotItemId(slot, id, enchant));
      } else if (name.equalsIgnoreCase("kind") || name.equalsIgnoreCase("weapon")) {
        long mask = 0;
        StringTokenizer st = new StringTokenizer(value, ",");
        tokens:
        while (st.hasMoreTokens()) {
          String item = st.nextToken().trim();

          for (WeaponTemplate.WeaponType wt : WeaponTemplate.WeaponType.VALUES) {
            if (wt.toString().equalsIgnoreCase(item)) {
              mask |= wt.mask();
              continue tokens;
            }
          }

          for (ArmorTemplate.ArmorType at : ArmorTemplate.ArmorType.VALUES) {
            if (at.toString().equalsIgnoreCase(item)) {
              mask |= at.mask();
              continue tokens;
            }
          }

          error("Invalid item kind: \"" + item + "\" in " + getCurrentFileName());
        }

        if (mask != 0) {
          cond = joinAnd(cond, new ConditionUsingItemType(mask));
        }
      } else if (name.equalsIgnoreCase("skill")) {
        cond = joinAnd(cond, new ConditionUsingSkill(Integer.parseInt(value)));
      }
    }

    return cond;
  }
Пример #12
0
 // 根据指定的元素创建一个Document
 @SuppressWarnings("unchecked")
 private static Document createDocument(Element element) {
   Document document = DocumentHelper.createDocument();
   Element root = document.addElement(element.getName());
   List<Attribute> attrs = element.attributes(); // 添加element元素的属性到根元素结点
   if (attrs != null) {
     for (Attribute attr : attrs) {
       root.addAttribute(attr.getName(), attr.getValue());
     }
   }
   root.appendContent(element);
   return document;
 }
Пример #13
0
  public static Map<String, String> AttributesToMap(List<Attribute> attMap) {

    Map<String, String> map = new HashMap<String, String>();
    for (int i = 0; i < attMap.size(); i++) {
      Attribute node = attMap.get(i);
      String name = node.getName();
      if (name.equals("ID")) {
        name = "id";
      }
      map.put(name, node.getValue());
    }
    return map;
  }
Пример #14
0
  /**
   * Convert dom4j attributes to SAX attributes.
   *
   * @param element dom4j Element
   * @return SAX Attributes
   */
  public static Attributes getSAXAttributes(Element element) {
    final AttributesImpl result = new AttributesImpl();
    for (Iterator i = element.attributeIterator(); i.hasNext(); ) {
      final org.dom4j.Attribute attribute = (org.dom4j.Attribute) i.next();

      result.addAttribute(
          attribute.getNamespaceURI(),
          attribute.getName(),
          attribute.getQualifiedName(),
          ContentHandlerHelper.CDATA,
          attribute.getValue());
    }
    return result;
  }
Пример #15
0
  /**
   * Writes the attributes of the given element
   *
   * @param element DOCUMENT ME!
   * @throws IOException DOCUMENT ME!
   */
  protected void writeAttributes(Element element) throws IOException {
    // I do not yet handle the case where the same prefix maps to
    // two different URIs. For attributes on the same element
    // this is illegal; but as yet we don't throw an exception
    // if someone tries to do this
    for (int i = 0, size = element.attributeCount(); i < size; i++) {
      Attribute attribute = element.attribute(i);
      Namespace ns = attribute.getNamespace();

      if ((ns != null) && (ns != Namespace.NO_NAMESPACE) && (ns != Namespace.XML_NAMESPACE)) {
        String prefix = ns.getPrefix();
        String uri = namespaceStack.getURI(prefix);

        if (!ns.getURI().equals(uri)) {
          writeNamespace(ns);
          namespaceStack.push(ns);
        }
      }

      // If the attribute is a namespace declaration, check if we have
      // already written that declaration elsewhere (if that's the case,
      // it must be in the namespace stack
      String attName = attribute.getName();

      if (attName.startsWith("xmlns:")) {
        String prefix = attName.substring(6);

        if (namespaceStack.getNamespaceForPrefix(prefix) == null) {
          String uri = attribute.getValue();
          namespaceStack.push(prefix, uri);
          writeNamespace(prefix, uri);
        }
      } else if (attName.equals("xmlns")) {
        if (namespaceStack.getDefaultNamespace() == null) {
          String uri = attribute.getValue();
          namespaceStack.push(null, uri);
          writeNamespace(null, uri);
        }
      } else {
        char quote = format.getAttributeQuoteCharacter();
        writer.write(" ");
        writer.write(attribute.getQualifiedName());
        writer.write("=");
        writer.write(quote);
        writeEscapeAttributeEntities(attribute.getValue());
        writer.write(quote);
      }
    }
  }
Пример #16
0
  /**
   * Method parseZoneCondition.
   *
   * @param element Element
   * @return Condition
   */
  private Condition parseZoneCondition(Element element) {
    Condition cond = null;

    for (Iterator<Attribute> iterator = element.attributeIterator(); iterator.hasNext(); ) {
      Attribute attribute = iterator.next();
      String name = attribute.getName();
      String value = attribute.getValue();

      if (name.equalsIgnoreCase("type")) {
        cond = joinAnd(cond, new ConditionZoneType(value));
      }
    }

    return cond;
  }
Пример #17
0
  /**
   * Method parseTargetCondition.
   *
   * @param element Element
   * @return Condition
   */
  private Condition parseTargetCondition(Element element) {
    Condition cond = null;

    for (Iterator<Attribute> iterator = element.attributeIterator(); iterator.hasNext(); ) {
      Attribute attribute = iterator.next();
      String name = attribute.getName();
      String value = attribute.getValue();

      if (name.equalsIgnoreCase("pvp")) {
        cond = joinAnd(cond, new ConditionTargetPlayable(Boolean.valueOf(value)));
      }
    }

    return cond;
  }
Пример #18
0
 private Package parsePackage(Element el) {
   Package pk = new Package();
   Map<String, String> nsMap = new HashMap<String, String>(4);
   for (Attribute attr : (List<Attribute>) el.attributes()) {
     String name = attr.getName();
     String value = attr.getValue();
     if ("name".equals(name)) {
       pk.setName(value);
     } else {
       nsMap.put(name, value);
     }
   }
   pk.setNamespaces(nsMap);
   pk.setId(pk.getNamespace("js"));
   parseDoc(el, pk);
   return pk;
 }
Пример #19
0
  /**
   * Method parsePlayerCondition.
   *
   * @param element Element
   * @return Condition
   */
  private Condition parsePlayerCondition(Element element) {
    Condition cond = null;

    for (Iterator<Attribute> iterator = element.attributeIterator(); iterator.hasNext(); ) {
      Attribute attribute = iterator.next();
      String name = attribute.getName();
      String value = attribute.getValue();

      if (name.equalsIgnoreCase("residence")) {
        String[] st = value.split(";");
        cond =
            joinAnd(
                cond,
                new ConditionPlayerResidence(
                    Integer.parseInt(st[1]), ResidenceType.valueOf(st[0])));
      } else if (name.equalsIgnoreCase("classId")) {
        cond = joinAnd(cond, new ConditionPlayerClassId(value.split(",")));
      } else if (name.equalsIgnoreCase("olympiad")) {
        cond = joinAnd(cond, new ConditionPlayerOlympiad(Boolean.valueOf(value)));
      } else if (name.equalsIgnoreCase("instance_zone")) {
        cond = joinAnd(cond, new ConditionPlayerInstanceZone(Integer.parseInt(value)));
      } else if (name.equalsIgnoreCase("race")) {
        cond = joinAnd(cond, new ConditionPlayerRace(value));
      } else if (name.equalsIgnoreCase("damage")) {
        String[] st = value.split(";");
        cond =
            joinAnd(
                cond,
                new ConditionPlayerMinMaxDamage(
                    Double.parseDouble(st[0]), Double.parseDouble(st[1])));
      } else if (name.equalsIgnoreCase("castleLight")) {
        cond = joinAnd(cond, new ConditionCastleLight());
      } else if (name.equalsIgnoreCase("castleLightClanLeader")) {
        cond = joinAnd(cond, new ConditionCastleLightClanLeader());
      } else if (name.equalsIgnoreCase("castleDark")) {
        cond = joinAnd(cond, new ConditionCastleDark());
      } else if (name.equalsIgnoreCase("castleDarkClanLeader")) {
        cond = joinAnd(cond, new ConditionCastleDarkClanLeader());
      }
    }

    return cond;
  }
Пример #20
0
 /**
  * 方法名: </br> 详述: </br>修改版本号和package 开发人员:谭明</br> 创建时间:Apr 1, 2014</br>
  *
  * @param pageName
  * @param project_path
  * @throws Exception
  */
 public static void update_AndroidManifest_xml(
     String project_path, String enterpriseId, String appId, String appKey) throws Exception {
   File file = new File(project_path + File.separator + "AndroidManifest.xml");
   String pageName = "app" + enterpriseId;
   String package_value = "com.cndatacom." + pageName;
   if (!file.exists()) {
     throw new Exception("项目AndroidManifest.xml文件不存在!");
   }
   Document doc = null;
   try {
     doc = new SAXReader().read(file);
     Element root = doc.getRootElement();
     root.setAttributeValue("package", package_value);
     logger.info("修改后的AndroidManifest.xml文件::" + doc.asXML());
     List<Element> elementList = root.element("application").elements("meta-data");
     for (Element childElement : elementList) {
       List<Attribute> aList = childElement.attributes();
       String name = "";
       Attribute a = null;
       for (Attribute attribute : aList) {
         String attributeName = attribute.getName();
         if ("value".equals(attributeName)) {
           a = attribute;
         } else if ("name".equals(attributeName)) {
           name = attribute.getValue();
         }
       }
       childElement.remove(a);
       if ("app_info".equals(name)) childElement.setAttributeValue("android:value", appId);
       else if ("app_key".equals(name)) childElement.setAttributeValue("android:value", appKey);
     }
   } catch (DocumentException e) {
     e.printStackTrace();
     throw new Exception("读取项目AndroidManifest.xml文件出错!");
   }
   try {
     XMLWriter writer = new XMLWriter(new FileOutputStream(file));
     writer.write(doc);
     writer.close();
   } catch (Exception e) {
     throw new Exception("输出项目AndroidManifest.xml文件出错!");
   }
 }
Пример #21
0
 /* 538:    */
 /* 539:    */ protected Attributes createAttributes(
     Element element, Attributes namespaceAttributes)
     /* 540:    */ throws SAXException
       /* 541:    */ {
   /* 542:822 */ this.attributes.clear();
   /* 543:824 */ if (namespaceAttributes != null) {
     /* 544:825 */ this.attributes.setAttributes(namespaceAttributes);
     /* 545:    */ }
   /* 546:828 */ for (Iterator iter = element.attributeIterator(); iter.hasNext(); )
   /* 547:    */ {
     /* 548:829 */ Attribute attribute = (Attribute) iter.next();
     /* 549:830 */ this.attributes.addAttribute(
         attribute.getNamespaceURI(),
         attribute.getName(),
         attribute.getQualifiedName(),
         "CDATA",
         attribute.getValue());
     /* 550:    */ }
   /* 551:835 */ return this.attributes;
   /* 552:    */ }
Пример #22
0
 public static Entity parseElement(Element ele, int level) {
   Entity entity = new Entity();
   entity.name = ele.getName();
   entity.content = ele.getTextTrim();
   entity.level = level;
   if (ele.attributeCount() > 0) {
     entity.attributes = new HashMap<String, String>();
     for (int i = 0; i < ele.attributeCount(); i++) {
       Attribute attr = ele.attribute(i);
       entity.attributes.put(attr.getName(), attr.getText());
     }
   }
   List<Element> cEs = ele.elements();
   if (cEs.size() > 0) {
     entity.children = new HashMap<String, Entity>();
     for (int i = 0; i < cEs.size(); i++) {
       entity.children.put(cEs.get(i).getName(), parseElement(cEs.get(i), level + 1));
     }
   }
   return entity;
 }
Пример #23
0
    @SuppressWarnings("unchecked")
    Descriptor(Element el) {
      // copy in sub-properties (child nodes)
      List<Element> elements = el.elements();
      for (Element element : elements) {
        put(element);
      }

      // copy in attributes
      for (int i = 0; i < el.attributeCount(); i++) {
        if (this.attributesMap == null) {
          this.attributesMap = new HashMap<String, String>();
        }

        Attribute attribute = (Attribute) el.attribute(i);

        String value = attribute.getValue();
        if (value != null) {
          this.attributesMap.put(attribute.getName(), value);
        }
      }
    }
Пример #24
0
  public void parseAttribute(Element element, ElementNode treeNode) {
    HashMap userObject = null;

    for (Iterator attributeIterator = element.attributeIterator(); attributeIterator.hasNext(); ) {
      Attribute attribute = (Attribute) attributeIterator.next();
      String attributeName = attribute.getName().trim();
      String attributeText = attribute.getText().trim();

      if (attributeName.equals(indexTag)) {
        treeNode.setIndex(Integer.parseInt(attributeText));
      } else if (attributeName.equals(nameTag)) {
        treeNode.setName(attributeText);
      } else if (attributeName.equals(textTag)) {
        treeNode.setText(attributeText);
      } else if (attributeName.equals(iconTag)) {
        String iconName = attributeText + (iconExtensionName != null ? iconExtensionName : "");
        switch (iconFolderMode) {
          case ICON_FOLDER_MODE_SWING:
            treeNode.setIcon(IconFactory.getSwingIcon(iconName));
            break;
          case ICON_FOLDER_MODE_CONTEXT:
            treeNode.setIcon(IconFactory.getContextIcon(iconName));
            break;
          case ICON_FOLDER_MODE_FULL:
            treeNode.setIcon(IconFactory.getIcon(iconName));
            break;
          default:
            treeNode.setIcon(IconFactory.getContextIcon(iconName));
            break;
        }
      } else if (attributeName.equals(toolTipTextTag)) {
        treeNode.setToolTipText(attributeText);
      } else if (attributeName.equals(classTag)) {
        if (userObject == null) {
          userObject = new HashMap();
          treeNode.setUserObject(userObject);
        }
        Object instance = null;
        try {
          instance = Class.forName(attributeText).newInstance();
        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        } catch (IllegalAccessException e) {
          e.printStackTrace();
        } catch (InstantiationException e) {
          e.printStackTrace();
        }
        userObject.put(classTag, instance);
      } else {
        if (userObject == null) {
          userObject = new HashMap();
          treeNode.setUserObject(userObject);
        }
        userObject.put(attributeName, attributeText);
      }
      if (treeNode.getText() == null && treeNode.getName() != null) {
        treeNode.setText(treeNode.getName());
      }
      if (treeNode.getToolTipText() == null && treeNode.getName() != null) {
        treeNode.setToolTipText(treeNode.getName());
      }
    }
  }
Пример #25
0
  private void addEntity(
      String pkg, Element entityElement, Object parentEntity, String callString) {
    try {

      // 根据包名和类名,得到全路径类名
      String clz = pkg + "." + entityElement.attributeValue("class");

      // 根据全路径类名,创建实体对象
      Object entity = Class.forName(clz).newInstance();

      // 给entity对象赋值
      // 即提取出当前Element中的所有属性,并用反射机制给entity对象赋值
      Iterator iterator = entityElement.attributeIterator();
      while (iterator.hasNext()) {
        Attribute attribute = (Attribute) iterator.next();
        String propertyName = attribute.getName();
        if (!propertyName.equals("class")
            && !propertyName.equals("call")
            && !propertyName.equals("parentName")) {
          String propertyValue = attribute.getValue();
          // 给entity相应的属性赋值,这里使用的是apache-commons-beanutils工具包,所以需要加入这个依赖包
          BeanUtils.copyProperty(entity, propertyName, propertyValue);
        }
      }

      /**
       * 提取出当前Element下面所有的非entity元素,这些元素也当作是本Entity属性的一部分 举个例子: <entity class="Form" name="请假单"
       * content="这里是请假单的内容" ...></entity> 像上面这样定义当然是可以的,但是有些属性的值可能会包含特殊字符,或者内容比较庞大,所以,可能
       * 像下面这样来定义更加合理,如: <entity class="Form" name="请假单" ...> <content> <![CDATA[
       *
       * <p>这是一个请假单 请假者姓名:<input type="text" name="leaverName" > .... ]]> </content> </entity>
       * 这样,比较复杂的文本属性,也可以定义
       */
      // 查找本元素下所有名称不是entity的元素
      List subPropertyElements = entityElement.selectNodes("*[name()!='entity']");
      if (subPropertyElements != null && !subPropertyElements.isEmpty())
        for (Iterator iterator2 = subPropertyElements.iterator(); iterator2.hasNext(); ) {
          Element e = (Element) iterator2.next();
          String propertyName = e.getName();
          String propertyValue = e.getText();
          BeanUtils.copyProperty(entity, propertyName, propertyValue);
        }

      // 判断parentEntity是否为空,如果不是空,则给parent对象赋值
      if (parentEntity != null) {
        String parentName = entityElement.attributeValue("parentName");
        if (parentName == null) { // 如果不配置父属性的名称,默认为parent
          parentName = "parent";
        }
        parentName = StringUtils.capitalize(parentName); // 首字母变成大写

        String setParentName = "set" + parentName;

        Method[] ms = entity.getClass().getMethods();
        for (Method m : ms) {
          if (m.getName().equals(setParentName)) {
            m.invoke(entity, parentEntity);
          }
        }
      }

      // 要调用哪个服务对象的哪个方法
      String call = entityElement.attributeValue("call");
      if (call != null) {
        callString = call;
      }

      if (callString == null) {
        throw new RuntimeException("没有找到call属性,无法获知要调用哪个服务对象的哪个方法!请配置call属性!");
      }

      // 得到服务对象的ID
      String serviceId = callString.substring(0, callString.indexOf("."));
      // 得到要调用的方法名称
      String methodName = callString.substring(callString.indexOf(".") + 1);

      // 通过BeanFactory得到服务对象
      Object service = factory.getBean(serviceId);

      // 得到service对象的所有方法
      Method[] ms = service.getClass().getMethods();
      for (Method m : ms) {
        if (m.getName().equals(methodName)) {
          // 调用其中我们想要调用的方法
          m.invoke(service, entity);
        }
      }

      // 判断当前entity下面是否还有其他的entity元素
      List subEntityElements = entityElement.elements("entity");
      for (Iterator iterator2 = subEntityElements.iterator(); iterator2.hasNext(); ) {
        Element e = (Element) iterator2.next();
        // 递归插入本entity元素下面的其它entity对象
        addEntity(pkg, e, entity, callString);
      }

    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }
Пример #26
0
  public static Config getConfigs(InputStream in) {
    Document document = loadXML(in);
    if (document == null) return null;

    Element elementRoot = document.getRootElement();
    Config config = new Config();

    Element elementParent = elementRoot.element("host");
    if (elementParent == null) return null;

    String tmp = elementParent.getText();
    if (tmp == null || tmp.length() == 0) return null;

    config.setHost(tmp);

    elementParent = elementRoot.element("clientv");
    if (elementParent == null) return null;

    tmp = elementParent.getText();
    if (tmp == null || tmp.length() == 0) return null;

    config.setClientv(tmp);

    elementParent = elementRoot.element("userid");
    if (elementParent == null) return null;

    tmp = elementParent.getText();
    if (!Numeric.isNumber(tmp)) return null;

    try {
      config.setUserId(Long.parseLong(tmp));
    } catch (Exception e) {
      return null;
    }

    elementParent = elementRoot.element("cookie");
    if (elementParent == null) return null;

    tmp = elementParent.getText();
    if (tmp == null || tmp.length() == 0) return null;

    config.setCookie(tmp);

    elementParent = elementRoot.element("autotowns");
    if (elementParent == null) return null;

    tmp = elementParent.getText();
    if (!Numeric.isNumber(tmp)) return null;

    try {
      config.setAutoTowns(Long.parseLong(tmp));
    } catch (NumberFormatException e) {
      return null;
    }

    elementParent = elementRoot.element("equipment");
    if (elementParent != null) {
      Element equipmentMax = elementParent.element("max");
      Element equipmentTowns = elementParent.element("towns");
      if (equipmentMax != null && equipmentTowns != null) {
        tmp = equipmentMax.getText();
        if (Numeric.isNumber(tmp)) {
          try {
            Long max = Long.parseLong(tmp);
            tmp = equipmentTowns.getText();
            if (max > 0 && tmp != null) {
              List<Long> towns = new Vector<Long>();
              if (tmp.indexOf(",") > -1) {
                String[] arrays = tmp.split(",");
                for (String array : arrays) {
                  if (Numeric.isNumber(array)) towns.add(Long.parseLong(array));
                }
              } else {
                if (Numeric.isNumber(tmp)) towns.add(Long.parseLong(tmp));
              }

              if (towns.size() > 0) {
                config.setEquipmentMax(max);
                config.setEquipmentTowns(towns);
              }
            }
          } catch (NumberFormatException e) {

          }
        }
      }
    }

    Iterator<Element> elements = elementRoot.elementIterator("towns");
    if (elements != null) {
      List<ConfigTown> configTowns = new Vector<ConfigTown>();
      while (elements.hasNext()) {
        try {
          elementParent = elements.next();
          ConfigTown configTown = new ConfigTown();

          Attribute attribute = elementParent.attribute("id");
          if (attribute == null) continue;

          tmp = attribute.getText();
          if (!Numeric.isNumber(tmp)) continue;

          configTown.setTownId(Long.parseLong(tmp));

          Element element = elementParent.element("autoupgrade");
          if (element != null && element.getText() != null) {
            tmp = element.getText();
            if (tmp.equals("true")) {
              Attribute priority = element.attribute("priority");
              if (priority != null && priority.getText() != null) {
                tmp = priority.getText();
                if (tmp.indexOf(",") > -1) {
                  String[] arrays = tmp.split(",");
                  if (arrays != null) {
                    List<Long> prioritys = new Vector<Long>();
                    for (String array : arrays) {
                      if (Numeric.isNumber(array)) prioritys.add(Long.parseLong(array));
                    }

                    if (prioritys.size() > 0) {
                      configTown.setUpgradePriority(prioritys);
                      configTown.setAutoUpgrade(true);
                    } else configTown.setAutoUpgrade(false);
                  } else configTown.setAutoUpgrade(false);
                } else {
                  if (Numeric.isNumber(tmp)) {
                    List<Long> prioritys = new Vector<Long>();
                    prioritys.add(Long.parseLong(tmp));
                    configTown.setUpgradePriority(prioritys);
                    configTown.setAutoUpgrade(true);
                  } else configTown.setAutoUpgrade(false);
                }
              } else configTown.setAutoUpgrade(false);
            } else configTown.setAutoUpgrade(false);
          } else configTown.setAutoUpgrade(false);

          element = elementParent.element("autoattack");
          if (element != null && element.getText() != null) {
            tmp = element.getText();
            if (tmp != null && tmp.equals("true")) {
              Attribute level = element.attribute("level");
              if (level != null && level.getText() != null) {
                tmp = level.getText();
                if (tmp.indexOf("-") > -1) {
                  String[] array = tmp.split("-");
                  if (array != null
                      && array.length == 2
                      && Numeric.isNumber(array[0])
                      && Numeric.isNumber(array[1])) {
                    configTown.setAutoAttack(true);
                    configTown.setAttackLevelMin(Long.parseLong(array[0]));
                    configTown.setAttackLevelMax(Long.parseLong(array[1]));
                  } else configTown.setAutoAttack(false);
                } else configTown.setAutoAttack(false);
              } else configTown.setAutoAttack(false);
            } else configTown.setAutoAttack(false);
          }

          element = elementParent.element("autorecruit");
          if (element != null && element.getText() != null) {
            tmp = element.getText();
            if (tmp.equals("true")) configTown.setAutoRecruit(true);
            else configTown.setAutoRecruit(false);
          } else configTown.setAutoRecruit(false);

          element = elementParent.element("sells");
          if (element != null && element.getText() != null) {
            tmp = element.getText();
            Iterator<Attribute> attributes = element.attributeIterator();
            if (attributes != null) {
              HashMap<String, Double> sells = new HashMap<String, Double>();
              while (attributes.hasNext()) {
                attribute = attributes.next();
                String name = attribute.getName();
                String value = attribute.getText();
                if (!Numeric.isNumber(value)) continue;

                Double rate = Double.parseDouble(value) / 100D;
                sells.put(name, rate);
              }

              if (sells.size() > 0) configTown.setSells(sells);

              if (tmp.equals("true")) configTown.setSell(true);
            }
          }

          element = elementParent.element("buys");
          if (element != null && element.getText() != null) {
            tmp = element.getText();
            Iterator<Attribute> attributes = element.attributeIterator();
            if (attributes != null) {
              HashMap<String, Double> buys = new HashMap<String, Double>();
              while (attributes.hasNext()) {
                attribute = attributes.next();
                String name = attribute.getName();
                String value = attribute.getText();
                if (!Numeric.isNumber(value)) continue;

                Double rate = Double.parseDouble(value) / 100D;
                buys.put(name, rate);
              }

              if (buys.size() > 0) configTown.setBuys(buys);

              if (tmp.equals("true")) configTown.setBuy(true);
            }
          }

          configTowns.add(configTown);
        } catch (NumberFormatException e) {

        }
      }

      config.setConfigTowns(configTowns);
    }

    return config;
  }