예제 #1
0
 public static void dom4j() throws IOException {
   // DOM4J allows construction of "invalid" (?) XML document
   org.dom4j.DocumentFactory fact = new org.dom4j.DocumentFactory();
   org.dom4j.Element root = fact.createElement("todo:todo");
   org.dom4j.Document doc = fact.createDocument(root);
   System.out.println("DOM4J: ");
   System.out.println(doc.asXML());
 }
예제 #2
0
 @Override
 public Element getXml() {
   DocumentFactory f = DocumentFactory.getInstance();
   Element toRet = f.createElement("gene");
   toRet.addAttribute("name", this.getName());
   toRet.addAttribute("expressiveness", this.getExpressiveness().toString());
   return toRet;
 }
  @Override
  public String put(
      String itemId,
      InputStream dataStream,
      long dataSize,
      HashMap<String, String> params,
      HashMap<String, String> metas,
      XMLConfig extra) {

    if (coll == null) return null;
    if (maxDocSize > 0 && dataSize > 0 && dataSize > maxDocSize) return null;

    BasicDBObject docsearch = new BasicDBObject();
    docsearch.put("item_id", itemId);

    BasicDBObject doc = new BasicDBObject();
    doc.put("item_id", itemId);
    doc.put("item_extra", extra.asXml());

    Document xml_params = DocumentFactory.getInstance().createDocument("utf-8");
    xml_params.setXMLEncoding("utf-8");
    Element xml_params_items = xml_params.addElement("params");

    for (Map.Entry<String, String> item : params.entrySet()) {
      String key = item.getKey();
      if (item.getValue() != null) xml_params_items.addElement(key).addText(item.getValue());
    }
    doc.put("item_params", xml_params.asXML());

    Document xml_metas = DocumentFactory.getInstance().createDocument("utf-8");
    xml_metas.setXMLEncoding("utf-8");
    Element xml_metas_items = xml_metas.addElement("metas");

    for (Map.Entry<String, String> item : metas.entrySet()) {
      String key = item.getKey();
      if (item.getKey().startsWith("meta_")) {
        key = key.replace(':', '_').replace('-', '_').replace('.', '_').replace('/', '_');
      }
      if (item.getValue() != null) xml_metas_items.addElement(key).addText(item.getValue());
    }
    doc.put("item_metas", xml_metas.asXML());

    if (dataStream != null) {
      String contentBase64 = "";
      try {
        // dataStream.reset();
        contentBase64 = Base64.inputStreamToStringBase64(dataStream);
        doc.put("content_base64", contentBase64);

      } catch (IOException e) {
        System.out.println(itemId);
        e.printStackTrace();
      }
    }
    remove(itemId);
    return coll.add(doc);
  }
예제 #4
0
  public Attribute createAttribute(Element element, String name, String value) {

    ElementImpl elementImpl = (ElementImpl) element;

    DocumentFactory documentFactory = DocumentFactory.getInstance();

    return new AttributeImpl(
        documentFactory.createAttribute(elementImpl.getWrappedElement(), name, value));
  }
예제 #5
0
  public static void dom4jWithURI() throws IOException {
    org.dom4j.DocumentFactory fact = new org.dom4j.DocumentFactory();
    org.dom4j.Element root = fact.createElement("todo:todo" /*, "http://www.example.com" */);

    // Namespace decl should be declared explicitly
    root.addNamespace("todo", "http://www.example.com");
    org.dom4j.Document doc = fact.createDocument(root);
    System.out.println("DOM4J: ");
    System.out.println(doc.asXML());
  }
예제 #6
0
 /**
  * @param config The configuration to write as XML
  * @param out The stream to write the configuration to
  * @throws java.io.IOException If an error occurs writing the XML document
  */
 public static void writeAsXml(MutableConfig config, java.io.OutputStream out)
     throws java.io.IOException {
   org.dom4j.DocumentFactory df = org.dom4j.DocumentFactory.getInstance();
   Element root = config.toXML(df);
   org.dom4j.Document doc = df.createDocument(root);
   org.dom4j.io.OutputFormat format = org.dom4j.io.OutputFormat.createPrettyPrint();
   format.setIndent("\t");
   org.dom4j.io.XMLWriter writer;
   writer = new org.dom4j.io.XMLWriter(out, format);
   writer.write(doc);
   writer.flush();
 }
예제 #7
0
 protected org.dom4j.Document documentRoot() throws Exception {
   CruiseConfig cruiseConfig = goConfigDao.loadForEditing();
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   new MagicalGoConfigXmlWriter(configCache, registry).write(cruiseConfig, out, true);
   org.dom4j.Document document = reader.read(new StringReader(out.toString()));
   Map<String, String> map = new HashMap<>();
   map.put("go", MagicalGoConfigXmlWriter.XML_NS);
   // TODO: verify this doesn't cache the factory
   DocumentFactory factory = DocumentFactory.getInstance();
   factory.setXPathNamespaceURIs(map);
   return document;
 }
 private void addXmlAnnotations(ModelAndView mav, String style) {
   List<ConceptAnnotation> annotations =
       (List<ConceptAnnotation>) mav.getModel().get("annotations");
   mav.addObject("mimetype", "text/xml");
   if (annotations != null) {
     Document doc = DocumentFactory.getInstance().createDocument();
     Element mappings = doc.addElement("mappings");
     for (ConceptAnnotation annotation : annotations) {
       Element mapping = mappings.addElement("mapping");
       mapping.addAttribute("id", String.valueOf(annotation.getOid()));
       mapping.addAttribute("start", String.valueOf(annotation.getBegin()));
       mapping.addAttribute("end", String.valueOf(annotation.getEnd()));
       mapping.addAttribute("pname", annotation.getPname());
       mapping.addAttribute("group", annotation.getStygroup());
       mapping.addAttribute("codes", StringUtils.replace(annotation.getStycodes(), "\"", ""));
       mapping.setText(annotation.getCoveredText());
     }
     OutputFormat outputFormat =
         "compact".equals(style)
             ? OutputFormat.createCompactFormat()
             : OutputFormat.createPrettyPrint();
     StringWriter swriter = new StringWriter();
     XMLWriter writer = new XMLWriter(swriter, outputFormat);
     try {
       writer.write(doc);
       writer.flush();
       mav.addObject("stringAnnotations", swriter.toString());
     } catch (IOException e) {
       logger.warn("IOException writing XML to buffer", e);
     }
   }
 }
  public void testDom4jSave() {
    Session pojos = openSession();
    Transaction txn = pojos.beginTransaction();

    prepareTestData(pojos);

    org.hibernate.Session dom4j = pojos.getSession(EntityMode.DOM4J);

    Element stock = DocumentFactory.getInstance().createElement("stock");
    stock.addElement("tradeSymbol").setText("IBM");

    Element val = stock.addElement("currentValuation").addElement("valuation");
    val.appendContent(stock);
    val.addElement("valuationDate").setText(new java.util.Date().toString());
    val.addElement("value").setText("121.00");

    dom4j.save(Stock.class.getName(), stock);
    dom4j.flush();

    txn.rollback();

    pojos.close();

    assertTrue(!pojos.isOpen());
    assertTrue(!dom4j.isOpen());

    prettyPrint(stock);
  }
예제 #10
0
  /**
   * DOCUMENT ME!
   *
   * @return the <code>DocumentFactory</code> used to create document objects
   */
  public DocumentFactory getDocumentFactory() {
    if (factory == null) {
      factory = DocumentFactory.getInstance();
    }

    return factory;
  }
예제 #11
0
  public Element getElement() {
    Element element = DocumentFactory.getInstance().createElement(QNAME);

    if (classificationScheme != null) {
      element.addAttribute(CLASSIFICATION_SCHEME_ATTRIBUTE, classificationScheme);
    }

    element.addAttribute(CLASSIFIED_OBJECT_ATTRIBUTE, classifiedObject);

    if (nodeRepresentation != null) {
      element.addAttribute(NODE_REPRESENTATION_ATTRIBUTE, nodeRepresentation);
    }

    if (classificationNode != null) {
      element.addAttribute(CLASSIFICATION_NODE_ATTRIBUTE, classificationNode);
    }

    if (name != null) {
      element.add(name.getElement());
    }
    if (slot != null) {
      element.add(slot.getElement());
    }
    return element;
  }
  protected void setProxy(DocumentFactory proxy) {
    if (proxy == null) {
      // use default factory
      proxy = DocumentFactory.getInstance();
    }

    this.proxy = proxy;
  }
 private Element createConfig(String roleId, String displayKey) {
   final Element root = DocumentFactory.getInstance().createElement("root");
   root.addAttribute("key", "randomKey7474");
   if (roleId != null) {
     root.addElement(ROLE_ID).setText(roleId);
   }
   if (displayKey != null) {
     root.addElement(ROLE_NAME).setText(displayKey);
   }
   return root;
 }
예제 #14
0
 /**
  * Returns an Element with the privacy list XML representation.
  *
  * @return an Element with the privacy list XML representation.
  */
 public Element asElement() {
   // Element listElement = DocumentFactory.getInstance().createDocument().addElement("list");
   Element listElement =
       DocumentFactory.getInstance().createDocument().addElement("list", "jabber:iq:privacy");
   listElement.addAttribute("name", getName());
   // Add the list items to the result
   for (PrivacyItem item : items) {
     listElement.add(item.asElement());
   }
   return listElement;
 }
예제 #15
0
  public Element xmlDump() {
    Element result = DocumentFactory.getInstance().createElement("error");
    result.addElement("short_desc").addText(getShortDesc());
    result.addElement("full_desc").addText(getFullDesc());
    result.addElement("importance").addText(Integer.toString(getImportance()));
    result.addElement("checker_name").addText(getCheckerName());
    Element eTraces = result.addElement("traces").addText(getCheckerName());

    for (final CheckerErrorTrace trace : getTraces()) eTraces.add(trace.xmlDump());
    return result;
  }
예제 #16
0
 private void addOpenHomeElement(
     String method, String action, Map<String, String> headerMap, String bodyText) {
   Element ht = super.setChildElement("http-tunnel", "http://icontrol.com/http-tunnel/v1");
   Element reqE = ht.addElement("request");
   reqE.addAttribute("method", method.toUpperCase());
   reqE.addAttribute("action", action);
   // headers
   if (headerMap != null) {
     for (Iterator<String> i = headerMap.keySet().iterator(); i.hasNext(); ) {
       String name = i.next();
       String text = headerMap.get(name);
       Element header = reqE.addElement("header");
       header.addAttribute("name", name);
       header.add(docFactory.createText(text));
     }
   }
   // body
   Element body = reqE.addElement("body");
   body.addAttribute("name", "body");
   if (bodyText != null) body.add(docFactory.createText(bodyText));
 }
예제 #17
0
  public static String generateXML(WTPart part, String directory)
      throws WTException, PropertyVetoException, IOException {
    File file = new File(directory + "/");
    if (!file.exists()) file.mkdirs();

    DocumentFactory factory = DocumentFactory.getInstance();
    Document document = factory.createDocument();

    Element root = generateRoot(part.getContainerName());
    root.add(generatePart(part, directory));
    document.setRootElement(root);

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("GBK");
    XMLWriter xmlWriter =
        new XMLWriter(
            new OutputStreamWriter(
                new FileOutputStream(directory + part.getNumber() + ".xml"), "GBK"),
            format);
    xmlWriter.write(document);
    xmlWriter.close();

    return null;
  }
 /**
  * Iterate through all AnnotatedMethods belonging to this class and store each one in a properly
  * organized XML file mirroring the REST api in the directory passed to the application.
  *
  * @param rootURL the relative root URL for set of Controllers to which this class belongs ex:
  *     /home/users NOT http://foo.com/bar/
  * @param location the location in which to save the XML files belonging to the methods of this
  *     class
  * @throws IOException
  */
 public void saveToXML(String rootURL, String location) throws IOException {
   String path = this.getPath();
   File dir = new File(location);
   // Make it a local directory
   String pathWithRoot = AnnotatedMethod.pathMash(rootURL, path);
   path = AnnotatedMethod.pathMash(location, pathWithRoot);
   for (AnnotatedMethod am : listOfMethods) {
     String methodPath = am.getPath();
     String requestMethod = am.getRequestMethod();
     // add the root to the method before making XML
     Element methodXML = am.toXML(rootURL);
     Document methodDoc = DocumentFactory.getInstance().createDocument();
     methodDoc.setRootElement(methodXML);
     // save
     String folderPath = AnnotatedMethod.pathMash(path, methodPath);
     String totalPath = AnnotatedMethod.pathMash(folderPath, requestMethod + ".xml");
     // Make directory structure
     writeFile(totalPath, methodDoc);
   }
 }
예제 #19
0
public class ServerRequestIQ extends IQ {

  protected static DocumentFactory docFactory = DocumentFactory.getInstance();

  public ServerRequestIQ(
      JID fromAddress,
      JID toAddress,
      String method,
      String action,
      Map<String, String> headerMap,
      String bodyText) {
    super(IQ.Type.set);

    if (fromAddress != null) super.setFrom(fromAddress);
    if (toAddress != null) super.setTo(toAddress);

    addOpenHomeElement(method, action, headerMap, bodyText);
  }

  private void addOpenHomeElement(
      String method, String action, Map<String, String> headerMap, String bodyText) {
    Element ht = super.setChildElement("http-tunnel", "http://icontrol.com/http-tunnel/v1");
    Element reqE = ht.addElement("request");
    reqE.addAttribute("method", method.toUpperCase());
    reqE.addAttribute("action", action);
    // headers
    if (headerMap != null) {
      for (Iterator<String> i = headerMap.keySet().iterator(); i.hasNext(); ) {
        String name = i.next();
        String text = headerMap.get(name);
        Element header = reqE.addElement("header");
        header.addAttribute("name", name);
        header.add(docFactory.createText(text));
      }
    }
    // body
    Element body = reqE.addElement("body");
    body.addAttribute("name", "body");
    if (bodyText != null) body.add(docFactory.createText(bodyText));
  }
}
예제 #20
0
 /**
  * Writes this configuration to an XML element
  *
  * @param df The document factory with which to create the element
  * @return The XML element representing this configuration
  */
 public Element toXML(org.dom4j.DocumentFactory df) {
   Element ret = df.createElement(theName);
   if (theValue != null) ret.setText(theValue);
   java.util.HashMap<String, int[]> attrs = new java.util.HashMap<String, int[]>();
   for (MutableConfig sub : theSubConfigs) {
     int[] count = attrs.get(sub.theName);
     if (count == null) {
       count = new int[1];
       attrs.put(sub.theName, count);
     }
     count[0]++;
   }
   for (MutableConfig sub : theSubConfigs) {
     if (attrs.get(sub.theName)[0] == 1
         && sub.theSubConfigs.length == 0
         && sub.theValue != null
         && sub.theValue.indexOf('\n') < 0) ret.addAttribute(sub.theName, sub.theValue);
     else ret.add(sub.toXML(df));
   }
   return ret;
 }
 public Namespace createNamespace(String prefix, String uri) {
   return proxy.createNamespace(prefix, uri);
 }
예제 #22
0
  @Override
  // Implementation methods
  // -------------------------------------------------------------------------
  protected Document parseDocument() throws DocumentException, IOException, XmlPullParserException {
    DocumentFactory df = getDocumentFactory();
    Document document = df.createDocument();
    Element parent = null;
    XmlPullParser pp = getXPPParser();
    pp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);

    while (true) {
      int type = pp.nextToken();

      switch (type) {
        case XmlPullParser.PROCESSING_INSTRUCTION:
          {
            String text = pp.getText();
            int loc = text.indexOf(' ');

            if (loc >= 0) {
              String target = text.substring(0, loc);
              String txt = text.substring(loc + 1);
              document.addProcessingInstruction(target, txt);
            } else {
              document.addProcessingInstruction(text, "");
            }

            break;
          }

        case XmlPullParser.COMMENT:
          {
            if (parent != null) {
              parent.addComment(pp.getText());
            } else {
              document.addComment(pp.getText());
            }

            break;
          }

        case XmlPullParser.CDSECT:
          {
            if (parent != null) {
              parent.addCDATA(pp.getText());
            } else {
              String msg = "Cannot have text content outside of the " + "root document";
              throw new DocumentException(msg);
            }

            break;
          }

        case XmlPullParser.END_DOCUMENT:
          return document;

        case XmlPullParser.START_TAG:
          {
            QName qname =
                (pp.getPrefix() == null)
                    ? df.createQName(pp.getName(), pp.getNamespace())
                    : df.createQName(pp.getName(), pp.getPrefix(), pp.getNamespace());
            Element newElement = df.createElement(qname);
            int nsStart = pp.getNamespaceCount(pp.getDepth() - 1);
            int nsEnd = pp.getNamespaceCount(pp.getDepth());

            for (int i = nsStart; i < nsEnd; i++) {
              if (pp.getNamespacePrefix(i) != null) {
                newElement.addNamespace(pp.getNamespacePrefix(i), pp.getNamespaceUri(i));
              }
            }

            for (int i = 0; i < pp.getAttributeCount(); i++) {
              QName qa =
                  (pp.getAttributePrefix(i) == null)
                      ? df.createQName(pp.getAttributeName(i))
                      : df.createQName(
                          pp.getAttributeName(i),
                          pp.getAttributePrefix(i),
                          pp.getAttributeNamespace(i));
              newElement.addAttribute(qa, pp.getAttributeValue(i));
            }

            if (parent != null) {
              parent.add(newElement);
            } else {
              document.add(newElement);
            }

            parent = newElement;

            break;
          }

        case XmlPullParser.END_TAG:
          {
            if (parent != null) {
              parent = parent.getParent();
            }

            break;
          }

        case XmlPullParser.ENTITY_REF:
        case XmlPullParser.TEXT:
          {
            String text = pp.getText();

            if (parent != null) {
              parent.addText(text);
            } else {
              String msg = "Cannot have text content outside of the " + "root document";
              throw new DocumentException(msg);
            }

            break;
          }

        default:
          break;
      }
    }
  }
 public Attribute createAttribute(Element owner, String name, String value) {
   return proxy.createAttribute(owner, name, value);
 }
 public CDATA createCDATA(String text) {
   return proxy.createCDATA(text);
 }
 public Comment createComment(String text) {
   return proxy.createComment(text);
 }
  private LotteryDraw nowPhaseResult() {

    String url = RESULT_LOCALITY_URL;
    LotteryDraw lotteryDraw = new LotteryDraw();
    String data = null;
    String pageInfo = "结果页面" + url;
    String encoding = "utf-8";
    String logHeader =
        "=="
            + lotteryScope
            + "=="
            + siteName
            + "=="
            + pageInfo
            + "==抓取=="
            + getLotteryType().getName()
            + "==";
    try {
      data = CoreFetcherUtils.URLGet(url, null, encoding);
    } catch (Exception e) {
      logger.error("获取xml数据失败" + e.getMessage());
      return null;
    }

    if (data == null || data.indexOf("404 Not Found") > 0 || data.isEmpty()) {
      logger.error(logHeader + "data is null or 404 Not Found");
      return null;
    }

    List<LotteryDrawPrizeItem> lotteryDrawPrizeItemList = new ArrayList<LotteryDrawPrizeItem>();

    SAXReader saxReader = new SAXReader();
    Document document = DocumentFactory.getInstance().createDocument();
    try {
      ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes(encoding));
      document = saxReader.read(bais);
      Iterator<?> it = document.getRootElement().elementIterator();
      while (it.hasNext()) {
        Element element = (Element) it.next();
        if (!element.getName().equals("po7oprize")) {
          continue;
        }
        Iterator<?> childIt = element.elementIterator();
        Element childElement = null;
        String name = "";
        String count = "";
        String bonus = "";

        while (childIt.hasNext()) {
          childElement = (Element) childIt.next();
          if (childElement.getName().equals("code")) {
            lotteryDraw.setResult(childElement.getTextTrim());
          }
          if (childElement.getName().equals("term")) {
            lotteryDraw.setPhase(childElement.getTextTrim());
            lotteryDraw.setLotteryType(getLotteryType());
          }
          if (childElement.getName().equals("drawOpenDate")) {
            lotteryDraw.setTimeDraw(childElement.getTextTrim() + " 00:00:00");
          }
          if (childElement.getName().equals("drawSaleCount")) {
            lotteryDraw.setVolumeOfSales(childElement.getTextTrim().replace(",", ""));
          }

          if (childElement.getName().equals("drawPrizePoolCount")) {
            lotteryDraw.setJackpot(childElement.getTextTrim().replace(",", ""));
          }

          if (childElement.getName().equals("name")) {
            name = childElement.getTextTrim();
          }
          if (childElement.getName().equals("count2")) {
            count = childElement.getTextTrim().replace(",", "");
          }
          if (childElement.getName().equals("bonus")) {
            bonus = childElement.getTextTrim().replace(",", "");
          }
          if (name != null
              && !"".equals(name)
              && bonus != null
              && !"".equals(bonus)
              && count != null
              && !"".equals(count)) {
            LotteryDrawPrizeItem lotteryDrawPrizeItem = new LotteryDrawPrizeItem();
            lotteryDrawPrizeItem.setName(name);
            lotteryDrawPrizeItem.setWinningCount(count);
            lotteryDrawPrizeItem.setPrizeAmount(bonus);
            lotteryDrawPrizeItemList.add(lotteryDrawPrizeItem);
            name = "";
            bonus = "";
            count = "";
          }
        }
      }
      lotteryDraw.setResultDetail(lotteryDrawPrizeItemList);
    } catch (Exception e) {
      logger.error("数据解析错误==" + e.getMessage(), e);
      return null;
    }
    return lotteryDraw;
  }
예제 #27
0
파일: Packet.java 프로젝트: citlab/rwx4j
/**
 * An XMPP packet (also referred to as a stanza). Each packet is backed by a DOM4J Element. A set of
 * convenience methods allows easy manipulation of the Element, or the Element can be accessed
 * directly and manipulated.
 *
 * <p>There are three core packet types:
 *
 * <ul>
 *   <li>{@link Message} -- used to send data between users.
 *   <li>{@link Presence} -- contains user presence information or is used to manage presence
 *       subscriptions.
 *   <li>{@link IQ} -- exchange information and perform queries using a request/response protocol.
 * </ul>
 *
 * @author Matt Tucker
 */
public abstract class Packet {

  protected static final DocumentFactory docFactory = DocumentFactory.getInstance();

  protected Element element;

  // Cache to and from JIDs
  protected JID toJID;
  protected JID fromJID;

  /**
   * Constructs a new Packet. The TO address contained in the XML Element will only be validated. In
   * other words, stringprep operations will only be performed on the TO JID to verify that it is
   * well-formed. The FROM address is assigned by the server so there is no need to verify it.
   *
   * @param element the XML Element that contains the packet contents.
   */
  public Packet(Element element) {
    this(element, false);
  }

  /**
   * Constructs a new Packet. The JID address contained in the XML Element may not be validated.
   * When validation can be skipped then stringprep operations will not be performed on the JIDs to
   * verify that addresses are well-formed. However, when validation cannot be skipped then
   * <tt>only</tt> the TO address will be verified. The FROM address is assigned by the server so
   * there is no need to verify it.
   *
   * @param element the XML Element that contains the packet contents.
   * @param skipValidation true if stringprep should not be applied to the TO address.
   */
  public Packet(Element element, boolean skipValidation) {
    this.element = element;
    // Apply stringprep profiles to the "to" and "from" values.
    String to = element.attributeValue("to");
    if (to != null) {
      if (to.length() == 0) {
        // Remove empty TO values
        element.addAttribute("to", null);
      } else {
        String[] parts = JID.getParts(to);
        toJID = new JID(parts[0], parts[1], parts[2], skipValidation);
        element.addAttribute("to", toJID.toString());
      }
    }
    String from = element.attributeValue("from");
    if (from != null) {
      if (from.length() == 0) {
        // Remove empty FROM values
        element.addAttribute("from", null);
      } else {
        String[] parts = JID.getParts(from);
        fromJID = new JID(parts[0], parts[1], parts[2], true);
        element.addAttribute("from", fromJID.toString());
      }
    }
  }

  /**
   * Constructs a new Packet with no element data. This method is used by extensions of this class
   * that require a more optimized path for creating new packets.
   */
  protected Packet() {}

  /**
   * Returns the packet ID, or <tt>null</tt> if the packet does not have an ID. Packet ID's are
   * optional, except for IQ packets.
   *
   * @return the packet ID.
   */
  public String getID() {
    return element.attributeValue("id");
  }

  /**
   * Sets the packet ID. Packet ID's are optional, except for IQ packets.
   *
   * @param ID the packet ID.
   */
  public void setID(String ID) {
    element.addAttribute("id", ID);
  }

  /**
   * Returns the XMPP address (JID) that the packet is addressed to, or <tt>null</tt> if the "to"
   * attribute is not set. The XMPP protocol often makes the "to" attribute optional, so it does not
   * always need to be set.
   *
   * @return the XMPP address (JID) that the packet is addressed to, or <tt>null</tt> if not set.
   */
  public JID getTo() {
    String to = element.attributeValue("to");
    if (to == null || to.length() == 0) {
      return null;
    } else {
      if (toJID != null && to.equals(toJID.toString())) {
        return toJID;
      } else {
        // Return a new JID that bypasses stringprep profile checking.
        // This improves speed and is safe as long as the user doesn't
        // directly manipulate the attributes of the underlying Element
        // that represent JID's.
        String[] parts = JID.getParts(to);
        toJID = new JID(parts[0], parts[1], parts[2], true);
        return toJID;
      }
    }
  }

  /**
   * Sets the XMPP address (JID) that the packet is addressed to. The XMPP protocol often makes the
   * "to" attribute optional, so it does not always need to be set.
   *
   * @param to the XMPP address (JID) that the packet is addressed to.
   */
  public void setTo(String to) {
    // Apply stringprep profiles to value.
    if (to != null) {
      toJID = new JID(to);
      to = toJID.toString();
    } else {
      toJID = null;
    }
    element.addAttribute("to", to);
  }

  /**
   * Sets the XMPP address (JID) that the packet is address to. The XMPP protocol often makes the
   * "to" attribute optional, so it does not always need to be set.
   *
   * @param to the XMPP address (JID) that the packet is addressed to.
   */
  public void setTo(JID to) {
    toJID = to;
    if (to == null) {
      element.addAttribute("to", null);
    } else {
      element.addAttribute("to", to.toString());
    }
  }

  /**
   * Returns the XMPP address (JID) that the packet is from, or <tt>null</tt> if the "from"
   * attribute is not set. The XMPP protocol often makes the "from" attribute optional, so it does
   * not always need to be set.
   *
   * @return the XMPP address that the packet is from, or <tt>null</tt> if not set.
   */
  public JID getFrom() {
    String from = element.attributeValue("from");
    if (from == null || from.length() == 0) {
      return null;
    } else {
      if (fromJID != null && from.equals(fromJID.toString())) {
        return fromJID;
      } else {
        // Return a new JID that bypasses stringprep profile checking.
        // This improves speed and is safe as long as the user doesn't
        // directly manipulate the attributes of the underlying Element
        // that represent JID's.
        String[] parts = JID.getParts(from);
        fromJID = new JID(parts[0], parts[1], parts[2], true);
        return fromJID;
      }
    }
  }

  /**
   * Sets the XMPP address (JID) that the packet comes from. The XMPP protocol often makes the
   * "from" attribute optional, so it does not always need to be set.
   *
   * @param from the XMPP address (JID) that the packet comes from.
   */
  public void setFrom(String from) {
    // Apply stringprep profiles to value.
    if (from != null) {
      fromJID = new JID(from);
      from = fromJID.toString();
    } else {
      fromJID = null;
    }
    element.addAttribute("from", from);
  }

  /**
   * Sets the XMPP address (JID) that the packet comes from. The XMPP protocol often makes the
   * "from" attribute optional, so it does not always need to be set.
   *
   * @param from the XMPP address (JID) that the packet comes from.
   */
  public void setFrom(JID from) {
    fromJID = from;
    if (from == null) {
      element.addAttribute("from", null);
    } else {
      element.addAttribute("from", from.toString());
    }
  }

  /**
   * Returns the packet error, or <tt>null</tt> if there is no packet error.
   *
   * @return the packet error.
   */
  public PacketError getError() {
    Element error = element.element("error");
    if (error != null) {
      return new PacketError(error);
    }
    return null;
  }

  /**
   * Sets the packet error. Calling this method will automatically set the packet "type" attribute
   * to "error".
   *
   * @param error the packet error.
   */
  public void setError(PacketError error) {
    if (element == null) {
      throw new NullPointerException("Error cannot be null");
    }
    // Force the packet type to "error".
    element.addAttribute("type", "error");
    // Remove an existing error packet.
    if (element.element("error") != null) {
      element.remove(element.element("error"));
    }
    // Add the error element.
    element.add(error.getElement());
  }

  /**
   * Sets the packet error using the specified condition. Calling this method will automatically set
   * the packet "type" attribute to "error". This is a convenience method equivalent to calling:
   *
   * <p><tt>setError(new PacketError(condition));</tt>
   *
   * @param condition the error condition.
   */
  public void setError(PacketError.Condition condition) {
    setError(new PacketError(condition));
  }

  /**
   * Creates a deep copy of this packet.
   *
   * @return a deep copy of this packet.
   */
  public abstract Packet createCopy();

  /**
   * Returns the DOM4J Element that backs the packet. The element is the definitive representation
   * of the packet and can be manipulated directly to change packet contents.
   *
   * @return the DOM4J Element that represents the packet.
   */
  public Element getElement() {
    return element;
  }

  /**
   * Returns the textual XML representation of this packet.
   *
   * @return the textual XML representation of this packet.
   */
  public String toXML() {
    return element.asXML();
  }

  public String toString() {
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
    try {
      writer.write(element);
    } catch (Exception e) {
      // Ignore.
    }
    return out.toString();
  }
}
예제 #28
0
 public Element cretateXMLElement() {
   return DocumentFactory.getInstance()
       .createElement(
           BpmnXMLConstants.BPMN2_PREFIX + ':' + BpmnXMLConstants.ELEMENT_ENDEVENT,
           BpmnXMLConstants.BPMN2_NAMESPACE);
 }
 public Text createText(String text) {
   return proxy.createText(text);
 }
 public Entity createEntity(String name, String text) {
   return proxy.createEntity(name, text);
 }