1
0
Fork 0
mirror of https://github.com/vanitasvitae/Smack.git synced 2024-11-26 05:52:06 +01:00

Use XmlStringBuilder in most toXML() bodies

Also change StringUtils.escapeForXML() and Packet.toXML() to return
CharSequence instead of String. XmlStringBuilder now has 'optX' methods.

Remove XmlUtils in favor of XmlStringBuilder
This commit is contained in:
Florian Schmaus 2014-03-21 09:51:52 +01:00
parent 1cf4681581
commit 978f692eb0
47 changed files with 511 additions and 412 deletions

View file

@ -338,7 +338,7 @@ public class BOSHConnection extends XMPPConnection {
void sendPacketInternal(Packet packet) { void sendPacketInternal(Packet packet) {
if (!done) { if (!done) {
try { try {
send(ComposableBody.builder().setPayloadXML(packet.toXML()) send(ComposableBody.builder().setPayloadXML(packet.toXML().toString())
.build()); .build());
} catch (BOSHException e) { } catch (BOSHException e) {
LOGGER.log(Level.SEVERE, "BOSHException in sendPacketInternal", e); LOGGER.log(Level.SEVERE, "BOSHException in sendPacketInternal", e);
@ -391,7 +391,7 @@ public class BOSHConnection extends XMPPConnection {
try { try {
client.disconnect(ComposableBody.builder() client.disconnect(ComposableBody.builder()
.setNamespaceDefinition("xmpp", XMPP_BOSH_NS) .setNamespaceDefinition("xmpp", XMPP_BOSH_NS)
.setPayloadXML(unavailablePresence.toXML()) .setPayloadXML(unavailablePresence.toXML().toString())
.build()); .build());
// Wait 150 ms for processes to clean-up, then shutdown. // Wait 150 ms for processes to clean-up, then shutdown.
Thread.sleep(150); Thread.sleep(150);

View file

@ -291,9 +291,9 @@ public class DirectoryRosterStore implements RosterStore {
XmlStringBuilder xml = new XmlStringBuilder(); XmlStringBuilder xml = new XmlStringBuilder();
xml.openElement("item"); xml.openElement("item");
xml.element("user", item.getUser()); xml.element("user", item.getUser());
xml.element("name", item.getName()); xml.optElement("name", item.getName());
xml.element("type", item.getItemType()); xml.optElement("type", item.getItemType());
xml.element("status", item.getItemStatus()); xml.optElement("status", item.getItemStatus());
for (String groupName : item.getGroupNames()) { for (String groupName : item.getGroupNames()) {
xml.openElement("group"); xml.openElement("group");
xml.element("groupName", groupName); xml.element("groupName", groupName);

View file

@ -241,8 +241,8 @@ public class LiteDebugger implements SmackDebugger {
// data as Smack sees it and not as it's coming in as raw XML. // data as Smack sees it and not as it's coming in as raw XML.
listener = new PacketListener() { listener = new PacketListener() {
public void processPacket(Packet packet) { public void processPacket(Packet packet) {
interpretedText1.append(packet.toXML()); interpretedText1.append(packet.toXML().toString());
interpretedText2.append(packet.toXML()); interpretedText2.append(packet.toXML().toString());
interpretedText1.append(NEWLINE); interpretedText1.append(NEWLINE);
interpretedText2.append(NEWLINE); interpretedText2.append(NEWLINE);
} }

View file

@ -17,6 +17,8 @@
package org.jivesoftware.smack.packet; package org.jivesoftware.smack.packet;
import org.jivesoftware.smack.util.XmlStringBuilder;
/** /**
* IQ packet used by Smack to bind a resource and to obtain the jid assigned by the server. * IQ packet used by Smack to bind a resource and to obtain the jid assigned by the server.
* There are two ways to bind a resource. One is simply sending an empty Bind packet where the * There are two ways to bind a resource. One is simply sending an empty Bind packet where the
@ -53,16 +55,16 @@ public class Bind extends IQ {
this.jid = jid; this.jid = jid;
} }
public String getChildElementXML() { @Override
StringBuilder buf = new StringBuilder(); public CharSequence getChildElementXML() {
buf.append("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">"); XmlStringBuilder xml = new XmlStringBuilder();
if (resource != null) { xml.halfOpenElement("bind");
buf.append("<resource>").append(resource).append("</resource>"); xml.xmlnsAttribute("urn:ietf:params:xml:ns:xmpp-bind");
} xml.rightAngelBracket();
if (jid != null) { xml.optElement("resource", resource);
buf.append("<jid>").append(jid).append("</jid>"); xml.optElement("jid", jid);
} xml.closeElement("bind");
buf.append("</bind>");
return buf.toString(); return xml;
} }
} }

View file

@ -19,6 +19,8 @@ package org.jivesoftware.smack.packet;
import java.util.*; import java.util.*;
import org.jivesoftware.smack.util.XmlStringBuilder;
/** /**
* Default implementation of the PacketExtension interface. Unless a PacketExtensionProvider * Default implementation of the PacketExtension interface. Unless a PacketExtensionProvider
* is registered with {@link org.jivesoftware.smack.provider.ProviderManager ProviderManager}, * is registered with {@link org.jivesoftware.smack.provider.ProviderManager ProviderManager},
@ -76,17 +78,16 @@ public class DefaultPacketExtension implements PacketExtension {
return namespace; return namespace;
} }
public String toXML() { @Override
StringBuilder buf = new StringBuilder(); public CharSequence toXML() {
buf.append("<").append(elementName).append(" xmlns=\"").append(namespace).append("\">"); XmlStringBuilder buf = new XmlStringBuilder();
buf.halfOpenElement(elementName).xmlnsAttribute(namespace).rightAngelBracket();
for (String name : getNames()) { for (String name : getNames()) {
String value = getValue(name); String value = getValue(name);
buf.append("<").append(name).append(">"); buf.element(name, value);
buf.append(value);
buf.append("</").append(name).append(">");
} }
buf.append("</").append(elementName).append(">"); buf.closeElement(elementName);
return buf.toString(); return buf;
} }
/** /**

View file

@ -17,7 +17,7 @@
package org.jivesoftware.smack.packet; package org.jivesoftware.smack.packet;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.XmlStringBuilder;
/** /**
* The base IQ (Info/Query) packet. IQ packets are used to get and set information * The base IQ (Info/Query) packet. IQ packets are used to get and set information
@ -71,36 +71,27 @@ public abstract class IQ extends Packet {
} }
} }
public String toXML() { @Override
StringBuilder buf = new StringBuilder(); public CharSequence toXML() {
buf.append("<iq "); XmlStringBuilder buf = new XmlStringBuilder();
if (getPacketID() != null) { buf.halfOpenElement("iq");
buf.append("id=\"" + getPacketID() + "\" "); addCommonAttributes(buf);
}
if (getTo() != null) {
buf.append("to=\"").append(StringUtils.escapeForXML(getTo())).append("\" ");
}
if (getFrom() != null) {
buf.append("from=\"").append(StringUtils.escapeForXML(getFrom())).append("\" ");
}
if (type == null) { if (type == null) {
buf.append("type=\"get\">"); buf.attribute("type", "get");
} }
else { else {
buf.append("type=\"").append(getType()).append("\">"); buf.attribute("type", type.toString());
} }
buf.rightAngelBracket();
// Add the query section if there is one. // Add the query section if there is one.
String queryXML = getChildElementXML(); buf.optAppend(getChildElementXML());
if (queryXML != null) {
buf.append(queryXML);
}
// Add the error sub-packet, if there is one. // Add the error sub-packet, if there is one.
XMPPError error = getError(); XMPPError error = getError();
if (error != null) { if (error != null) {
buf.append(error.toXML()); buf.append(error.toXML());
} }
buf.append("</iq>"); buf.closeElement("iq");
return buf.toString(); return buf;
} }
/** /**
@ -111,7 +102,7 @@ public abstract class IQ extends Packet {
* *
* @return the child element section of the IQ XML. * @return the child element section of the IQ XML.
*/ */
public abstract String getChildElementXML(); public abstract CharSequence getChildElementXML();
/** /**
* Convenience method to create a new empty {@link Type#RESULT IQ.Type.RESULT} * Convenience method to create a new empty {@link Type#RESULT IQ.Type.RESULT}
@ -170,7 +161,8 @@ public abstract class IQ extends Packet {
"IQ must be of type 'set' or 'get'. Original IQ: " + request.toXML()); "IQ must be of type 'set' or 'get'. Original IQ: " + request.toXML());
} }
final IQ result = new IQ() { final IQ result = new IQ() {
public String getChildElementXML() { @Override
public CharSequence getChildElementXML() {
return request.getChildElementXML(); return request.getChildElementXML();
} }
}; };

View file

@ -17,7 +17,7 @@
package org.jivesoftware.smack.packet; package org.jivesoftware.smack.packet;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.XmlStringBuilder;
import java.util.*; import java.util.*;
@ -404,59 +404,47 @@ public class Message extends Packet {
} }
public String toXML() { @Override
StringBuilder buf = new StringBuilder(); public XmlStringBuilder toXML() {
buf.append("<message"); XmlStringBuilder buf = new XmlStringBuilder();
if (getXmlns() != null) { buf.halfOpenElement("message");
buf.append(" xmlns=\"").append(getXmlns()).append("\""); buf.xmlnsAttribute(getXmlns());
} buf.xmllangAttribute(getLanguage());
if (language != null) { addCommonAttributes(buf);
buf.append(" xml:lang=\"").append(getLanguage()).append("\"");
}
if (getPacketID() != null) {
buf.append(" id=\"").append(getPacketID()).append("\"");
}
if (getTo() != null) {
buf.append(" to=\"").append(StringUtils.escapeForXML(getTo())).append("\"");
}
if (getFrom() != null) {
buf.append(" from=\"").append(StringUtils.escapeForXML(getFrom())).append("\"");
}
if (type != Type.normal) { if (type != Type.normal) {
buf.append(" type=\"").append(type).append("\""); buf.attribute("type", type);
} }
buf.append(">"); buf.rightAngelBracket();
// Add the subject in the default language // Add the subject in the default language
Subject defaultSubject = getMessageSubject(null); Subject defaultSubject = getMessageSubject(null);
if (defaultSubject != null) { if (defaultSubject != null) {
buf.append("<subject>").append(StringUtils.escapeForXML(defaultSubject.subject)).append("</subject>"); buf.element("subject", defaultSubject.subject);
} }
// Add the subject in other languages // Add the subject in other languages
for (Subject subject : getSubjects()) { for (Subject subject : getSubjects()) {
// Skip the default language // Skip the default language
if(subject.equals(defaultSubject)) if(subject.equals(defaultSubject))
continue; continue;
buf.append("<subject xml:lang=\"").append(subject.language).append("\">"); buf.halfOpenElement("subject").xmllangAttribute(subject.language).rightAngelBracket();
buf.append(StringUtils.escapeForXML(subject.subject)); buf.escape(subject.subject);
buf.append("</subject>"); buf.closeElement("subject");
} }
// Add the body in the default language // Add the body in the default language
Body defaultBody = getMessageBody(null); Body defaultBody = getMessageBody(null);
if (defaultBody != null) { if (defaultBody != null) {
buf.append("<body>").append(StringUtils.escapeForXML(defaultBody.message)).append("</body>"); buf.element("body", defaultBody.message);
} }
// Add the bodies in other languages // Add the bodies in other languages
for (Body body : getBodies()) { for (Body body : getBodies()) {
// Skip the default language // Skip the default language
if(body.equals(defaultBody)) if(body.equals(defaultBody))
continue; continue;
buf.append("<body xml:lang=\"").append(body.getLanguage()).append("\">"); buf.halfOpenElement("body").xmllangAttribute(body.getLanguage()).rightAngelBracket();
buf.append(StringUtils.escapeForXML(body.getMessage())); buf.escape(body.getMessage());
buf.append("</body>"); buf.closeElement("body");
}
if (thread != null) {
buf.append("<thread>").append(thread).append("</thread>");
} }
buf.optElement("thread", thread);
// Append the error subpacket if the message type is an error. // Append the error subpacket if the message type is an error.
if (type == Type.error) { if (type == Type.error) {
XMPPError error = getError(); XMPPError error = getError();
@ -466,8 +454,8 @@ public class Message extends Packet {
} }
// Add packet extensions, if any are defined. // Add packet extensions, if any are defined.
buf.append(getExtensionsXML()); buf.append(getExtensionsXML());
buf.append("</message>"); buf.closeElement("message");
return buf.toString(); return buf;
} }

View file

@ -18,6 +18,7 @@
package org.jivesoftware.smack.packet; package org.jivesoftware.smack.packet;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.XmlStringBuilder;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
@ -352,7 +353,7 @@ public abstract class Packet {
* *
* @return the XML format of the packet as a String. * @return the XML format of the packet as a String.
*/ */
public abstract String toXML(); public abstract CharSequence toXML();
/** /**
* Returns the extension sub-packets (including properties data) as an XML * Returns the extension sub-packets (including properties data) as an XML
@ -361,40 +362,47 @@ public abstract class Packet {
* @return the extension sub-packets as XML or the Empty String if there * @return the extension sub-packets as XML or the Empty String if there
* are no packet extensions. * are no packet extensions.
*/ */
protected synchronized String getExtensionsXML() { protected synchronized CharSequence getExtensionsXML() {
StringBuilder buf = new StringBuilder(); XmlStringBuilder xml = new XmlStringBuilder();
// Add in all standard extension sub-packets. // Add in all standard extension sub-packets.
for (PacketExtension extension : getExtensions()) { for (PacketExtension extension : getExtensions()) {
buf.append(extension.toXML()); xml.append(extension.toXML());
} }
// Add in packet properties. // Add in packet properties.
if (properties != null && !properties.isEmpty()) { if (properties != null && !properties.isEmpty()) {
buf.append("<properties xmlns=\"http://www.jivesoftware.com/xmlns/xmpp/properties\">"); xml.halfOpenElement("properties").xmlnsAttribute("http://www.jivesoftware.com/xmlns/xmpp/properties");
// Loop through all properties and write them out. // Loop through all properties and write them out.
for (String name : getPropertyNames()) { for (String name : getPropertyNames()) {
Object value = getProperty(name); Object value = getProperty(name);
buf.append("<property>"); xml.openElement("property");
buf.append("<name>").append(StringUtils.escapeForXML(name)).append("</name>"); xml.element("name", name);
buf.append("<value type=\""); xml.halfOpenElement("value");
String type;
String valueStr;
if (value instanceof Integer) { if (value instanceof Integer) {
buf.append("integer\">").append(value).append("</value>"); type = "integer";
valueStr = Integer.toString((Integer)value);
} }
else if (value instanceof Long) { else if (value instanceof Long) {
buf.append("long\">").append(value).append("</value>"); type = "long";
valueStr = Long.toString((Long) value);
} }
else if (value instanceof Float) { else if (value instanceof Float) {
buf.append("float\">").append(value).append("</value>"); type = "float";
valueStr = Float.toString((Float) value);
} }
else if (value instanceof Double) { else if (value instanceof Double) {
buf.append("double\">").append(value).append("</value>"); type = "double";
valueStr = Double.toString((Double) value);
} }
else if (value instanceof Boolean) { else if (value instanceof Boolean) {
buf.append("boolean\">").append(value).append("</value>"); type = "boolean";
valueStr = Boolean.toString((Boolean) value);
} }
else if (value instanceof String) { else if (value instanceof String) {
buf.append("string\">"); type = "string";
buf.append(StringUtils.escapeForXML((String)value)); valueStr = (String) value;
buf.append("</value>");
} }
// Otherwise, it's a generic Serializable object. Serialized objects are in // Otherwise, it's a generic Serializable object. Serialized objects are in
// a binary format, which won't work well inside of XML. Therefore, we base-64 // a binary format, which won't work well inside of XML. Therefore, we base-64
@ -406,12 +414,13 @@ public abstract class Packet {
byteStream = new ByteArrayOutputStream(); byteStream = new ByteArrayOutputStream();
out = new ObjectOutputStream(byteStream); out = new ObjectOutputStream(byteStream);
out.writeObject(value); out.writeObject(value);
buf.append("java-object\">"); type ="java-object";
String encodedVal = StringUtils.encodeBase64(byteStream.toByteArray()); valueStr = StringUtils.encodeBase64(byteStream.toByteArray());
buf.append(encodedVal).append("</value>");
} }
catch (Exception e) { catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error encoding java object", e); LOGGER.log(Level.SEVERE, "Error encoding java object", e);
type ="java-object";
valueStr = "Serializing error: " + e.getMessage();
} }
finally { finally {
if (out != null) { if (out != null) {
@ -432,11 +441,15 @@ public abstract class Packet {
} }
} }
} }
buf.append("</property>"); xml.attribute("type", type);
xml.rightAngelBracket();
xml.escape(valueStr);
xml.closeElement("value");
xml.closeElement("property");
} }
buf.append("</properties>"); xml.closeElement("properties");
} }
return buf.toString(); return xml;
} }
public String getXmlns() { public String getXmlns() {
@ -488,6 +501,17 @@ public abstract class Packet {
@Override @Override
public String toString() { public String toString() {
return toXML(); return toXML().toString();
}
/**
* Add to, from and id attributes
*
* @param xml
*/
protected void addCommonAttributes(XmlStringBuilder xml) {
xml.optAttribute("id", getPacketID());
xml.optAttribute("to", getTo());
xml.optAttribute("from", getFrom());
} }
} }

View file

@ -49,5 +49,5 @@ public interface PacketExtension {
* *
* @return the packet extension as XML. * @return the packet extension as XML.
*/ */
public String toXML(); public CharSequence toXML();
} }

View file

@ -17,7 +17,7 @@
package org.jivesoftware.smack.packet; package org.jivesoftware.smack.packet;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.XmlStringBuilder;
/** /**
* Represents XMPP presence packets. Every presence packet has a type, which is one of * Represents XMPP presence packets. Every presence packet has a type, which is one of
@ -220,49 +220,35 @@ public class Presence extends Packet {
this.language = language; this.language = language;
} }
public String toXML() { @Override
StringBuilder buf = new StringBuilder(); public XmlStringBuilder toXML() {
buf.append("<presence"); XmlStringBuilder buf = new XmlStringBuilder();
if(getXmlns() != null) { buf.halfOpenElement("presence");
buf.append(" xmlns=\"").append(getXmlns()).append("\""); buf.xmlnsAttribute(getXmlns());
} buf.xmllangAttribute(getLanguage());
if (language != null) { addCommonAttributes(buf);
buf.append(" xml:lang=\"").append(getLanguage()).append("\"");
}
if (getPacketID() != null) {
buf.append(" id=\"").append(getPacketID()).append("\"");
}
if (getTo() != null) {
buf.append(" to=\"").append(StringUtils.escapeForXML(getTo())).append("\"");
}
if (getFrom() != null) {
buf.append(" from=\"").append(StringUtils.escapeForXML(getFrom())).append("\"");
}
if (type != Type.available) { if (type != Type.available) {
buf.append(" type=\"").append(type).append("\""); buf.attribute("type", type);
}
buf.append(">");
if (status != null) {
buf.append("<status>").append(StringUtils.escapeForXML(status)).append("</status>");
} }
buf.rightAngelBracket();
buf.optElement("status", status);
if (priority != Integer.MIN_VALUE) { if (priority != Integer.MIN_VALUE) {
buf.append("<priority>").append(priority).append("</priority>"); buf.element("priority", Integer.toString(priority));
} }
if (mode != null && mode != Mode.available) { if (mode != null && mode != Mode.available) {
buf.append("<show>").append(mode).append("</show>"); buf.element("show", mode);
} }
buf.append(getExtensionsXML());
buf.append(this.getExtensionsXML());
// Add the error sub-packet, if there is one. // Add the error sub-packet, if there is one.
XMPPError error = getError(); XMPPError error = getError();
if (error != null) { if (error != null) {
buf.append(error.toXML()); buf.append(error.toXML());
} }
buf.closeElement("presence");
buf.append("</presence>"); return buf;
return buf.toString();
} }
public String toString() { public String toString() {

View file

@ -19,6 +19,8 @@ package org.jivesoftware.smack.packet;
import java.util.Map; import java.util.Map;
import org.jivesoftware.smack.util.XmlStringBuilder;
/** /**
* Represents registration packets. An empty GET query will cause the server to return information * Represents registration packets. An empty GET query will cause the server to return information
* about it's registration support. SET queries can be used to create accounts or update * about it's registration support. SET queries can be used to create accounts or update
@ -85,23 +87,22 @@ public class Registration extends IQ {
this.attributes = attributes; this.attributes = attributes;
} }
public String getChildElementXML() { @Override
StringBuilder buf = new StringBuilder(); public XmlStringBuilder getChildElementXML() {
buf.append("<query xmlns=\"jabber:iq:register\">"); XmlStringBuilder xml = new XmlStringBuilder();
if (instructions != null) { xml.halfOpenElement("query");
buf.append("<instructions>").append(instructions).append("</instructions>"); xml.xmlnsAttribute("jabber:iq:register");
} xml.rightAngelBracket();
xml.optElement("instructions", instructions);
if (attributes != null && attributes.size() > 0) { if (attributes != null && attributes.size() > 0) {
for (String name : attributes.keySet()) { for (String name : attributes.keySet()) {
String value = attributes.get(name); String value = attributes.get(name);
buf.append("<").append(name).append(">"); xml.element(name, value);
buf.append(value);
buf.append("</").append(name).append(">");
} }
} }
// Add packet extensions, if any are defined. // Add packet extensions, if any are defined.
buf.append(getExtensionsXML()); xml.append(getExtensionsXML());
buf.append("</query>"); xml.closeElement("query");
return buf.toString(); return xml;
} }
} }

View file

@ -18,6 +18,7 @@
package org.jivesoftware.smack.packet; package org.jivesoftware.smack.packet;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.XmlStringBuilder;
import java.util.*; import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.CopyOnWriteArraySet;
@ -65,22 +66,20 @@ public class RosterPacket extends IQ {
} }
} }
public String getChildElementXML() { public CharSequence getChildElementXML() {
StringBuilder buf = new StringBuilder(); XmlStringBuilder buf = new XmlStringBuilder();
buf.append("<query xmlns=\"jabber:iq:roster\""); buf.halfOpenElement("query");
if (rosterVersion != null) { buf.xmlnsAttribute("jabber:iq:roster");
buf.append(" ver=\""); buf.optAttribute("ver", rosterVersion);
buf.append(rosterVersion); buf.rightAngelBracket();
buf.append('"');
}
buf.append(">");
synchronized (rosterItems) { synchronized (rosterItems) {
for (Item entry : rosterItems) { for (Item entry : rosterItems) {
buf.append(entry.toXML()); buf.append(entry.toXML());
} }
} }
buf.append("</query>"); buf.closeElement("query");
return buf.toString(); return buf;
} }
public String getVersion() { public String getVersion() {

View file

@ -36,7 +36,8 @@ public class Session extends IQ {
setType(IQ.Type.SET); setType(IQ.Type.SET);
} }
public String getChildElementXML() { @Override
public CharSequence getChildElementXML() {
return "<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>"; return "<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>";
} }
} }

View file

@ -152,7 +152,7 @@ public class XMPPError {
* *
* @return the error as XML. * @return the error as XML.
*/ */
public String toXML() { public CharSequence toXML() {
StringBuilder buf = new StringBuilder(); StringBuilder buf = new StringBuilder();
buf.append("<error"); buf.append("<error");
if (type != null) { if (type != null) {

View file

@ -0,0 +1,89 @@
/**
*
* Copyright 2014 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack.util;
import java.util.ArrayList;
import java.util.List;
public class LazyStringBuilder implements Appendable, CharSequence {
private final List<CharSequence> list;
public LazyStringBuilder() {
list = new ArrayList<CharSequence>(20);
}
public LazyStringBuilder append(LazyStringBuilder lsb) {
list.addAll(lsb.list);
return this;
}
@Override
public LazyStringBuilder append(CharSequence csq) {
assert csq != null;
list.add(csq);
return this;
}
@Override
public LazyStringBuilder append(CharSequence csq, int start, int end) {
CharSequence subsequence = csq.subSequence(start, end);
list.add(subsequence);
return this;
}
@Override
public LazyStringBuilder append(char c) {
list.add(Character.toString(c));
return this;
}
@Override
public int length() {
int length = 0;
for (CharSequence csq : list) {
length += csq.length();
}
return length;
}
@Override
public char charAt(int index) {
for (CharSequence csq : list) {
if (index < csq.length()) {
return csq.charAt(index);
} else {
index -= csq.length();
}
}
throw new IndexOutOfBoundsException();
}
@Override
public CharSequence subSequence(int start, int end) {
return toString().subSequence(start, end);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(length());
for (CharSequence csq : list) {
sb.append(csq);
}
return sb.toString();
}
}

View file

@ -290,7 +290,7 @@ public class StringUtils {
* @param string the string to escape. * @param string the string to escape.
* @return the string with appropriate characters escaped. * @return the string with appropriate characters escaped.
*/ */
public static String escapeForXML(final String string) { public static CharSequence escapeForXML(final String string) {
if (string == null) { if (string == null) {
return null; return null;
} }
@ -339,7 +339,7 @@ public class StringUtils {
if (i > last) { if (i > last) {
out.append(input, last, i - last); out.append(input, last, i - last);
} }
return out.toString(); return out;
} }
/** /**

View file

@ -16,12 +16,20 @@
*/ */
package org.jivesoftware.smack.util; package org.jivesoftware.smack.util;
public class XmlStringBuilder implements Appendable, CharSequence { import org.jivesoftware.smack.packet.PacketExtension;
private final StringBuilder sb; public class XmlStringBuilder implements Appendable, CharSequence {
public static final String RIGHT_ANGEL_BRACKET = Character.toString('>');
private final LazyStringBuilder sb;
public XmlStringBuilder() { public XmlStringBuilder() {
sb = new StringBuilder(); sb = new LazyStringBuilder();
}
public XmlStringBuilder(PacketExtension pe) {
this();
prelude(pe);
} }
/** /**
@ -29,11 +37,10 @@ public class XmlStringBuilder implements Appendable, CharSequence {
* *
* @param name * @param name
* @param content * @param content
* @return * @return the XmlStringBuilder
*/ */
public XmlStringBuilder element(String name, String content) { public XmlStringBuilder element(String name, String content) {
if (content == null) assert content != null;
return this;
openElement(name); openElement(name);
escape(content); escape(content);
closeElement(name); closeElement(name);
@ -41,8 +48,21 @@ public class XmlStringBuilder implements Appendable, CharSequence {
} }
public XmlStringBuilder element(String name, Enum<?> content) { public XmlStringBuilder element(String name, Enum<?> content) {
if (content != null) { assert content != null;
element(name, content.name()); element(name, content.name());
return this;
}
public XmlStringBuilder optElement(String name, String content) {
if (content != null) {
element(name, content);
}
return this;
}
public XmlStringBuilder optElement(String name, Enum<?> content) {
if (content != null) {
element(name, content);
} }
return this; return this;
} }
@ -53,54 +73,111 @@ public class XmlStringBuilder implements Appendable, CharSequence {
} }
public XmlStringBuilder openElement(String name) { public XmlStringBuilder openElement(String name) {
halfOpenElement(name).append('>'); halfOpenElement(name).rightAngelBracket();
return this; return this;
} }
public XmlStringBuilder closeElement(String name) { public XmlStringBuilder closeElement(String name) {
sb.append("</").append(name).append('>'); sb.append("</").append(name);
rightAngelBracket();
return this; return this;
} }
public XmlStringBuilder emptyElementClose() { public XmlStringBuilder closeElement(PacketExtension pe) {
closeElement(pe.getElementName());
return this;
}
public XmlStringBuilder closeEmptyElement() {
sb.append("/>"); sb.append("/>");
return this; return this;
} }
public XmlStringBuilder rightAngelBracket() {
sb.append(RIGHT_ANGEL_BRACKET);
return this;
}
/** /**
* Does nothing if value is null. * Does nothing if value is null.
* *
* @param name * @param name
* @param value * @param value
* @return * @return the XmlStringBuilder
*/ */
public XmlStringBuilder attribute(String name, String value) { public XmlStringBuilder attribute(String name, String value) {
if (value == null) assert value != null;
return this;
sb.append(' ').append(name).append("='"); sb.append(' ').append(name).append("='");
escape(value); escape(value);
sb.append('\''); sb.append('\'');
return this; return this;
} }
public XmlStringBuilder attribute(String name, Enum<?> value) {
assert value != null;
attribute(name, value.name());
return this;
}
public XmlStringBuilder optAttribute(String name, String value) {
if (value != null) {
attribute(name, value);
}
return this;
}
public XmlStringBuilder optAttribute(String name, Enum<?> value) {
if (value != null) {
attribute(name, value.name());
}
return this;
}
public XmlStringBuilder xmlnsAttribute(String value) { public XmlStringBuilder xmlnsAttribute(String value) {
attribute("xmlns", value); optAttribute("xmlns", value);
return this;
}
public XmlStringBuilder xmllangAttribute(String value) {
optAttribute("xml:lang", value);
return this; return this;
} }
public XmlStringBuilder escape(String text) { public XmlStringBuilder escape(String text) {
assert text != null;
sb.append(StringUtils.escapeForXML(text)); sb.append(StringUtils.escapeForXML(text));
return this; return this;
} }
public XmlStringBuilder prelude(PacketExtension pe) {
halfOpenElement(pe.getElementName());
xmlnsAttribute(pe.getNamespace());
return this;
}
public XmlStringBuilder optAppend(CharSequence csq) {
if (csq != null) {
append(csq);
}
return this;
}
public XmlStringBuilder append(XmlStringBuilder xsb) {
assert xsb != null;
sb.append(xsb.sb);
return this;
}
@Override @Override
public XmlStringBuilder append(CharSequence csq) { public XmlStringBuilder append(CharSequence csq) {
assert csq != null;
sb.append(csq); sb.append(csq);
return this; return this;
} }
@Override @Override
public XmlStringBuilder append(CharSequence csq, int start, int end) { public XmlStringBuilder append(CharSequence csq, int start, int end) {
assert csq != null;
sb.append(csq, start, end); sb.append(csq, start, end);
return this; return this;
} }

View file

@ -1,34 +0,0 @@
/**
*
* Copyright the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack.util;
/**
* Simple utility for XML.
*
* @author Robin Collier
*/
public class XmlUtils {
static public void appendAttribute(StringBuilder builder, String att, String value) {
builder.append(" ");
builder.append(att);
builder.append("='");
builder.append(value);
builder.append("'");
}
}

View file

@ -54,7 +54,7 @@ public class MessageTest {
Message messageTypeInConstructor = new Message(null, Message.Type.chat); Message messageTypeInConstructor = new Message(null, Message.Type.chat);
messageTypeInConstructor.setPacketID(Packet.ID_NOT_AVAILABLE); messageTypeInConstructor.setPacketID(Packet.ID_NOT_AVAILABLE);
assertEquals(type, messageTypeInConstructor.getType()); assertEquals(type, messageTypeInConstructor.getType());
assertXMLEqual(control, messageTypeInConstructor.toXML()); assertXMLEqual(control, messageTypeInConstructor.toXML().toString());
controlBuilder = new StringBuilder(); controlBuilder = new StringBuilder();
controlBuilder.append("<message") controlBuilder.append("<message")
@ -67,7 +67,7 @@ public class MessageTest {
Message messageTypeSet = getNewMessage(); Message messageTypeSet = getNewMessage();
messageTypeSet.setType(type2); messageTypeSet.setType(type2);
assertEquals(type2, messageTypeSet.getType()); assertEquals(type2, messageTypeSet.getType());
assertXMLEqual(control, messageTypeSet.toXML()); assertXMLEqual(control, messageTypeSet.toXML().toString());
} }
@Test(expected=IllegalArgumentException.class) @Test(expected=IllegalArgumentException.class)
@ -98,7 +98,7 @@ public class MessageTest {
message.setSubject(messageSubject); message.setSubject(messageSubject);
assertEquals(messageSubject, message.getSubject()); assertEquals(messageSubject, message.getSubject());
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
} }
@Test @Test
@ -117,7 +117,7 @@ public class MessageTest {
message.setBody(messageBody); message.setBody(messageBody);
assertEquals(messageBody, message.getBody()); assertEquals(messageBody, message.getBody());
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
} }
@Test @Test
@ -150,7 +150,7 @@ public class MessageTest {
message.addBody(null, messageBody1); message.addBody(null, messageBody1);
message.addBody(lang2, messageBody2); message.addBody(lang2, messageBody2);
message.addBody(lang3, messageBody3); message.addBody(lang3, messageBody3);
Diff xmlDiff = new Diff(control, message.toXML()); Diff xmlDiff = new Diff(control, message.toXML().toString());
xmlDiff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier()); xmlDiff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
assertTrue(xmlDiff.similar()); assertTrue(xmlDiff.similar());
@ -196,7 +196,7 @@ public class MessageTest {
message.setThread(messageThread); message.setThread(messageThread);
assertEquals(messageThread, message.getThread()); assertEquals(messageThread, message.getThread());
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
} }
@Test @Test
@ -214,7 +214,7 @@ public class MessageTest {
Message message = getNewMessage(); Message message = getNewMessage();
message.setLanguage(lang); message.setLanguage(lang);
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
} }
@Test @Test

View file

@ -49,7 +49,7 @@ public class PresenceTest {
Presence presenceTypeInConstructor = new Presence(type); Presence presenceTypeInConstructor = new Presence(type);
presenceTypeInConstructor.setPacketID(Packet.ID_NOT_AVAILABLE); presenceTypeInConstructor.setPacketID(Packet.ID_NOT_AVAILABLE);
assertEquals(type, presenceTypeInConstructor.getType()); assertEquals(type, presenceTypeInConstructor.getType());
assertXMLEqual(control, presenceTypeInConstructor.toXML()); assertXMLEqual(control, presenceTypeInConstructor.toXML().toString());
controlBuilder = new StringBuilder(); controlBuilder = new StringBuilder();
controlBuilder.append("<presence") controlBuilder.append("<presence")
@ -62,7 +62,7 @@ public class PresenceTest {
Presence presenceTypeSet = getNewPresence(); Presence presenceTypeSet = getNewPresence();
presenceTypeSet.setType(type2); presenceTypeSet.setType(type2);
assertEquals(type2, presenceTypeSet.getType()); assertEquals(type2, presenceTypeSet.getType());
assertXMLEqual(control, presenceTypeSet.toXML()); assertXMLEqual(control, presenceTypeSet.toXML().toString());
} }
@Test(expected=NullPointerException.class) @Test(expected=NullPointerException.class)
@ -96,7 +96,7 @@ public class PresenceTest {
presence.setStatus(status); presence.setStatus(status);
assertEquals(status, presence.getStatus()); assertEquals(status, presence.getStatus());
assertXMLEqual(control, presence.toXML()); assertXMLEqual(control, presence.toXML().toString());
} }
@Test @Test
@ -115,7 +115,7 @@ public class PresenceTest {
presence.setPriority(priority); presence.setPriority(priority);
assertEquals(priority, presence.getPriority()); assertEquals(priority, presence.getPriority());
assertXMLEqual(control, presence.toXML()); assertXMLEqual(control, presence.toXML().toString());
} }
@Test(expected=IllegalArgumentException.class) @Test(expected=IllegalArgumentException.class)
@ -148,7 +148,7 @@ public class PresenceTest {
mode1); mode1);
presenceModeInConstructor.setPacketID(Packet.ID_NOT_AVAILABLE); presenceModeInConstructor.setPacketID(Packet.ID_NOT_AVAILABLE);
assertEquals(mode1, presenceModeInConstructor.getMode()); assertEquals(mode1, presenceModeInConstructor.getMode());
assertXMLEqual(control, presenceModeInConstructor.toXML()); assertXMLEqual(control, presenceModeInConstructor.toXML().toString());
controlBuilder = new StringBuilder(); controlBuilder = new StringBuilder();
controlBuilder.append("<presence>") controlBuilder.append("<presence>")
@ -161,7 +161,7 @@ public class PresenceTest {
Presence presenceModeSet = getNewPresence(); Presence presenceModeSet = getNewPresence();
presenceModeSet.setMode(mode2); presenceModeSet.setMode(mode2);
assertEquals(mode2, presenceModeSet.getMode()); assertEquals(mode2, presenceModeSet.getMode());
assertXMLEqual(control, presenceModeSet.toXML()); assertXMLEqual(control, presenceModeSet.toXML().toString());
} }
@Test @Test
@ -189,7 +189,7 @@ public class PresenceTest {
Presence presence = getNewPresence(); Presence presence = getNewPresence();
presence.setLanguage(lang); presence.setLanguage(lang);
assertXMLEqual(control, presence.toXML()); assertXMLEqual(control, presence.toXML().toString());
} }
private static Presence getNewPresence() { private static Presence getNewPresence() {

View file

@ -75,7 +75,7 @@ public class PacketParserUtilsTest {
assertTrue(message.getBodyLanguages().isEmpty()); assertTrue(message.getBodyLanguages().isEmpty());
assertEquals(defaultLanguage, message.getBody(defaultLanguage)); assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertNull(message.getBody(otherLanguage)); assertNull(message.getBody(otherLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has non-default language, body has no language // message has non-default language, body has no language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -94,7 +94,7 @@ public class PacketParserUtilsTest {
assertTrue(message.getBodyLanguages().isEmpty()); assertTrue(message.getBodyLanguages().isEmpty());
assertEquals(otherLanguage, message.getBody(otherLanguage)); assertEquals(otherLanguage, message.getBody(otherLanguage));
assertNull(message.getBody(defaultLanguage)); assertNull(message.getBody(defaultLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has no language, body has no language // message has no language, body has no language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -112,7 +112,7 @@ public class PacketParserUtilsTest {
assertTrue(message.getBodyLanguages().isEmpty()); assertTrue(message.getBodyLanguages().isEmpty());
assertEquals(defaultLanguage, message.getBody(defaultLanguage)); assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertNull(message.getBody(otherLanguage)); assertNull(message.getBody(otherLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has no language, body has default language // message has no language, body has default language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -133,7 +133,7 @@ public class PacketParserUtilsTest {
assertNull(message.getBody(otherLanguage)); assertNull(message.getBody(otherLanguage));
// body attribute xml:lang is unnecessary // body attribute xml:lang is unnecessary
assertXMLNotEqual(control, message.toXML()); assertXMLNotEqual(control, message.toXML().toString());
// message has no language, body has non-default language // message has no language, body has non-default language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -153,7 +153,7 @@ public class PacketParserUtilsTest {
assertTrue(message.getBodyLanguages().contains(otherLanguage)); assertTrue(message.getBodyLanguages().contains(otherLanguage));
assertEquals(otherLanguage, message.getBody(otherLanguage)); assertEquals(otherLanguage, message.getBody(otherLanguage));
assertNull(message.getBody(defaultLanguage)); assertNull(message.getBody(defaultLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has default language, body has non-default language // message has default language, body has non-default language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -174,7 +174,7 @@ public class PacketParserUtilsTest {
assertTrue(message.getBodyLanguages().contains(otherLanguage)); assertTrue(message.getBodyLanguages().contains(otherLanguage));
assertEquals(otherLanguage, message.getBody(otherLanguage)); assertEquals(otherLanguage, message.getBody(otherLanguage));
assertNull(message.getBody(defaultLanguage)); assertNull(message.getBody(defaultLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has non-default language, body has default language // message has non-default language, body has default language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -195,7 +195,7 @@ public class PacketParserUtilsTest {
assertTrue(message.getBodyLanguages().contains(defaultLanguage)); assertTrue(message.getBodyLanguages().contains(defaultLanguage));
assertEquals(defaultLanguage, message.getBody(defaultLanguage)); assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertNull(message.getBody(otherLanguage)); assertNull(message.getBody(otherLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
} }
@ -225,7 +225,7 @@ public class PacketParserUtilsTest {
assertTrue(message.getSubjectLanguages().isEmpty()); assertTrue(message.getSubjectLanguages().isEmpty());
assertEquals(defaultLanguage, message.getSubject(defaultLanguage)); assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertNull(message.getSubject(otherLanguage)); assertNull(message.getSubject(otherLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has non-default language, subject has no language // message has non-default language, subject has no language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -244,7 +244,7 @@ public class PacketParserUtilsTest {
assertTrue(message.getSubjectLanguages().isEmpty()); assertTrue(message.getSubjectLanguages().isEmpty());
assertEquals(otherLanguage, message.getSubject(otherLanguage)); assertEquals(otherLanguage, message.getSubject(otherLanguage));
assertNull(message.getSubject(defaultLanguage)); assertNull(message.getSubject(defaultLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has no language, subject has no language // message has no language, subject has no language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -262,7 +262,7 @@ public class PacketParserUtilsTest {
assertTrue(message.getSubjectLanguages().isEmpty()); assertTrue(message.getSubjectLanguages().isEmpty());
assertEquals(defaultLanguage, message.getSubject(defaultLanguage)); assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertNull(message.getSubject(otherLanguage)); assertNull(message.getSubject(otherLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has no language, subject has default language // message has no language, subject has default language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -283,7 +283,7 @@ public class PacketParserUtilsTest {
assertNull(message.getSubject(otherLanguage)); assertNull(message.getSubject(otherLanguage));
// subject attribute xml:lang is unnecessary // subject attribute xml:lang is unnecessary
assertXMLNotEqual(control, message.toXML()); assertXMLNotEqual(control, message.toXML().toString());
// message has no language, subject has non-default language // message has no language, subject has non-default language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -303,7 +303,7 @@ public class PacketParserUtilsTest {
assertTrue(message.getSubjectLanguages().contains(otherLanguage)); assertTrue(message.getSubjectLanguages().contains(otherLanguage));
assertEquals(otherLanguage, message.getSubject(otherLanguage)); assertEquals(otherLanguage, message.getSubject(otherLanguage));
assertNull(message.getSubject(defaultLanguage)); assertNull(message.getSubject(defaultLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has default language, subject has non-default language // message has default language, subject has non-default language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -324,7 +324,7 @@ public class PacketParserUtilsTest {
assertTrue(message.getSubjectLanguages().contains(otherLanguage)); assertTrue(message.getSubjectLanguages().contains(otherLanguage));
assertEquals(otherLanguage, message.getSubject(otherLanguage)); assertEquals(otherLanguage, message.getSubject(otherLanguage));
assertNull(message.getSubject(defaultLanguage)); assertNull(message.getSubject(defaultLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has non-default language, subject has default language // message has non-default language, subject has default language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -345,7 +345,7 @@ public class PacketParserUtilsTest {
assertTrue(message.getSubjectLanguages().contains(defaultLanguage)); assertTrue(message.getSubjectLanguages().contains(defaultLanguage));
assertEquals(defaultLanguage, message.getSubject(defaultLanguage)); assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertNull(message.getSubject(otherLanguage)); assertNull(message.getSubject(otherLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
} }
@ -381,7 +381,7 @@ public class PacketParserUtilsTest {
assertEquals(2, message.getBodies().size()); assertEquals(2, message.getBodies().size());
assertEquals(1, message.getBodyLanguages().size()); assertEquals(1, message.getBodyLanguages().size());
assertTrue(message.getBodyLanguages().contains(otherLanguage)); assertTrue(message.getBodyLanguages().contains(otherLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has default language, first body no language, second body default language // message has default language, first body no language, second body default language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -405,7 +405,7 @@ public class PacketParserUtilsTest {
assertEquals(defaultLanguage, message.getBody(defaultLanguage)); assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertEquals(1, message.getBodies().size()); assertEquals(1, message.getBodies().size());
assertEquals(0, message.getBodyLanguages().size()); assertEquals(0, message.getBodyLanguages().size());
assertXMLNotEqual(control, message.toXML()); assertXMLNotEqual(control, message.toXML().toString());
// message has non-default language, first body no language, second body default language // message has non-default language, first body no language, second body default language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -430,7 +430,7 @@ public class PacketParserUtilsTest {
assertEquals(2, message.getBodies().size()); assertEquals(2, message.getBodies().size());
assertEquals(1, message.getBodyLanguages().size()); assertEquals(1, message.getBodyLanguages().size());
assertTrue(message.getBodyLanguages().contains(defaultLanguage)); assertTrue(message.getBodyLanguages().contains(defaultLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has no language, first body no language, second body default language // message has no language, first body no language, second body default language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -453,7 +453,7 @@ public class PacketParserUtilsTest {
assertEquals(defaultLanguage, message.getBody(defaultLanguage)); assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertEquals(1, message.getBodies().size()); assertEquals(1, message.getBodies().size());
assertEquals(0, message.getBodyLanguages().size()); assertEquals(0, message.getBodyLanguages().size());
assertXMLNotEqual(control, message.toXML()); assertXMLNotEqual(control, message.toXML().toString());
// message has no language, first body no language, second body other language // message has no language, first body no language, second body other language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -477,7 +477,7 @@ public class PacketParserUtilsTest {
assertEquals(otherLanguage, message.getBody(otherLanguage)); assertEquals(otherLanguage, message.getBody(otherLanguage));
assertEquals(2, message.getBodies().size()); assertEquals(2, message.getBodies().size());
assertEquals(1, message.getBodyLanguages().size()); assertEquals(1, message.getBodyLanguages().size());
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has no language, first body no language, second body no language // message has no language, first body no language, second body no language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -499,7 +499,7 @@ public class PacketParserUtilsTest {
assertEquals(defaultLanguage, message.getBody(defaultLanguage)); assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertEquals(1, message.getBodies().size()); assertEquals(1, message.getBodies().size());
assertEquals(0, message.getBodyLanguages().size()); assertEquals(0, message.getBodyLanguages().size());
assertXMLNotEqual(control, message.toXML()); assertXMLNotEqual(control, message.toXML().toString());
} }
@ -535,7 +535,7 @@ public class PacketParserUtilsTest {
assertEquals(2, message.getSubjects().size()); assertEquals(2, message.getSubjects().size());
assertEquals(1, message.getSubjectLanguages().size()); assertEquals(1, message.getSubjectLanguages().size());
assertTrue(message.getSubjectLanguages().contains(otherLanguage)); assertTrue(message.getSubjectLanguages().contains(otherLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has default language, first subject no language, second subject default language // message has default language, first subject no language, second subject default language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -559,7 +559,7 @@ public class PacketParserUtilsTest {
assertEquals(defaultLanguage, message.getSubject(defaultLanguage)); assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertEquals(1, message.getSubjects().size()); assertEquals(1, message.getSubjects().size());
assertEquals(0, message.getSubjectLanguages().size()); assertEquals(0, message.getSubjectLanguages().size());
assertXMLNotEqual(control, message.toXML()); assertXMLNotEqual(control, message.toXML().toString());
// message has non-default language, first subject no language, second subject default language // message has non-default language, first subject no language, second subject default language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -584,7 +584,7 @@ public class PacketParserUtilsTest {
assertEquals(2, message.getSubjects().size()); assertEquals(2, message.getSubjects().size());
assertEquals(1, message.getSubjectLanguages().size()); assertEquals(1, message.getSubjectLanguages().size());
assertTrue(message.getSubjectLanguages().contains(defaultLanguage)); assertTrue(message.getSubjectLanguages().contains(defaultLanguage));
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has no language, first subject no language, second subject default language // message has no language, first subject no language, second subject default language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -607,7 +607,7 @@ public class PacketParserUtilsTest {
assertEquals(defaultLanguage, message.getSubject(defaultLanguage)); assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertEquals(1, message.getSubjects().size()); assertEquals(1, message.getSubjects().size());
assertEquals(0, message.getSubjectLanguages().size()); assertEquals(0, message.getSubjectLanguages().size());
assertXMLNotEqual(control, message.toXML()); assertXMLNotEqual(control, message.toXML().toString());
// message has no language, first subject no language, second subject other language // message has no language, first subject no language, second subject other language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -631,7 +631,7 @@ public class PacketParserUtilsTest {
assertEquals(otherLanguage, message.getSubject(otherLanguage)); assertEquals(otherLanguage, message.getSubject(otherLanguage));
assertEquals(2, message.getSubjects().size()); assertEquals(2, message.getSubjects().size());
assertEquals(1, message.getSubjectLanguages().size()); assertEquals(1, message.getSubjectLanguages().size());
assertXMLEqual(control, message.toXML()); assertXMLEqual(control, message.toXML().toString());
// message has no language, first subject no language, second subject no language // message has no language, first subject no language, second subject no language
control = XMLBuilder.create("message") control = XMLBuilder.create("message")
@ -653,7 +653,7 @@ public class PacketParserUtilsTest {
assertEquals(defaultLanguage, message.getSubject(defaultLanguage)); assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertEquals(1, message.getSubjects().size()); assertEquals(1, message.getSubjects().size());
assertEquals(0, message.getSubjectLanguages().size()); assertEquals(0, message.getSubjectLanguages().size());
assertXMLNotEqual(control, message.toXML()); assertXMLNotEqual(control, message.toXML().toString());
} }
@ -679,9 +679,9 @@ public class PacketParserUtilsTest {
+ "Bad Message Body</span>"; + "Bad Message Body</span>";
assertEquals(body, message.getBody()); assertEquals(body, message.getBody());
assertXMLNotEqual(control, message.toXML()); assertXMLNotEqual(control, message.toXML().toString());
DetailedDiff diffs = new DetailedDiff(new Diff(control, message.toXML())); DetailedDiff diffs = new DetailedDiff(new Diff(control, message.toXML().toString()));
// body has no namespace URI, span is escaped // body has no namespace URI, span is escaped
assertEquals(6, diffs.getAllDifferences().size()); assertEquals(6, diffs.getAllDifferences().size());
@ -754,7 +754,7 @@ public class PacketParserUtilsTest {
.asString(outputProperties); .asString(outputProperties);
Packet message = PacketParserUtils.parseMessage(TestUtils.getMessageParser(control)); Packet message = PacketParserUtils.parseMessage(TestUtils.getMessageParser(control));
Diff xmlDiff = new Diff(control, message.toXML()); Diff xmlDiff = new Diff(control, message.toXML().toString());
xmlDiff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier()); xmlDiff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
assertTrue(xmlDiff.similar()); assertTrue(xmlDiff.similar());
} }
@ -765,7 +765,7 @@ public class PacketParserUtilsTest {
Presence presence = PacketParserUtils.parsePresence(TestUtils.getPresenceParser(stanza)); Presence presence = PacketParserUtils.parsePresence(TestUtils.getPresenceParser(stanza));
assertXMLEqual(stanza, presence.toXML()); assertXMLEqual(stanza, presence.toXML().toString());
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@ -775,7 +775,7 @@ public class PacketParserUtilsTest {
Presence presence = PacketParserUtils.parsePresence(TestUtils.getPresenceParser(stanza)); Presence presence = PacketParserUtils.parsePresence(TestUtils.getPresenceParser(stanza));
assertXMLEqual(stanza, presence.toXML()); assertXMLEqual(stanza, presence.toXML().toString());
assertEquals(Presence.Type.unsubscribed, presence.getType()); assertEquals(Presence.Type.unsubscribed, presence.getType());
} }
@ -789,7 +789,7 @@ public class PacketParserUtilsTest {
+ "</presence>"; + "</presence>";
Presence presence = PacketParserUtils.parsePresence(TestUtils.getPresenceParser(stanza)); Presence presence = PacketParserUtils.parsePresence(TestUtils.getPresenceParser(stanza));
assertXMLEqual(stanza, presence.toXML()); assertXMLEqual(stanza, presence.toXML().toString());
assertEquals(Presence.Type.unsubscribed, presence.getType()); assertEquals(Presence.Type.unsubscribed, presence.getType());
assertEquals("dnd", presence.getMode().name()); assertEquals("dnd", presence.getMode().name());
assertEquals("en", presence.getLanguage()); assertEquals("en", presence.getLanguage());

View file

@ -35,37 +35,41 @@ public class StringUtilsTest {
assertNull(StringUtils.escapeForXML(null)); assertNull(StringUtils.escapeForXML(null));
input = "<b>"; input = "<b>";
assertEquals("&lt;b&gt;", StringUtils.escapeForXML(input)); assertCharSequenceEquals("&lt;b&gt;", StringUtils.escapeForXML(input));
input = "\""; input = "\"";
assertEquals("&quot;", StringUtils.escapeForXML(input)); assertCharSequenceEquals("&quot;", StringUtils.escapeForXML(input));
input = "&"; input = "&";
assertEquals("&amp;", StringUtils.escapeForXML(input)); assertCharSequenceEquals("&amp;", StringUtils.escapeForXML(input));
input = "<b>\n\t\r</b>"; input = "<b>\n\t\r</b>";
assertEquals("&lt;b&gt;\n\t\r&lt;/b&gt;", StringUtils.escapeForXML(input)); assertCharSequenceEquals("&lt;b&gt;\n\t\r&lt;/b&gt;", StringUtils.escapeForXML(input));
input = " & "; input = " & ";
assertEquals(" &amp; ", StringUtils.escapeForXML(input)); assertCharSequenceEquals(" &amp; ", StringUtils.escapeForXML(input));
input = " \" "; input = " \" ";
assertEquals(" &quot; ", StringUtils.escapeForXML(input)); assertCharSequenceEquals(" &quot; ", StringUtils.escapeForXML(input));
input = "> of me <"; input = "> of me <";
assertEquals("&gt; of me &lt;", StringUtils.escapeForXML(input)); assertCharSequenceEquals("&gt; of me &lt;", StringUtils.escapeForXML(input));
input = "> of me & you<"; input = "> of me & you<";
assertEquals("&gt; of me &amp; you&lt;", StringUtils.escapeForXML(input)); assertCharSequenceEquals("&gt; of me &amp; you&lt;", StringUtils.escapeForXML(input));
input = "& <"; input = "& <";
assertEquals("&amp; &lt;", StringUtils.escapeForXML(input)); assertCharSequenceEquals("&amp; &lt;", StringUtils.escapeForXML(input));
input = "&"; input = "&";
assertEquals("&amp;", StringUtils.escapeForXML(input)); assertCharSequenceEquals("&amp;", StringUtils.escapeForXML(input));
input = "It's a good day today"; input = "It's a good day today";
assertEquals("It&apos;s a good day today", StringUtils.escapeForXML(input)); assertCharSequenceEquals("It&apos;s a good day today", StringUtils.escapeForXML(input));
}
public static void assertCharSequenceEquals(CharSequence expected, CharSequence actual) {
assertEquals(expected.toString(), actual.toString());
} }
@Test @Test

View file

@ -801,7 +801,7 @@ public class EnhancedDebugger implements SmackDebugger {
messagesTable.addRow( messagesTable.addRow(
new Object[]{ new Object[]{
formatXML(packet.toXML()), formatXML(packet.toXML().toString()),
dateFormatter.format(new Date()), dateFormatter.format(new Date()),
packetReceivedIcon, packetReceivedIcon,
packetTypeIcon, packetTypeIcon,
@ -862,7 +862,7 @@ public class EnhancedDebugger implements SmackDebugger {
messagesTable.addRow( messagesTable.addRow(
new Object[]{ new Object[]{
formatXML(packet.toXML()), formatXML(packet.toXML().toString()),
dateFormatter.format(new Date()), dateFormatter.format(new Date()),
packetSentIcon, packetSentIcon,
packetTypeIcon, packetTypeIcon,

View file

@ -336,7 +336,7 @@ public class MultipleRecipientManager {
*/ */
private static class PacketCopy extends Packet { private static class PacketCopy extends Packet {
private String text; private CharSequence text;
/** /**
* Create a copy of a packet with the text to send. The passed text must be a valid text to * Create a copy of a packet with the text to send. The passed text must be a valid text to
@ -344,11 +344,12 @@ public class MultipleRecipientManager {
* *
* @param text the whole text of the packet to send * @param text the whole text of the packet to send
*/ */
public PacketCopy(String text) { public PacketCopy(CharSequence text) {
this.text = text; this.text = text;
} }
public String toXML() { @Override
public CharSequence toXML() {
return text; return text;
} }

View file

@ -128,7 +128,7 @@ public class SimpleDirectoryPersistentCache implements EntityCapsPersistentCache
private static void writeInfoToFile(File file, DiscoverInfo info) throws IOException { private static void writeInfoToFile(File file, DiscoverInfo info) throws IOException {
DataOutputStream dos = new DataOutputStream(new FileOutputStream(file)); DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
try { try {
dos.writeUTF(info.toXML()); dos.writeUTF(info.toXML().toString());
} finally { } finally {
dos.close(); dos.close();
} }

View file

@ -17,6 +17,7 @@
package org.jivesoftware.smackx.caps.packet; package org.jivesoftware.smackx.caps.packet;
import org.jivesoftware.smack.packet.PacketExtension; import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.util.XmlStringBuilder;
import org.jivesoftware.smackx.caps.EntityCapsManager; import org.jivesoftware.smackx.caps.EntityCapsManager;
public class CapsExtension implements PacketExtension { public class CapsExtension implements PacketExtension {
@ -56,10 +57,10 @@ public class CapsExtension implements PacketExtension {
* ver='QgayPKawpkPSDYmwT/WM94uAlu0='/> * ver='QgayPKawpkPSDYmwT/WM94uAlu0='/>
* *
*/ */
public String toXML() { public CharSequence toXML() {
return "<" + EntityCapsManager.ELEMENT + " xmlns=\"" + EntityCapsManager.NAMESPACE + "\" " + XmlStringBuilder xml = new XmlStringBuilder(this);
"hash=\"" + hash + "\" " + xml.attribute("hash", hash).attribute("node", node).attribute("ver", ver);
"node=\"" + node + "\" " + xml.closeEmptyElement();
"ver=\"" + ver + "\"/>"; return xml;
} }
} }

View file

@ -18,7 +18,7 @@
package org.jivesoftware.smackx.disco.packet; package org.jivesoftware.smackx.disco.packet;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.XmlStringBuilder;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
@ -186,29 +186,27 @@ public class DiscoverInfo extends IQ {
return false; return false;
} }
public String getChildElementXML() { @Override
StringBuilder buf = new StringBuilder(); public CharSequence getChildElementXML() {
buf.append("<query xmlns=\"" + NAMESPACE + "\""); XmlStringBuilder xml = new XmlStringBuilder();
if (getNode() != null) { xml.halfOpenElement("query");
buf.append(" node=\""); xml.xmlnsAttribute(NAMESPACE);
buf.append(StringUtils.escapeForXML(getNode())); xml.optAttribute("node", getNode());
buf.append("\""); xml.rightAngelBracket();
}
buf.append(">");
synchronized (identities) { synchronized (identities) {
for (Identity identity : identities) { for (Identity identity : identities) {
buf.append(identity.toXML()); xml.append(identity.toXML());
} }
} }
synchronized (features) { synchronized (features) {
for (Feature feature : features) { for (Feature feature : features) {
buf.append(feature.toXML()); xml.append(feature.toXML());
} }
} }
// Add packet extensions, if any are defined. // Add packet extensions, if any are defined.
buf.append(getExtensionsXML()); xml.append(getExtensionsXML());
buf.append("</query>"); xml.closeElement("query");
return buf.toString(); return xml;
} }
/** /**
@ -358,22 +356,15 @@ public class DiscoverInfo extends IQ {
return lang; return lang;
} }
public String toXML() { public XmlStringBuilder toXML() {
StringBuilder buf = new StringBuilder(); XmlStringBuilder xml = new XmlStringBuilder();
buf.append("<identity"); xml.halfOpenElement("identity");
// Check if this packet has 'lang' set and maybe append it to the resulting string xml.xmllangAttribute(lang);
if (lang != null) xml.attribute("category", category);
buf.append(" xml:lang=\"").append(StringUtils.escapeForXML(lang)).append("\""); xml.attribute("name", name);
// Category must always be set xml.optAttribute("type", type);
buf.append(" category=\"").append(StringUtils.escapeForXML(category)).append("\""); xml.closeEmptyElement();
// Name must always be set return xml;
buf.append(" name=\"").append(StringUtils.escapeForXML(name)).append("\"");
// Check if this packet has 'type' set and maybe append it to the resulting string
if (type != null) {
buf.append(" type=\"").append(StringUtils.escapeForXML(type)).append("\"");
}
buf.append("/>");
return buf.toString();
} }
/** /**
@ -488,10 +479,12 @@ public class DiscoverInfo extends IQ {
return variable; return variable;
} }
public String toXML() { public XmlStringBuilder toXML() {
StringBuilder buf = new StringBuilder(); XmlStringBuilder xml = new XmlStringBuilder();
buf.append("<feature var=\"").append(StringUtils.escapeForXML(variable)).append("\"/>"); xml.halfOpenElement("feature");
return buf.toString(); xml.attribute("var", variable);
xml.closeEmptyElement();
return xml;
} }
public boolean equals(Object obj) { public boolean equals(Object obj) {

View file

@ -18,7 +18,7 @@
package org.jivesoftware.smackx.disco.packet; package org.jivesoftware.smackx.disco.packet;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.XmlStringBuilder;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
@ -102,22 +102,20 @@ public class DiscoverItems extends IQ {
this.node = node; this.node = node;
} }
public String getChildElementXML() { public XmlStringBuilder getChildElementXML() {
StringBuilder buf = new StringBuilder(); XmlStringBuilder xml = new XmlStringBuilder();
buf.append("<query xmlns=\"" + NAMESPACE + "\""); xml.halfOpenElement("query");
if (getNode() != null) { xml.xmlnsAttribute(NAMESPACE);
buf.append(" node=\""); xml.optAttribute("node", getNode());
buf.append(StringUtils.escapeForXML(getNode())); xml.rightAngelBracket();
buf.append("\"");
}
buf.append(">");
synchronized (items) { synchronized (items) {
for (Item item : items) { for (Item item : items) {
buf.append(item.toXML()); xml.append(item.toXML());
} }
} }
buf.append("</query>"); xml.closeElement("query");
return buf.toString(); return xml;
} }
/** /**
@ -231,20 +229,15 @@ public class DiscoverItems extends IQ {
this.action = action; this.action = action;
} }
public String toXML() { public XmlStringBuilder toXML() {
StringBuilder buf = new StringBuilder(); XmlStringBuilder xml = new XmlStringBuilder();
buf.append("<item jid=\"").append(entityID).append("\""); xml.halfOpenElement("item");
if (name != null) { xml.attribute("jid", entityID);
buf.append(" name=\"").append(StringUtils.escapeForXML(name)).append("\""); xml.optAttribute("name", name);
} xml.optAttribute("node", node);
if (node != null) { xml.optAttribute("action", action);
buf.append(" node=\"").append(StringUtils.escapeForXML(node)).append("\""); xml.closeEmptyElement();
} return xml;
if (action != null) {
buf.append(" action=\"").append(StringUtils.escapeForXML(action)).append("\"");
}
buf.append("/>");
return buf.toString();
} }
} }
} }

View file

@ -46,7 +46,7 @@ public class AffiliationsExtension extends NodeExtension
} }
@Override @Override
public String toXML() public CharSequence toXML()
{ {
if ((items == null) || (items.size() == 0)) if ((items == null) || (items.size() == 0))
{ {

View file

@ -73,7 +73,7 @@ public class FormNode extends NodeExtension
} }
@Override @Override
public String toXML() public CharSequence toXML()
{ {
if (configForm == null) if (configForm == null)
{ {

View file

@ -151,7 +151,7 @@ public class ItemsExtension extends NodeExtension implements EmbeddedPacketExten
} }
@Override @Override
public String toXML() public CharSequence toXML()
{ {
if ((items == null) || (items.size() == 0)) if ((items == null) || (items.size() == 0))
{ {

View file

@ -75,7 +75,7 @@ public class NodeExtension implements PacketExtension
return element.getNamespace().getXmlns(); return element.getNamespace().getXmlns();
} }
public String toXML() public CharSequence toXML()
{ {
return '<' + getElementName() + (node == null ? "" : " node='" + node + '\'') + "/>"; return '<' + getElementName() + (node == null ? "" : " node='" + node + '\'') + "/>";
} }

View file

@ -16,7 +16,7 @@
*/ */
package org.jivesoftware.smackx.pubsub; package org.jivesoftware.smackx.pubsub;
import org.jivesoftware.smack.util.XmlUtils; import org.jivesoftware.smack.util.XmlStringBuilder;
/** /**
* A packet extension representing the <b>options</b> element. * A packet extension representing the <b>options</b> element.
@ -56,20 +56,13 @@ public class OptionsExtension extends NodeExtension
} }
@Override @Override
public String toXML() public XmlStringBuilder toXML() {
{ XmlStringBuilder xml = new XmlStringBuilder();
StringBuilder builder = new StringBuilder("<"); xml.halfOpenElement(getElementName());
builder.append(getElementName()); xml.attribute("jid", jid);
XmlUtils.appendAttribute(builder, "jid", jid); xml.optAttribute("node", getNode());
xml.optAttribute("subid", id);
if (getNode() != null) xml.closeEmptyElement();
XmlUtils.appendAttribute(builder, "node", getNode()); return xml;
if (id != null)
XmlUtils.appendAttribute(builder, "subid", id);
builder.append("/>");
return builder.toString();
} }
} }

View file

@ -66,7 +66,7 @@ public class SubscriptionsExtension extends NodeExtension
} }
@Override @Override
public String toXML() public CharSequence toXML()
{ {
if ((items == null) || (items.size() == 0)) if ((items == null) || (items.size() == 0))
{ {

View file

@ -16,7 +16,7 @@
*/ */
package org.jivesoftware.smackx.pubsub; package org.jivesoftware.smackx.pubsub;
import org.jivesoftware.smack.util.XmlUtils; import org.jivesoftware.smack.util.XmlStringBuilder;
/** /**
@ -57,20 +57,13 @@ public class UnsubscribeExtension extends NodeExtension
} }
@Override @Override
public String toXML() public XmlStringBuilder toXML() {
{ XmlStringBuilder xml = new XmlStringBuilder();
StringBuilder builder = new StringBuilder("<"); xml.halfOpenElement(getElementName());
builder.append(getElementName()); xml.attribute("jid", jid);
XmlUtils.appendAttribute(builder, "jid", jid); xml.optAttribute("node", getNode());
xml.optAttribute("subid", id);
if (getNode() != null) xml.closeEmptyElement();
XmlUtils.appendAttribute(builder, "node", getNode()); return xml;
if (id != null)
XmlUtils.appendAttribute(builder, "subid", id);
builder.append("/>");
return builder.toString();
} }
} }

View file

@ -844,11 +844,11 @@ public class VCard extends IQ {
appendTag(tag, null, null, hasContent, builder); appendTag(tag, null, null, hasContent, builder);
} }
private void appendTag(String tag, final String tagText) { private void appendTag(String tag, final CharSequence tagText) {
if (tagText == null) return; if (tagText == null) return;
final ContentBuilder contentBuilder = new ContentBuilder() { final ContentBuilder contentBuilder = new ContentBuilder() {
public void addTagContent() { public void addTagContent() {
sb.append(tagText.trim()); sb.append(tagText.toString().trim());
} }
}; };
appendTag(tag, true, contentBuilder); appendTag(tag, true, contentBuilder);

View file

@ -18,6 +18,7 @@
package org.jivesoftware.smackx.xdata; package org.jivesoftware.smackx.xdata;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.XmlStringBuilder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -264,15 +265,13 @@ public class FormField {
} }
public String toXML() { public String toXML() {
StringBuilder buf = new StringBuilder(); XmlStringBuilder buf = new XmlStringBuilder();
buf.append("<field"); buf.append("<field");
// Add attributes // Add attributes
if (getLabel() != null) { if (getLabel() != null) {
buf.append(" label=\"").append(getLabel()).append("\""); buf.append(" label=\"").append(getLabel()).append("\"");
} }
if (getVariable() != null) { buf.attribute("var", getVariable());
buf.append(" var=\"").append(getVariable()).append("\"");
}
if (getType() != null) { if (getType() != null) {
buf.append(" type=\"").append(getType()).append("\""); buf.append(" type=\"").append(getType()).append("\"");
} }
@ -286,7 +285,7 @@ public class FormField {
} }
// Loop through all the values and append them to the string buffer // Loop through all the values and append them to the string buffer
for (Iterator<String> i = getValues(); i.hasNext();) { for (Iterator<String> i = getValues(); i.hasNext();) {
buf.append("<value>").append(i.next()).append("</value>"); buf.element("value", i.next());
} }
// Loop through all the values and append them to the string buffer // Loop through all the values and append them to the string buffer
for (Iterator<Option> i = getOptions(); i.hasNext();) { for (Iterator<Option> i = getOptions(); i.hasNext();) {

View file

@ -78,7 +78,7 @@ public class CloseTest {
close.setTo("juliet@capulet.lit/balcony"); close.setTo("juliet@capulet.lit/balcony");
close.setPacketID("us71g45j"); close.setPacketID("us71g45j");
assertXMLEqual(control, close.toXML()); assertXMLEqual(control, close.toXML().toString());
} }
} }

View file

@ -83,7 +83,7 @@ public class DataTest {
data.setTo("juliet@capulet.lit/balcony"); data.setTo("juliet@capulet.lit/balcony");
data.setPacketID("kr91n475"); data.setPacketID("kr91n475");
assertXMLEqual(control, data.toXML()); assertXMLEqual(control, data.toXML().toString());
} }
} }

View file

@ -100,7 +100,7 @@ public class OpenTest {
open.setTo("juliet@capulet.lit/balcony"); open.setTo("juliet@capulet.lit/balcony");
open.setPacketID("jn3h8g65"); open.setPacketID("jn3h8g65");
assertXMLEqual(control, open.toXML()); assertXMLEqual(control, open.toXML().toString());
} }

View file

@ -101,7 +101,7 @@ public class EntityCapsManagerTest {
DiscoverInfo restored_di = EntityCapsManager.getDiscoveryInfoByNodeVer(nodeVer); DiscoverInfo restored_di = EntityCapsManager.getDiscoveryInfoByNodeVer(nodeVer);
assertNotNull(restored_di); assertNotNull(restored_di);
assertEquals(di.toXML(), restored_di.toXML()); assertEquals(di.toXML().toString(), restored_di.toXML().toString());
} }
private static DiscoverInfo createComplexSamplePacket() { private static DiscoverInfo createComplexSamplePacket() {

View file

@ -50,6 +50,7 @@ public class FileTransferNegotiatorTest {
FileTransferNegotiator fileNeg = FileTransferNegotiator.getInstanceFor(connection); FileTransferNegotiator fileNeg = FileTransferNegotiator.getInstanceFor(connection);
fileNeg.negotiateOutgoingTransfer("me", "streamid", "file", 1024, null, 10); fileNeg.negotiateOutgoingTransfer("me", "streamid", "file", 1024, null, 10);
Packet packet = connection.getSentPacket(); Packet packet = connection.getSentPacket();
assertTrue(packet.toXML().indexOf("\"stream-method\" type=\"list-single\"") != -1); String xml = packet.toXML().toString();
assertTrue(xml.indexOf("var='stream-method' type=\"list-single\"") != -1);
} }
} }

View file

@ -135,10 +135,10 @@ public class Protocol {
if (printProtocol) { if (printProtocol) {
System.out.println("------------------- Request -------------\n"); System.out.println("------------------- Request -------------\n");
System.out.println(prettyFormat(request.toXML())); System.out.println(prettyFormat(request.toXML().toString()));
System.out.println("------------------- Response ------------\n"); System.out.println("------------------- Response ------------\n");
if (response != null) { if (response != null) {
System.out.println(prettyFormat(response.toXML())); System.out.println(prettyFormat(response.toXML().toString()));
} }
else { else {
System.out.println("No response"); System.out.println("No response");

View file

@ -786,9 +786,6 @@ public class AgentSession {
* @throws NotConnectedException * @throws NotConnectedException
*/ */
public void setNote(String sessionID, String note) throws NoResponseException, XMPPErrorException, NotConnectedException { public void setNote(String sessionID, String note) throws NoResponseException, XMPPErrorException, NotConnectedException {
note = ChatNotes.replace(note, "\n", "\\n");
note = StringUtils.escapeForXML(note);
ChatNotes notes = new ChatNotes(); ChatNotes notes = new ChatNotes();
notes.setType(IQ.Type.SET); notes.setType(IQ.Type.SET);
notes.setTo(workgroupJID); notes.setTo(workgroupJID);

View file

@ -19,6 +19,7 @@ package org.jivesoftware.smackx.workgroup.ext.notes;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.provider.IQProvider; import org.jivesoftware.smack.provider.IQProvider;
import org.jivesoftware.smack.util.XmlStringBuilder;
import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParser;
/** /**
@ -57,13 +58,13 @@ public class ChatNotes extends IQ {
} }
public String getChildElementXML() { public String getChildElementXML() {
StringBuilder buf = new StringBuilder(); XmlStringBuilder buf = new XmlStringBuilder();
buf.append("<").append(ELEMENT_NAME).append(" xmlns=\"").append(NAMESPACE).append("\">"); buf.append("<").append(ELEMENT_NAME).append(" xmlns=\"").append(NAMESPACE).append("\">");
buf.append("<sessionID>").append(getSessionID()).append("</sessionID>"); buf.append("<sessionID>").append(getSessionID()).append("</sessionID>");
if (getNotes() != null) { if (getNotes() != null) {
buf.append("<notes>").append(getNotes()).append("</notes>"); buf.element("notes", getNotes());
} }
buf.append("</").append(ELEMENT_NAME).append("> "); buf.append("</").append(ELEMENT_NAME).append("> ");

View file

@ -374,13 +374,10 @@ public class Workgroup {
String name = iter.next(); String name = iter.next();
String value = metadata.get(name).toString(); String value = metadata.get(name).toString();
String escapedName = StringUtils.escapeForXML(name); FormField field = new FormField(name);
String escapedValue = StringUtils.escapeForXML(value);
FormField field = new FormField(escapedName);
field.setType(FormField.TYPE_TEXT_SINGLE); field.setType(FormField.TYPE_TEXT_SINGLE);
form.addField(field); form.addField(field);
form.setAnswer(escapedName, escapedValue); form.setAnswer(name, value);
} }
joinQueue(form, userID); joinQueue(form, userID);
} }

View file

@ -146,7 +146,7 @@ class PacketWriter {
while (!done && (writerThread == thisThread)) { while (!done && (writerThread == thisThread)) {
Packet packet = nextPacket(); Packet packet = nextPacket();
if (packet != null) { if (packet != null) {
writer.write(packet.toXML()); writer.write(packet.toXML().toString());
if (queue.isEmpty()) { if (queue.isEmpty()) {
writer.flush(); writer.flush();
@ -159,7 +159,7 @@ class PacketWriter {
try { try {
while (!queue.isEmpty()) { while (!queue.isEmpty()) {
Packet packet = queue.remove(); Packet packet = queue.remove();
writer.write(packet.toXML()); writer.write(packet.toXML().toString());
} }
writer.flush(); writer.flush();
} }