Esempio n. 1
0
 public static boolean attributeValueBoolean(Element element, String attr) {
   if (element == null) {
     throw new ServiceException("element is null");
   }
   String value = element.attributeValue(attr);
   if (value == null) {
     throw new ServiceException(String.format("缺少属性%s:%s", attr, element.asXML()));
   }
   try {
     return Boolean.parseBoolean(value);
   } catch (NumberFormatException e) {
     throw new ServiceException(String.format("属性%s不是布尔类型:%s", attr, element.asXML()));
   }
 }
Esempio n. 2
0
 /**
  * 使用document 对象封装XML
  *
  * @param userName
  * @param pwd
  * @param id
  * @param phone
  * @param contents
  * @param sign
  * @param subcode
  * @param sendtime
  * @return
  */
 public String DocXml(
     String userName,
     String pwd,
     String msgid,
     String phone,
     String contents,
     String sign,
     String subcode,
     String sendtime) {
   Document doc = DocumentHelper.createDocument();
   doc.setXMLEncoding("UTF-8");
   Element message = doc.addElement("message");
   Element account = message.addElement("account");
   account.setText(userName);
   Element password = message.addElement("password");
   password.setText(pwd);
   Element msgid1 = message.addElement("msgid");
   msgid1.setText(msgid);
   Element phones = message.addElement("phones");
   phones.setText(phone);
   Element content = message.addElement("content");
   content.setText(contents);
   Element sign1 = message.addElement("sign");
   sign1.setText(sign);
   Element subcode1 = message.addElement("subcode");
   subcode1.setText(subcode);
   Element sendtime1 = message.addElement("sendtime");
   sendtime1.setText(sendtime);
   return message.asXML();
 }
Esempio n. 3
0
 public void updateVCard(String username, Element vCardElement) throws NotFoundException {
   if (loadVCard(username) == null) {
     // The user already has a vCard
     throw new NotFoundException("Username " + username + " does not have a vCard");
   }
   Connection con = null;
   PreparedStatement pstmt = null;
   try {
     con = DbConnectionManager.getConnection();
     pstmt = con.prepareStatement(UPDATE_PROPERTIES);
     pstmt.setString(1, vCardElement.asXML());
     pstmt.setString(2, username);
     pstmt.executeUpdate();
   } catch (SQLException e) {
     Log.error(e);
   } finally {
     try {
       if (pstmt != null) {
         pstmt.close();
       }
     } catch (Exception e) {
       Log.error(e);
     }
     try {
       if (con != null) {
         con.close();
       }
     } catch (Exception e) {
       Log.error(e);
     }
   }
 }
Esempio n. 4
0
  public void createVCard(String username, Element vCardElement) throws AlreadyExistsException {
    if (loadVCard(username) != null) {
      // The user already has a vCard
      throw new AlreadyExistsException("Username " + username + " already has a vCard");
    }

    Connection con = null;
    PreparedStatement pstmt = null;
    try {
      con = DbConnectionManager.getConnection();
      pstmt = con.prepareStatement(INSERT_PROPERTY);
      pstmt.setString(1, username);
      pstmt.setString(2, vCardElement.asXML());
      pstmt.executeUpdate();
    } catch (SQLException e) {
      Log.error(e);
    } finally {
      try {
        if (pstmt != null) {
          pstmt.close();
        }
      } catch (Exception e) {
        Log.error(e);
      }
      try {
        if (con != null) {
          con.close();
        }
      } catch (Exception e) {
        Log.error(e);
      }
    }
  }
Esempio n. 5
0
  public String getMap(String concept) {
    String TypeUri = ConceptEngine.skosPrefix + "#Concept";
    Element root = init();
    Element centerNode = buildCenterNode(concept, TypeUri);
    boolean includeConcept = false;

    String sparql =
        "PREFIX skos: <"
            + ConceptEngine.skosPrefix
            + "#> "
            + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
            + "SELECT distinct ?t "
            + "WHERE {	?x skos:prefLabel '"
            + concept
            + "'. "
            + "       	?x rdf:type	?t .} ";
    QueryResult r;
    try {
      r = QueryEngine.sparql(sparql);
      while (r.next()) {
        String typeUri = r.getString(0);
        if (typeUri.equals(TypeUri)) {
          includeConcept = true;
          continue;
        }
        Element node = nodeArray.addElement("Node").addAttribute("id", nodeID + "");
        node.addElement("Label").addText(concept);
        node.addElement("TypeUri").addText(typeUri);
        String typeLabel = model.getResLabel(typeUri);
        node.addElement("Type").addText(typeLabel);
        nodes.put(concept, node);
        Element edge = edgeArray.addElement("Edge").addAttribute("id", edgeID + "");
        edge.addElement("Label").addText("作为" + typeLabel);
        edge.addElement("TypeUri").addText("as");
        edge.addElement("FromID").addText("1");
        edge.addElement("ToID").addText(nodeID + "");
        nodeID++;
        edgeID++;
      }
    } catch (Exception e) {
      logger.error("Dart Grid: Query Error! --> " + concept + "(RDF.type)");
    }

    List<?> nodeList = nodeArray.elements();
    if (includeConcept) {
      buildMap(centerNode, true);
    }
    int j;
    for (j = 1; j < nodeList.size(); j++) {
      Element node = (Element) nodeList.get(j);
      buildMap(node, false);
    }
    nodeList = nodeArray.elements();
    for (; j < nodeList.size(); j++) {
      Element node = (Element) nodeList.get(j);
      buildMap(node, true);
    }
    return root.asXML();
  }
Esempio n. 6
0
 private void addRelations(
     Element centerNode, String concept, List<?> relations, Boolean isOpposed) {
   if (!isOpposed)
     System.out.println("++++++++++++++" + concept + "++++++++++++++++++" + centerNode.asXML());
   for (int i = 0; i < relations.size(); i++) {
     Element relation = (Element) relations.get(i);
     String propertyUri = relation.attributeValue("propertyUri");
     if (propertyUri.equals(ConceptEngine.ontoPrefix + "#hasRela")) {
       buildRelaMap(centerNode);
       continue;
     }
     if (propertyUri.equals(ConceptEngine.ontoPrefix + "#relaConcept")) continue;
     String propertyLabel = relation.attributeValue("property");
     String objectUri = relation.attributeValue("objectUri");
     String objectLabel = relation.attributeValue("object");
     String sparql = ConceptEngine.getContentSparql(concept, propertyUri, false, isOpposed);
     QueryResult r;
     try {
       r = QueryEngine.sparql(sparql);
       if (r == null) continue;
       int ct = 0;
       while (r.next() && ct < count) {
         ct++;
         String content = r.getString(0);
         Element node = null;
         Boolean isNewNode = true;
         if (nodes.containsKey(content)) {
           Element e = (Element) nodes.get(content);
           if (e.elementText("TypeUri").equals(objectUri)) {
             isNewNode = false;
             node = e;
           }
         }
         if (isNewNode) {
           node = nodeArray.addElement("Node").addAttribute("id", nodeID++ + "");
           node.addElement("Label").addText(content);
           node.addElement("TypeUri").addText(objectUri);
           node.addElement("Type").addText(objectLabel);
           nodes.put(content, node);
         }
         Element edge = edgeArray.addElement("Edge").addAttribute("id", edgeID++ + "");
         edge.addElement("Label").addText(propertyLabel);
         edge.addElement("TypeUri").addText(propertyUri);
         edge.addElement("FromID")
             .addText(isOpposed ? node.attributeValue("id") : centerNode.attributeValue("id"));
         edge.addElement("ToID")
             .addText(isOpposed ? centerNode.attributeValue("id") : node.attributeValue("id"));
       }
     } catch (java.lang.NullPointerException e) {
       logger.error("Dart Grid: Query Error! --> " + concept + "(" + propertyLabel + ")");
       r = null;
       e.printStackTrace();
     }
   }
   // if(isOpposed)
   //	System.out.println("++++++++++++++++++++++++++++++++");
 }
Esempio n. 7
0
 public static String attributeValueString(Element element, String attr) {
   if (element == null) {
     throw new ServiceException("element is null");
   }
   String value = element.attributeValue(attr);
   if (value == null) {
     throw new ServiceException(String.format("缺少属性%s:%s", attr, element.asXML()));
   }
   return value;
 }
Esempio n. 8
0
  /**
   * Process the received stanza using the given XMPP packet reader.
   *
   * @param stanza the received statza
   * @param reader the XMPP packet reader
   * @throws Exception if the XML stream is not valid.
   */
  public void process(String stanza, XMPPPacketReader reader) throws Exception {
    boolean initialStream = stanza.startsWith("<stream:stream");
    if (!sessionCreated || initialStream) {
      if (!initialStream) {
        return; // Ignore <?xml version="1.0"?>
      }
      if (!sessionCreated) {
        sessionCreated = true;
        MXParser parser = reader.getXPPParser();
        parser.setInput(new StringReader(stanza));
        createSession(parser);
      } else if (startedTLS) {
        startedTLS = false;
        tlsNegotiated();
      }
      return;
    }

    // If end of stream was requested
    if (stanza.equals("</stream:stream>")) {
      session.close();
      return;
    }
    // Ignore <?xml version="1.0"?>
    if (stanza.startsWith("<?xml")) {
      return;
    }
    // Create DOM object
    Element doc = reader.read(new StringReader(stanza)).getRootElement();
    if (doc == null) {
      return;
    }

    String tag = doc.getName();
    if ("starttls".equals(tag)) {
      if (negotiateTLS()) { // Negotiate TLS
        startedTLS = true;
      } else {
        connection.close();
        session = null;
      }
    } else if ("message".equals(tag)) {
      processMessage(doc);
    } else if ("presence".equals(tag)) {
      log.debug("presence...");
      processPresence(doc);
    } else if ("iq".equals(tag)) {
      log.debug("iq...");
      processIQ(doc);
    } else {
      log.warn("Unexpected packet tag (not message, iq, presence)" + doc.asXML());
      session.close();
    }
  }
Esempio n. 9
0
  /** Convert the parameters in string array form to their XML representation */
  public static String prepareParams(String... params) {
    Element root = DocumentHelper.createElement(TAG_PARAMS);

    // add individual parameters
    for (String param : params) {
      Element param0 = DocumentHelper.createElement(TAG_PARAM);
      param0.add(DocumentHelper.createText(param));
      root.add(param0);
    }
    return root.asXML();
  }
Esempio n. 10
0
  /**
   * 获得同义词,即由词获得以此词为概念词的异名,或以此词为异名的概念词
   *
   * @param word
   * @return 同义词XML字符串 例如:搜索"大黄"的同义词,返回XML: <thesauruses> <concept>水黄</concept>
   *     <concept>小大黄</concept> <concept>山大黄</concept> <alias>Dheum Officinale</alias>
   *     <alias>肤如</alias> <alias>黄良</alias> <alias>da huang</alias> <alias>牛舌大黄</alias>
   *     <alias>川军</alias> <alias>蜀大黄</alias> <alias>锦纹</alias> <alias>生军</alias> <alias>火参</alias>
   *     <alias>将军</alias> <alias>锦纹大黄</alias> <alias>RHEUM OFFICINALE</alias> <alias>Rheum palmatum
   *     L.;Rheum tanguticum Maxim.ex Balf.;Rheum officinale Baill.</alias> <alias>Radix et Rhizoma
   *     Rhei(拉);rhubarb root and rhizome</alias> </thesauruses>
   */
  private static String getThesaurus(String word) {
    Document doc = DocumentHelper.createDocument();
    Element e = doc.addElement("thesauruses");

    List<String> thesauruses = ConceptEngine.getConceptByAlias(word);
    for (int i = 0; i < thesauruses.size(); i++)
      e.addElement("concept").setText(thesauruses.get(i));

    thesauruses = ConceptEngine.getAliasByConcept(word);
    for (int i = 0; i < thesauruses.size(); i++) e.addElement("alias").setText(thesauruses.get(i));

    return e.asXML();
  }
Esempio n. 11
0
  public String getMap(String concept, String typeUri) {
    if (typeUri == null || typeUri.equals("")) return getMap(concept);
    Element root = init();
    Element centerNode = buildCenterNode(concept, typeUri);

    buildMap(centerNode, true);
    List<?> nodeList = nodeArray.elements();
    for (int j = 1; j < nodeList.size(); j++) {
      Element node = (Element) nodeList.get(j);
      buildMap(node, true);
    }
    return root.asXML();
  }
Esempio n. 12
0
  @Test
  public void testMap2AttributeNode() {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("email", "*****@*****.**");
    map.put("age", new Integer(24));
    map.put("addr", null);

    Element node = XMLDocUtil.map2AttributeNode(map, "row");
    assertEquals("<row email=\"[email protected]\" age=\"24\"/>", node.asXML());

    assertEquals(2, XMLDocUtil.dataNode2Map(node).size());
    assertEquals("", XMLDocUtil.getNodeText(node));
  }
  private synchronized void doConfigClearspace() throws UnauthorizedException {

    Log.debug("Starting Clearspace configuration.");

    List<String> bindInterfaces = getServerInterfaces();
    if (bindInterfaces.size() == 0) {
      // We aren't up and running enough to tell Clearspace what interfaces to bind to.
      Log.debug("No bind interfaces found to config Clearspace");
      throw new IllegalStateException("There are no binding interfaces.");
    }

    try {

      XMPPServerInfo serverInfo = XMPPServer.getInstance().getServerInfo();

      String path = IM_URL_PREFIX + "configureComponent/";

      // Creates the XML with the data
      Document groupDoc = DocumentHelper.createDocument();
      Element rootE = groupDoc.addElement("configureComponent");
      Element domainE = rootE.addElement("domain");
      domainE.setText(serverInfo.getXMPPDomain());
      for (String bindInterface : bindInterfaces) {
        Element hostsE = rootE.addElement("hosts");
        hostsE.setText(bindInterface);
      }
      Element portE = rootE.addElement("port");
      portE.setText(String.valueOf(ExternalComponentManager.getServicePort()));

      Log.debug(
          "Trying to configure Clearspace with: Domain: "
              + serverInfo.getXMPPDomain()
              + ", hosts: "
              + bindInterfaces.toString()
              + ", port: "
              + port);

      executeRequest(POST, path, rootE.asXML());

      // Done, Clearspace was configured correctly, clear the task
      Log.debug("Clearspace was configured, stopping the task.");
      TaskEngine.getInstance().cancelScheduledTask(configClearspaceTask);
      configClearspaceTask = null;

    } catch (UnauthorizedException ue) {
      throw ue;
    } catch (Exception e) {
      // It is not supported exception, wrap it into an UnsupportedOperationException
      throw new UnsupportedOperationException("Unexpected error", e);
    }
  }
Esempio n. 14
0
 public static int attributeValueInt(Element element, String attr, int defaultValue) {
   if (element == null) {
     throw new ServiceException("element is null");
   }
   String value = element.attributeValue(attr);
   if (value == null) {
     return defaultValue;
   }
   try {
     return Integer.parseInt(value);
   } catch (NumberFormatException e) {
     throw new ServiceException(String.format("属性%s不是数值类型:%s", attr, element.asXML()));
   }
 }
  /**
   * Looks up and modifies a user's CS properties to indicate whether they are enabled or disabled.
   * It is important for this to incorporate the existing user data and only tweak the field that we
   * want to change.
   *
   * @param username Username of user to set status of.
   * @param enabled Whether the account should be enabled or disabled.
   */
  private void setEnabledStatus(String username, Boolean enabled) {
    try {
      Element user = getUserByUsername(username);
      Element modifiedUser =
          modifyUser(user.element("return"), "enabled", enabled ? "true" : "false");

      String path = USER_URL_PREFIX + "users";
      ClearspaceManager.getInstance().executeRequest(PUT, path, modifiedUser.asXML());
    } catch (UserNotFoundException e) {
      Log.error("User with name " + username + " not found.", e);
    } catch (Exception e) {
      // It is not supported exception, wrap it into an UnsupportedOperationException
      throw new UnsupportedOperationException("Unexpected error", e);
    }
  }
Esempio n. 16
0
 public String buildPeqParamValue(String OrderId) {
   Map<String, String> ParamMap = new LinkedHashMap<String, String>();
   ParamMap.put("OrderId", "" + OrderId);
   Document document = DocumentHelper.createDocument();
   /** 建立XML文档的根 */
   Element rootElement = document.addElement("ReqParam");
   rootElement.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
   rootElement.addAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
   Element ticketElement = rootElement.addElement("ticket");
   for (String key : ParamMap.keySet()) {
     String value = ParamMap.get(key);
     Element element = ticketElement.addElement(key);
     element.setText(value);
   }
   return "<?xml version=\"1.0\"?>" + rootElement.asXML();
 }
  /*
   * @see com.painiu.core.service.api.ResponseFormat#format(java.io.Writer, java.lang.Object)
   */
  public void format(Writer out, Object object) throws IOException {
    XmlRpcResponseProcessor processor = new XmlRpcResponseProcessor();

    String result = null;

    if (object instanceof ApiException) {
      ApiException apiEx = (ApiException) object;
      Exception e = apiEx;

      if (apiEx.getCall() != null) {
        e = new DebuggableApiException(apiEx);
      }

      result =
          new String(
              processor.encodeException(e, ENCODING, Integer.parseInt(apiEx.getCode())), ENCODING);

    } else if (object == null || object instanceof ApiObject) {
      String restResult = null;

      if (object == null) {
        restResult = "";
      } else {
        Document doc = createDocument();
        Element root = doc.addElement("rsp");
        createElement(root, (ApiObject) object);

        restResult = root.asXML();

        restResult = restResult.substring(5, restResult.length() - 6);
      }

      try {
        result = new String(processor.encodeResponse(restResult, ENCODING), ENCODING);
      } catch (Exception e) {
        // should not happen
        e.printStackTrace();
      }

    } else {
      throw new IllegalArgumentException("unsupported object");
    }

    out.write(result);
  }
  @Test
  public void testCreatingDocument() {
    Element invoiceDocument = new DefaultElement("invoiceDocument");
    Document doc = DocumentHelper.createDocument(invoiceDocument);
    Element root = doc.getRootElement();
    root.addAttribute("createdDate", XMLDateFormatter.getXMLFormat(new Date()));

    Element buyerType = new DefaultElement("buyer");
    buyerType.addAttribute("id", "00192");
    buyerType.add(createNameElement("this is buyer name"));
    buyerType.add(createStreetAddressOne("address1"));
    buyerType.add(createStreetAddressTwo("address2"));
    buyerType.add(createPhoneNumber("Jln. kemanggisan II no 3"));

    Element sellerType = new DefaultElement("seller");
    sellerType.addAttribute("id", "0011");
    sellerType.add(createNameElement("this is seller name"));
    sellerType.add(createStreetAddressOne("address1"));
    sellerType.add(createStreetAddressTwo("address2"));
    sellerType.add(createPhoneNumber("Jln. kemanggisan II no 3"));

    Element invoiceSummary = new DefaultElement("invoiceSummary");
    invoiceSummary.addElement("invoiceTotal").addText("120000");
    invoiceSummary.addElement("remark");

    root.add(buyerType);
    root.add(sellerType);
    root.add(invoiceSummary);

    for (int i = 0; i < 3; i++) {
      Element tradeItem = new DefaultElement("tradeITem");
      tradeItem.addAttribute("number", "" + i);
      tradeItem.addElement("gtin").addText("00000000000" + i);
      Element additionalTradeInformation = tradeItem.addElement("additionalTradeInformation");
      additionalTradeInformation.add(
          createTradeItemAdditionalInformation("serial_number", "00000" + i));
      additionalTradeInformation.add(
          createTradeItemAdditionalInformation("price", "" + (i + 1) * 1000));
      additionalTradeInformation.add(
          createTradeItemAdditionalInformation("quantity", "" + (i + 1) * 10));
      root.add(tradeItem);
    }

    System.out.println(root.asXML());
  }
Esempio n. 19
0
 /**
  * xml to list xml <nodes><node><key label="key1">value1</key><key
  * label="key2">value2</key>......</node><node><key label="key1">value1</key><key
  * label="key2">value2</key>......</node></nodes>
  *
  * @param xml
  * @return
  */
 public static List xmltoList(String xml) {
   try {
     List<Map> list = new ArrayList<Map>();
     Document document = DocumentHelper.parseText(xml);
     Element nodesElement = document.getRootElement();
     List nodes = nodesElement.elements();
     for (Iterator its = nodes.iterator(); its.hasNext(); ) {
       Element nodeElement = (Element) its.next();
       Map map = xmltoMap(nodeElement.asXML());
       list.add(map);
       map = null;
     }
     nodes = null;
     nodesElement = null;
     document = null;
     return list;
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
Esempio n. 20
0
  @Override
  protected void readData(org.dom4j.Element rootElement) throws Exception {
    for (Iterator<org.dom4j.Element> npcIterator = rootElement.elementIterator();
        npcIterator.hasNext(); ) {
      org.dom4j.Element npcElement = npcIterator.next();
      int npcId = Integer.parseInt(npcElement.attributeValue("id"));

      L2onNpcInfo info = L2onNpcHolder.getInstance().getNpcInfoNoCreate(npcId);

      if (info == null || info._level == 0) {
        System.out.println("Missing data " + npcId);
        continue;
      }

      for (Iterator<org.dom4j.Element> firstIterator = npcElement.elementIterator();
          firstIterator.hasNext(); ) {
        org.dom4j.Element firstElement = firstIterator.next();
        if (firstElement.getName().equalsIgnoreCase("set")) {
          if (firstElement.attributeValue("name").equalsIgnoreCase("rewardExp")) {
            firstElement.addAttribute("value", String.valueOf(info._exp));
          }
          if (firstElement.attributeValue("name").equalsIgnoreCase("rewardSp")) {
            firstElement.addAttribute("value", String.valueOf(info._sp));
          }
          if (firstElement.attributeValue("name").equalsIgnoreCase("level")) {
            firstElement.addAttribute("value", String.valueOf(info._level));
          }
          if (firstElement.attributeValue("name").equalsIgnoreCase("baseHpMax")) {
            firstElement.addAttribute("value", String.valueOf(info._hp));
          }
        }
      }
    }

    XmlPretty.writeToFile(
        getCurrentFileName().replace(".xml", ""),
        rootElement.asXML(),
        "npc.dtd",
        "data/blood_npc/");
  }
Esempio n. 21
0
  private void checkMatchingConflict(
      final Element element, final LinkedList<Pair<XMLPattern, SimpleAutomatonID>> matchings) {
    if (!logger.isDebugEnabled()) return;

    boolean same = true;
    final Set<String> names = new HashSet<String>();
    names.add(matchings.getFirst().getFirst().getName());
    for (final Pair<XMLPattern, SimpleAutomatonID> match : matchings)
      if (names.add(match.getFirst().getName())) {
        same = false;
        break;
      }
    if (!same) {
      logger.debug("This code:");
      logger.debug(element.asXML());
      logger.debug("can be matched by more than one " + "distinct rule:");
      for (final Pair<XMLPattern, SimpleAutomatonID> match : matchings) {
        final XMLPattern pat = match.getFirst();
        logger.debug(pat.getName() + ": " + pat.getPatternXMLelement().asXML());
      }
    }
  }
Esempio n. 22
0
  @Test
  public void testMap2DataNode() {

    new XMLDocUtil();

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("tel", new Object[] {"057188889999", "13588899889"});
    map.put("email", "*****@*****.**");
    map.put("age", new Integer(24));
    map.put("id", new Object[] {new Integer(23), "<![CDATA[sss]]>"});
    map.put("addr", null);

    Element node = XMLDocUtil.map2DataNode(map, "row");

    String dataXml =
        "<row><id><![CDATA[23]]></id><id><![CDATA[&lt;![CDATA[sss]]&gt;]]></id><email><![CDATA[[email protected]]]></email><age><![CDATA[24]]></age><tel><![CDATA[057188889999]]></tel><tel><![CDATA[13588899889]]></tel></row>";
    assertEquals(dataXml, node.asXML());

    XMLDocUtil.dataNodes2Map(node);
    XMLDocUtil.dataXml2Doc(dataXml);

    try {
      XMLDocUtil.dataXml2Doc(dataXml + "<error>");
    } catch (Exception e) {
      Assert.assertTrue("由dataXml生成doc出错", true);
    }

    try {
      XMLDocUtil.createDoc("META-INF/notExsits.xml");
    } catch (Exception e) {
      Assert.assertTrue("定义的文件没有找到", true);
    }

    Document doc = XMLDocUtil.createDoc("tss/cache.xml");
    XMLDocUtil.getNodeText(node);

    XMLDocUtil.selectNodes(doc, "//id");
    XMLDocUtil.selectNodes(node, "//tel");
  }
Esempio n. 23
0
  /**
   * Handles packets that includes a data form. The data form was sent using an element with name
   * "x" and namespace "jabber:x:data".
   *
   * @param senderRole the role of the user that sent the data form.
   * @param formElement the element that contains the data form specification.
   * @throws ForbiddenException if the user does not have enough privileges.
   * @throws ConflictException If the room was going to lose all of its owners.
   */
  private void handleDataFormElement(MUCRole senderRole, Element formElement)
      throws ForbiddenException, ConflictException {
    DataForm completedForm = new DataForm(formElement);

    switch (completedForm.getType()) {
      case cancel:
        // If the room was just created (i.e. is locked) and the owner cancels the configuration
        // form then destroy the room
        if (room.isLocked()) {
          room.destroyRoom(null, null);
        }
        break;

      case submit:
        // The owner is requesting an instant room
        if (completedForm.getFields().isEmpty()) {
          // Do nothing
        }
        // The owner is requesting a reserved room or is changing the current configuration
        else {
          processConfigurationForm(completedForm, senderRole);
        }
        // If the room was locked, unlock it and send to the owner the "room is now unlocked"
        // message
        if (room.isLocked() && !room.isManuallyLocked()) {
          room.unlock(senderRole);
        }
        if (!room.isDestroyed) {
          // Let other cluster nodes that the room has been updated
          CacheFactory.doClusterTask(new RoomUpdatedEvent(room));
        }
        break;

      default:
        Log.warn("cannot handle data form element: " + formElement.asXML());
        break;
    }
  }
Esempio n. 24
0
  /** 组装actionModel */
  @Override
  public void parse() throws Exception {
    // 读取对应的配置文件
    XmlUtils xmlUtils = new XmlUtils();
    xmlUtils.createXml(((Action) this.model).getConfig());

    // Action生成的动态文件模型
    DynamicActionFileModel fileModel = new DynamicActionFileModel(((Action) model));

    // Action生成的动态执行方法模型
    DynamicActionExecuteMethodModel execute = new DynamicActionExecuteMethodModel();
    execute.setReturnType("void");

    // Action调用逻辑的代码片段
    StringBuffer sb = new StringBuffer("");

    Parse parse = new Parse(new ParseEngineFactory());

    /** 解析对象池定义放入Action对象中的poolVariable */
    if (xmlUtils.getNodeList("//action/pool/object").size() != 0) {
      List<Element> objectList = xmlUtils.getNodeList("//action/pool/object");
      List<String[]> pool = new ArrayList<String[]>();
      for (Element e : objectList) {
        pool.add(new String[] {e.elementTextTrim("name"), e.elementTextTrim("type")});
      }
      ((Action) model).setPoolVariable(pool);
    }

    /** 解析handle */
    int order = 0;
    List<Element> handlesList = xmlUtils.getNodeList("//action/handles/content");
    for (int i = 0; handlesList != null && handlesList.size() > 0 && i < handlesList.size(); i++) {
      Element handleConfig = handlesList.get(i);

      Handle handle = new Handle();
      handle.setAction((Action) model);
      handle.setExecuteOrder(Integer.parseInt(handleConfig.attributeValue("execute-order")));
      handle.setHandleType(handleConfig.attributeValue("type"));
      handle.setHandle(handleConfig.asXML());

      parse.parse(handle);

      sb.append("\n\t\t\t" + handle.getMethod().getCodeSegment());
      execute.appendImports(handle.getMethod().getImports());
      execute.appendGlobalVariables(handle.getMethod().getGlobalVariables());

      order++;
    }

    // 全局变量
    fileModel.appendGlobalVariable(
        "DataProcessEngine dataProcessEngine = new DataProcessEngine();");
    // 引入包
    fileModel.appendImport(" com.dhcc.itsm.form.runtime.FormContext");
    fileModel.appendImport("java.util.*");
    fileModel.appendImport("com.dhcc.itsm.form.engine.core.parseEngine.DataProcessEngine");
    fileModel.appendImport("com.dhcc.itsm.form.runtime.webapp.action.RuntimeAction");
    // 为execute方法设置代码片段
    execute.setCodeSegment(sb.toString());
    // 为Action生成的动态文件模型添加execute方法
    fileModel.addMethod(execute);

    ((Action) model).setFile(fileModel);
  }
Esempio n. 25
0
  public List<CpResultVisitor> sendTicket(List<Ticket> ticketList)
      throws DataException, IOException, DocumentException {

    Document document = DocumentHelper.createDocument();
    /** 建立XML文档的根 */
    Element rootElement = document.addElement("ReqParam");
    rootElement.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    rootElement.addAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
    for (Ticket ticket : ticketList) {
      Map<String, String> paramMap = buildPeqParamValue(ticket);
      Element ticketElement = rootElement.addElement("Ticket");
      for (String key : paramMap.keySet()) {
        String value = paramMap.get(key);
        Element element = ticketElement.addElement(key);
        element.setText(value);
      }
    }
    String peqParamValue = "<?xml version=\"1.0\"?>" + rootElement.asXML();
    String msgIdValue = System.currentTimeMillis() + "";
    String reqIdValue = "801";

    Map<String, String> ParamMap = new LinkedHashMap<String, String>();
    ParamMap.put("ReqId", reqIdValue);
    ParamMap.put("MsgId", msgIdValue);
    ParamMap.put("ReqParam", peqParamValue);
    ParamMap.put(
        "ReqKey",
        SecurityUtil.md5((reqIdValue + msgIdValue + peqParamValue + key).getBytes("UTF-8"))
            .toLowerCase());

    // ParamMap.put("ReqKey",
    // SecurityUtil.md5(reqIdValue+msgIdValue+peqParamValue+key).toLowerCase());

    // String url = getReUrl(reqIdValue,msgIdValue,peqParamValue);

    String returnString = HttpclientUtil.Utf8HttpClientUtils(reUrl, ParamMap);
    Document doc = DocumentHelper.parseText(returnString);
    Element root = doc.getRootElement();
    List<CpResultVisitor> returnList = Lists.newArrayList();
    for (Iterator i = root.elementIterator("Ticket"); i.hasNext(); ) {
      String ResultId = null;
      String OrderId = null;
      try {
        Element element = (Element) i.next();
        ResultId = element.selectSingleNode("ResultId").getText();
        OrderId = element.selectSingleNode("OrderId").getText();
        CpResultVisitor cpResultVisitor = new CpResultVisitor();
        /// 是否成功
        if (StringUtils.isNotBlank(ResultId)) {
          if (String.valueOf("0").equals(ResultId.trim())
              || String.valueOf("2").equals(ResultId.trim())) {
            /// 0成功2重复
            cpResultVisitor.setIsSuccess(Boolean.TRUE);
          }
          cpResultVisitor.setResult(ResultId);
        }
        if (StringUtils.isNotBlank(OrderId)) {
          cpResultVisitor.setOrderId(OrderId);
        }
        returnList.add(cpResultVisitor);
      } catch (Exception e) {
        logger.error("发送彩票出现错误[ResultId]" + ResultId + "[OrderId]" + OrderId + e.getMessage());
        continue;
      }
    }
    return returnList;
  }
  /*
   * (non-Javadoc)
   *
   * @see de.tud.kom.p2psim.api.scenario.HostBuilder#parse(org.dom4j.Element,
   * de.tud.kom.p2psim.api.scenario.Configurator)
   */
  public void parse(Element elem, Configurator config) {
    DefaultConfigurator defaultConfigurator = (DefaultConfigurator) config;

    // create groups
    for (Iterator iter = elem.elementIterator(); iter.hasNext(); ) {
      Element groupElem = (Element) iter.next();
      String groupID = groupElem.attributeValue(GROUP_ID_TAG);
      if (groupID == null) {
        throw new IllegalArgumentException(
            "Id of host/group " + groupElem.asXML() + " must not be null");
      }

      // either a group of hosts or a single host (=group with size 1)
      int groupSize;
      if (groupElem.getName().equals(HOST_TAG)) {
        groupSize = 1;
      } else if (groupElem.getName().equals(GROUP_TAG)) {
        String attributeValue = config.parseValue(groupElem.attributeValue(GROUP_SIZE_TAG));
        groupSize = Integer.parseInt(attributeValue);
      } else {
        throw new IllegalArgumentException("Unexpected tag " + groupElem.getName());
      }
      List<Host> group = new ArrayList<Host>(groupSize);

      // create hosts and instances of specified components for each host
      for (int i = 0; i < groupSize; i++) {

        DefaultHost host = new DefaultHost();

        // initialize properties
        DefaultHostProperties hostProperties = new DefaultHostProperties();
        host.setProperties(hostProperties);
        // minimal information for host properties is the group id
        hostProperties.setGroupID(groupID);

        // initialize layers and properties
        for (Iterator layers = groupElem.elementIterator(); layers.hasNext(); ) {
          Element layerElem = (Element) layers.next();
          if (layerElem.getName().equals(Configurator.HOST_PROPERTIES_TAG)) {
            defaultConfigurator.configureAttributes(hostProperties, layerElem);
          } else {
            // layer component factory
            ComponentFactory layer =
                (ComponentFactory) defaultConfigurator.configureComponent(layerElem);
            Component comp = layer.createComponent(host);

            setComponent(host, comp);
          }
        }
        group.add(host);
      }
      log.debug("Created a group with " + group.size() + " hosts");
      hosts.addAll(group);
      groups.put(groupID, group);
    }
    log.info("CREATED " + hosts.size() + " hosts");
    if (hosts.size() != experimentSize) {
      log.warn(
          "Only "
              + hosts.size()
              + " hosts were specified, though the experiment size was set to "
              + experimentSize);
    }
  }
Esempio n. 27
0
  public static String JpdlGen(String drawXml, String processName) {
    if (logger.isDebugEnabled()) {
      logger.debug("drawXml:" + drawXml);
    }

    Document jpdlDoc = DocumentHelper.createDocument();

    jpdlDoc.setXMLEncoding("utf-8");

    Element processEl = jpdlDoc.addElement("process");

    processEl.addAttribute("name", processName);

    Document drawDoc = XmlUtil.stringToDocument(drawXml);
    Element orgRootEl = drawDoc.getRootElement();

    Set transitionSet = new HashSet();

    Map nodeMap = parseDrawXml(transitionSet, orgRootEl);

    Map newNodeMap = new LinkedHashMap();
    Iterator ids = nodeMap.keySet().iterator();

    while (ids.hasNext()) {
      String id = (String) ids.next();
      Element pNode = (Element) nodeMap.get(id);
      Element curNewNode = processEl.addElement(pNode.getQualifiedName());
      String x = pNode.attributeValue("x");
      String y = pNode.attributeValue("y");

      String width = pNode.attributeValue("w");
      Integer intWidth = Integer.valueOf(new Integer(width).intValue() + 5);

      String height = pNode.attributeValue("h");
      Integer intHeight = Integer.valueOf(new Integer(height).intValue() + 15);

      curNewNode.addAttribute("name", pNode.attributeValue("name"));
      curNewNode.addAttribute(
          "g",
          new Integer(x).intValue()
              - 12
              + ","
              + (new Integer(y).intValue() - 8)
              + ","
              + intWidth
              + ","
              + intHeight);

      newNodeMap.put(id, curNewNode);
    }

    Iterator tranIt = transitionSet.iterator();

    while (tranIt.hasNext()) {
      Element tranEl = (Element) tranIt.next();
      String g = tranEl.attributeValue("g");
      String name = tranEl.attributeValue("name");

      Element startNode = (Element) tranEl.selectSingleNode("./startConnector/rConnector/Owner/*");
      Element endNode = (Element) tranEl.selectSingleNode("./endConnector/rConnector/Owner/*");

      if ((startNode != null) && (endNode != null)) {
        String startRef = startNode.attributeValue("ref");
        String endRef = endNode.attributeValue("ref");
        Element newEndNode;
        Element newStartNode;
        if ((startRef != null) && (endRef != null)) {
          newStartNode = (Element) newNodeMap.get(startRef);
          newEndNode = (Element) newNodeMap.get(endRef);
        } else {
          String startId = startNode.attributeValue("id");
          String endId = startNode.attributeValue("id");
          newStartNode = (Element) newNodeMap.get(startId);
          newEndNode = (Element) newNodeMap.get(endId);
        }

        Element transitionEl = newStartNode.addElement("transition");
        transitionEl.addAttribute("name", name);
        transitionEl.addAttribute("to", newEndNode.attributeValue("name"));
        transitionEl.addAttribute("g", g);

        if ("decision".equals(newStartNode.getQualifiedName())) {
          Element conditionEl =
              (Element)
                  orgRootEl.selectSingleNode(
                      "/drawing/figures//decision/conditions/condition[@to='" + name + "']");
          if (conditionEl != null) {
            Element newConditionEl = transitionEl.addElement("condition");
            newConditionEl.addAttribute("expr", conditionEl.attributeValue("expr"));
          }
        }
      }
    }

    if (logger.isDebugEnabled()) {
      logger.debug("after convter jbpm xml:" + processEl.asXML());
    }

    return jpdlDoc.asXML();
  }
Esempio n. 28
0
  private void processTarget(Element targetNode, Element outProjectNode)
      throws IOException, DocumentException {
    String targetName = targetNode.attributeValue("name");
    log("Processing target: " + targetName, Project.MSG_DEBUG);

    // Add documentation
    // Get comment element before the target element to extract target doc
    String commentText = "";
    List children = targetNode.selectNodes("preceding-sibling::node()");
    if (children.size() > 0) {
      // Scan past the text nodes, which are most likely whitespace
      int index = children.size() - 1;
      Node child = (Node) children.get(index);
      while (index > 0 && child.getNodeType() == Node.TEXT_NODE) {
        index--;
        child = (Node) children.get(index);
      }

      // Check if there is a comment node
      if (child.getNodeType() == Node.COMMENT_NODE) {
        Comment targetComment = (Comment) child;
        commentText = targetComment.getStringValue().trim();

        log(targetName + " comment: " + commentText, Project.MSG_DEBUG);
      } else {
        log("Target has no comment: " + targetName, Project.MSG_WARN);
      }

      Node previousNode = (Node) children.get(children.size() - 1);
    }

    if (!commentText.contains("Private:")) {
      Element outTargetNode = outProjectNode.addElement("target");

      addTextElement(outTargetNode, "name", targetNode.attributeValue("name"));
      addTextElement(outTargetNode, "ifDependency", targetNode.attributeValue("if"));
      addTextElement(outTargetNode, "unlessDependency", targetNode.attributeValue("unless"));
      addTextElement(outTargetNode, "description", targetNode.attributeValue("description"));
      addTextElement(outTargetNode, "tasks", String.valueOf(targetNode.elements().size()));

      // Add location
      Project project = getProject();
      Target antTarget = (Target) project.getTargets().get(targetName);

      if (antTarget == null) return;

      addTextElement(outTargetNode, "location", antTarget.getLocation().toString());

      // Add dependencies
      Enumeration dependencies = antTarget.getDependencies();
      while (dependencies.hasMoreElements()) {
        String dependency = (String) dependencies.nextElement();
        Element dependencyElement = addTextElement(outTargetNode, "dependency", dependency);
        dependencyElement.addAttribute("type", "direct");
      }

      callAntTargetVisitor(targetNode, outTargetNode, outProjectNode);

      // Process the comment text as MediaWiki syntax and convert to HTML
      insertDocumentation(outTargetNode, commentText);

      // Get names of all properties used in this target
      ArrayList properties = new ArrayList();
      Visitor visitor = new AntPropertyVisitor(properties);
      targetNode.accept(visitor);
      for (Iterator iterator = properties.iterator(); iterator.hasNext(); ) {
        String property = (String) iterator.next();
        addTextElement(outTargetNode, "propertyDependency", property);
      }

      // Add the raw XML content of the element
      String targetXml = targetNode.asXML();
      // Replace the CDATA end notation to avoid nested CDATA sections
      targetXml = targetXml.replace("]]>", "] ]>");

      addTextElement(outTargetNode, "source", targetXml, true);
    }
  }
Esempio n. 29
0
 /**
  * Returns the textual XML representation of this packet.
  *
  * @return the textual XML representation of this packet.
  */
 public String toXML() {
   return element.asXML();
 }
Esempio n. 30
0
  /** Parse Node /apps/app */
  @SuppressWarnings("unchecked")
  private boolean parseAppNode(AppConfig config, Element appElm, int index) throws Exception {
    if (null == appElm) {
      return false;
    }

    // String version = null == versionOnZones ? "1.0" : versionOnZones;
    // Attribute versonAttr = (Attribute)
    // appNode.selectSingleNode("@version");
    // if (null != versonAttr) {
    // version = versonAttr.getStringValue();
    // }

    assert config != null;
    try {
      String name = XMLHelper.getTextTrim(appElm, "name");
      String displayName = XMLHelper.getTextTrim(appElm, "display-name", Strings.EMPTY_STRING);
      String logo = XMLHelper.getTextTrim(appElm, "logo", Strings.EMPTY_STRING);
      String version = XMLHelper.getTextTrim(appElm, "version", Strings.EMPTY_STRING);
      String desc = XMLHelper.getTextTrim(appElm, "description", Strings.EMPTY_STRING);
      String authorInfo = XMLHelper.getTextTrim(appElm, "author-info");
      Date createTime =
          DateUtil.safeParseDate(XMLHelper.getTextTrim(appElm, "create-time"), DateUtil.ssdf);

      config.setName(name);
      config.setDisplayName(displayName);
      config.setLogo(logo);
      config.setVersion(version);
      config.setDesc(desc);
      config.setAuthorInfo(authorInfo);
      config.setCreateTime(createTime);

      String configVersion = XMLHelper.getAttributeString(appElm, "@version", "1.0");

      String type = XMLHelper.getAttributeString(appElm, "@type");
      String buildInAppName = XMLHelper.getTextTrim(appElm, "buildin-app-name");

      Short shortType = AppConstants.DISPLAY_APP_TYPE.inverse().get(type);
      if (null == type) {
        throw new AppException("Type invalid for " + name);
      }
      config.setType(null == shortType ? AppConstants.APPTYEP_EMPTY : shortType);
      config.setBuildInAppName(buildInAppName);

      List<Element> zones = (List<Element>) appElm.selectNodes("zones/zone");
      if (null != zones) {
        for (Element zone : zones) {
          String zoneType = XMLHelper.getAttributeString(zone, "@type", type);
          if (null == zoneType) {
            continue;
          }
          AppZone appZone = new AppZone();
          Short zoneTypeCode = AppConstants.DISPLAY_APP_TYPE.inverse().get(zoneType);
          appZone.setAppType(zoneTypeCode);
          appZone.setSize(XMLHelper.getAttributeString(zone, "@zoneSize"));
          appZone.setHeight(XMLHelper.getTextTrim(zone, "height"));
          appZone.setWidth(XMLHelper.getTextTrim(zone, "width"));

          // for buildin app
          if (AppConstants.APPTYPE_BUILDIN == zoneTypeCode) {
            appZone.setBuildinAppName(
                XMLHelper.getTextTrim(zone, "buildin-app-name", buildInAppName));
          } else if (AppConstants.APPTYPE_IFRAME == zoneTypeCode) {
            appZone.setBuildinAppName(IFramePortlet.class.getSimpleName());
            appZone.setPathTemplate(XMLHelper.getTextTrim(zone, "path"));
          } else if (AppConstants.APPTYPE_URL == zoneTypeCode) {
            appZone.setBuildinAppName(URLPortlet.class.getSimpleName());
            appZone.setPathTemplate(XMLHelper.getTextTrim(zone, "path"));
          } else if (AppConstants.APPTYEP_EMPTY == zoneTypeCode) {
            // appZone.setBuildinAppName(URLPortlet.class.getSimpleName());
            // appZone.setPathTemplate(XMLHelper.getTextTrim(zone,
            // "path"));
          }

          config.addPage(appZone);
        }
      }

      String status = XMLHelper.getTextTrim(appElm, "status");
      if ("disabled".equalsIgnoreCase(status)) {
        config.setStatus(AppConstants.STATUS_DISABLED);
      } else if ("platform".equalsIgnoreCase(status)) {
        config.setStatus(AppConstants.STATUS_PENDING);
      } else {
        config.setStatus(AppConstants.STATUS_PENDING);
      }
    } catch (Exception e) {
      e.printStackTrace();
      config.setStatus(AppConstants.STATUS_CONFIG_ERROR);
      config.setStatusString(
          String.format(
              "Parse Config Error, Exception: [%s:%s] found for: %s",
              e.getClass().getSimpleName(), e.getMessage(), appElm.asXML()));
    }
    return true;
  }