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

Introduce FormFieldChildElement and make FormField immutable

This commit is contained in:
Florian Schmaus 2019-06-10 16:58:38 +02:00
parent 1a99801501
commit 4d36e3b521
36 changed files with 1191 additions and 490 deletions

View file

@ -1,6 +1,6 @@
/** /**
* *
* Copyright 2015-2018 Florian Schmaus * Copyright 2015-2019 Florian Schmaus
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -49,4 +49,10 @@ public class CollectionUtil {
public interface Predicate<T> { public interface Predicate<T> {
boolean test(T t); boolean test(T t);
} }
public static <T> ArrayList<T> newListWith(Collection<? extends T> collection) {
ArrayList<T> arrayList = new ArrayList<>(collection.size());
arrayList.addAll(collection);
return arrayList;
}
} }

View file

@ -22,6 +22,7 @@ import java.util.LinkedHashMap;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
/** /**
@ -57,7 +58,11 @@ public class MultiMap<K, V> {
* @param size the initial capacity. * @param size the initial capacity.
*/ */
public MultiMap(int size) { public MultiMap(int size) {
map = new LinkedHashMap<>(size); this(new LinkedHashMap<>(size));
}
private MultiMap(Map<K, List<V>> map) {
this.map = map;
} }
public int size() { public int size() {
@ -235,6 +240,18 @@ public class MultiMap<K, V> {
return entrySet; return entrySet;
} }
public MultiMap<K, V> asUnmodifiableMultiMap() {
LinkedHashMap<K, List<V>> mapCopy = new LinkedHashMap<>(map.size());
for (Entry<K, List<V>> entry : map.entrySet()) {
K key = entry.getKey();
List<V> values = entry.getValue();
mapCopy.put(key, Collections.unmodifiableList(values));
}
return new MultiMap<K, V>(Collections.unmodifiableMap(mapCopy));
}
private static final class SimpleMapEntry<K, V> implements Map.Entry<K, V> { private static final class SimpleMapEntry<K, V> implements Map.Entry<K, V> {
private final K key; private final K key;

View file

@ -273,6 +273,15 @@ public class XmlStringBuilder implements Appendable, CharSequence, Element {
return this; return this;
} }
public <E extends Enum<?>> XmlStringBuilder attribute(String name, E value, E implicitDefault) {
if (value == null || value == implicitDefault) {
return this;
}
attribute(name, value.toString());
return this;
}
public XmlStringBuilder attribute(String name, int value) { public XmlStringBuilder attribute(String name, int value) {
assert name != null; assert name != null;
return attribute(name, String.valueOf(value)); return attribute(name, String.valueOf(value));

View file

@ -18,6 +18,7 @@ package org.jivesoftware.smack.test.util;
import java.util.Base64; import java.util.Base64;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.util.stringencoder.Base64.Encoder; import org.jivesoftware.smack.util.stringencoder.Base64.Encoder;
/** /**
@ -27,6 +28,7 @@ import org.jivesoftware.smack.util.stringencoder.Base64.Encoder;
public class SmackTestSuite { public class SmackTestSuite {
static { static {
SmackConfiguration.getVersion();
org.jivesoftware.smack.util.stringencoder.Base64.setEncoder(new Encoder() { org.jivesoftware.smack.util.stringencoder.Base64.setEncoder(new Encoder() {
@Override @Override

View file

@ -21,6 +21,7 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.WeakHashMap; import java.util.WeakHashMap;
@ -295,7 +296,7 @@ public final class MamManager extends Manager {
public static final class Builder { public static final class Builder {
private String node; private String node;
private final Map<String, FormField> formFields = new HashMap<>(8); private final Map<String, FormField> formFields = new LinkedHashMap<>(8);
private int maxResults = -1; private int maxResults = -1;
@ -329,8 +330,9 @@ public final class MamManager extends Manager {
return this; return this;
} }
FormField formField = new FormField(FORM_FIELD_START); FormField formField = FormField.builder(FORM_FIELD_START)
formField.addValue(start); .addValue(start)
.build();
formFields.put(formField.getVariable(), formField); formFields.put(formField.getVariable(), formField);
FormField endFormField = formFields.get(FORM_FIELD_END); FormField endFormField = formFields.get(FORM_FIELD_END);
@ -356,8 +358,9 @@ public final class MamManager extends Manager {
return this; return this;
} }
FormField formField = new FormField(FORM_FIELD_END); FormField formField = FormField.builder(FORM_FIELD_END)
formField.addValue(end); .addValue(end)
.build();
formFields.put(formField.getVariable(), formField); formFields.put(formField.getVariable(), formField);
FormField startFormField = formFields.get(FORM_FIELD_START); FormField startFormField = formFields.get(FORM_FIELD_START);
@ -469,9 +472,9 @@ public final class MamManager extends Manager {
} }
private static FormField getWithFormField(Jid withJid) { private static FormField getWithFormField(Jid withJid) {
FormField formField = new FormField(FORM_FIELD_WITH); return FormField.builder(FORM_FIELD_WITH)
formField.addValue(withJid.toString()); .addValue(withJid.toString())
return formField; .build();
} }
public MamQuery queryMostRecentPage(Jid jid, int max) throws NoResponseException, XMPPErrorException, public MamQuery queryMostRecentPage(Jid jid, int max) throws NoResponseException, XMPPErrorException,
@ -711,9 +714,7 @@ public final class MamManager extends Manager {
} }
private static DataForm getNewMamForm() { private static DataForm getNewMamForm() {
FormField field = new FormField(FormField.FORM_TYPE); FormField field = FormField.hiddenFormType(MamElements.NAMESPACE);
field.setType(FormField.Type.hidden);
field.addValue(MamElements.NAMESPACE);
DataForm form = new DataForm(DataForm.Type.submit); DataForm form = new DataForm(DataForm.Type.submit);
form.addField(field); form.addField(field);
return form; return form;

View file

@ -100,16 +100,19 @@ public class EnablePushNotificationsIQ extends IQ {
if (publishOptions != null) { if (publishOptions != null) {
DataForm dataForm = new DataForm(DataForm.Type.submit); DataForm dataForm = new DataForm(DataForm.Type.submit);
FormField formTypeField = new FormField("FORM_TYPE"); // TODO: Shouldn't this use some potentially existing PubSub API? Also FORM_TYPE fields are usually of type
// 'hidden', but the examples in XEP-0357 do also not set the value to hidden and FORM_TYPE itself appears
// to be more convention than specification.
FormField.Builder formTypeField = FormField.builder("FORM_TYPE");
formTypeField.addValue(PubSub.NAMESPACE + "#publish-options"); formTypeField.addValue(PubSub.NAMESPACE + "#publish-options");
dataForm.addField(formTypeField); dataForm.addField(formTypeField.build());
Iterator<Map.Entry<String, String>> publishOptionsIterator = publishOptions.entrySet().iterator(); Iterator<Map.Entry<String, String>> publishOptionsIterator = publishOptions.entrySet().iterator();
while (publishOptionsIterator.hasNext()) { while (publishOptionsIterator.hasNext()) {
Map.Entry<String, String> pairVariableValue = publishOptionsIterator.next(); Map.Entry<String, String> pairVariableValue = publishOptionsIterator.next();
FormField field = new FormField(pairVariableValue.getKey()); FormField.Builder field = FormField.builder(pairVariableValue.getKey());
field.addValue(pairVariableValue.getValue()); field.addValue(pairVariableValue.getValue());
dataForm.addField(field); dataForm.addField(field.build());
} }
xml.element(dataForm); xml.element(dataForm);

View file

@ -1,6 +1,6 @@
/** /**
* *
* Copyright 2016 Fernando Ramirez, 2018 Florian Schmaus * Copyright 2016 Fernando Ramirez, 2018-2019 Florian Schmaus
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -36,7 +36,7 @@ public class RetrieveFormFieldsTest extends MamTest {
private static final String additionalFieldsStanza = "<x xmlns='jabber:x:data' type='submit'>" + "<field var='FORM_TYPE' type='hidden'>" private static final String additionalFieldsStanza = "<x xmlns='jabber:x:data' type='submit'>" + "<field var='FORM_TYPE' type='hidden'>"
+ "<value>" + MamElements.NAMESPACE + "</value>" + "</field>" + "<value>" + MamElements.NAMESPACE + "</value>" + "</field>"
+ "<field var='urn:example:xmpp:free-text-search' type='text-single'>" + "<value>Hi</value>" + "</field>" + "<field var='urn:example:xmpp:free-text-search'>" + "<value>Hi</value>" + "</field>"
+ "<field var='urn:example:xmpp:stanza-content' type='jid-single'>" + "<value>Hi2</value>" + "</field>" + "<field var='urn:example:xmpp:stanza-content' type='jid-single'>" + "<value>Hi2</value>" + "</field>"
+ "</x>"; + "</x>";
@ -50,13 +50,15 @@ public class RetrieveFormFieldsTest extends MamTest {
@Test @Test
public void checkAddAdditionalFieldsStanza() throws Exception { public void checkAddAdditionalFieldsStanza() throws Exception {
FormField field1 = new FormField("urn:example:xmpp:free-text-search"); FormField field1 = FormField.builder("urn:example:xmpp:free-text-search")
field1.setType(FormField.Type.text_single); .setType(FormField.Type.text_single)
field1.addValue("Hi"); .addValue("Hi")
.build();
FormField field2 = new FormField("urn:example:xmpp:stanza-content"); FormField field2 = FormField.builder("urn:example:xmpp:stanza-content")
field2.setType(FormField.Type.jid_single); .setType(FormField.Type.jid_single)
field2.addValue("Hi2"); .addValue("Hi2")
.build();
MamQueryArgs mamQueryArgs = MamQueryArgs.builder() MamQueryArgs mamQueryArgs = MamQueryArgs.builder()
.withAdditionalFormField(field1) .withAdditionalFormField(field1)

View file

@ -1,6 +1,6 @@
/** /**
* *
* Copyright 2016 Florian Schmaus * Copyright 2016-2019 Florian Schmaus
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -30,11 +30,9 @@ import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smackx.commands.AdHocCommandManager; import org.jivesoftware.smackx.commands.AdHocCommandManager;
import org.jivesoftware.smackx.commands.RemoteCommand; import org.jivesoftware.smackx.commands.RemoteCommand;
import org.jivesoftware.smackx.xdata.Form; import org.jivesoftware.smackx.xdata.Form;
import org.jivesoftware.smackx.xdata.FormField;
import org.jxmpp.jid.EntityBareJid; import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.Jid; import org.jxmpp.jid.Jid;
import org.jxmpp.jid.util.JidUtil;
public class ServiceAdministrationManager extends Manager { public class ServiceAdministrationManager extends Manager {
@ -76,14 +74,9 @@ public class ServiceAdministrationManager extends Manager {
Form answerForm = command.getForm().createAnswerForm(); Form answerForm = command.getForm().createAnswerForm();
FormField accountJidField = answerForm.getField("accountjid"); answerForm.setAnswer("accountjid", userJid);
accountJidField.addValue(userJid.toString()); answerForm.setAnswer("password", password);
answerForm.setAnswer("password-verify", password);
FormField passwordField = answerForm.getField("password");
passwordField.addValue(password);
FormField passwordVerifyField = answerForm.getField("password-verify");
passwordVerifyField.addValue(password);
command.execute(answerForm); command.execute(answerForm);
assert (command.isCompleted()); assert (command.isCompleted());
@ -110,8 +103,7 @@ public class ServiceAdministrationManager extends Manager {
Form answerForm = command.getForm().createAnswerForm(); Form answerForm = command.getForm().createAnswerForm();
FormField accountJids = answerForm.getField("accountjids"); answerForm.setAnswer("accountjids", jidsToDelete);
accountJids.addValues(JidUtil.toStringList(jidsToDelete));
command.execute(answerForm); command.execute(answerForm);
assert (command.isCompleted()); assert (command.isCompleted());

View file

@ -226,7 +226,7 @@ public final class FileTransferNegotiator extends Manager {
boolean isByteStream = false; boolean isByteStream = false;
boolean isIBB = false; boolean isIBB = false;
for (FormField.Option option : field.getOptions()) { for (FormField.Option option : field.getOptions()) {
variable = option.getValue(); variable = option.getValueString();
if (variable.equals(Bytestream.NAMESPACE) && !IBB_ONLY) { if (variable.equals(Bytestream.NAMESPACE) && !IBB_ONLY) {
isByteStream = true; isByteStream = true;
} }
@ -369,13 +369,15 @@ public final class FileTransferNegotiator extends Manager {
private static DataForm createDefaultInitiationForm() { private static DataForm createDefaultInitiationForm() {
DataForm form = new DataForm(DataForm.Type.form); DataForm form = new DataForm(DataForm.Type.form);
FormField field = new FormField(STREAM_DATA_FIELD_NAME); FormField.Builder fieldBuilder = FormField.builder();
field.setType(FormField.Type.list_single); fieldBuilder.setFieldName(STREAM_DATA_FIELD_NAME)
.setType(FormField.Type.list_single);
if (!IBB_ONLY) { if (!IBB_ONLY) {
field.addOption(new FormField.Option(Bytestream.NAMESPACE)); fieldBuilder.addOption(Bytestream.NAMESPACE);
} }
field.addOption(new FormField.Option(DataPacketExtension.NAMESPACE)); fieldBuilder.addOption(DataPacketExtension.NAMESPACE);
form.addField(field); form.addField(fieldBuilder.build());
return form; return form;
} }
} }

View file

@ -81,12 +81,12 @@ public abstract class StreamNegotiator extends Manager {
response.setStanzaId(streamInitiationOffer.getStanzaId()); response.setStanzaId(streamInitiationOffer.getStanzaId());
DataForm form = new DataForm(DataForm.Type.submit); DataForm form = new DataForm(DataForm.Type.submit);
FormField field = new FormField( FormField.Builder field = FormField.builder(
FileTransferNegotiator.STREAM_DATA_FIELD_NAME); FileTransferNegotiator.STREAM_DATA_FIELD_NAME);
for (String namespace : namespaces) { for (String namespace : namespaces) {
field.addValue(namespace); field.addValue(namespace);
} }
form.addField(field); form.addField(field.build());
response.setFeatureNegotiationForm(form); response.setFeatureNegotiationForm(form);
return response; return response;

View file

@ -1212,14 +1212,14 @@ public class MultiUserChat {
*/ */
public void requestVoice() throws NotConnectedException, InterruptedException { public void requestVoice() throws NotConnectedException, InterruptedException {
DataForm form = new DataForm(DataForm.Type.submit); DataForm form = new DataForm(DataForm.Type.submit);
FormField formTypeField = new FormField(FormField.FORM_TYPE); FormField.Builder formTypeField = FormField.builder(FormField.FORM_TYPE);
formTypeField.addValue(MUCInitialPresence.NAMESPACE + "#request"); formTypeField.addValue(MUCInitialPresence.NAMESPACE + "#request");
form.addField(formTypeField); form.addField(formTypeField.build());
FormField requestVoiceField = new FormField("muc#role"); FormField.Builder requestVoiceField = FormField.builder("muc#role");
requestVoiceField.setType(FormField.Type.text_single); requestVoiceField.setType(FormField.Type.text_single);
requestVoiceField.setLabel("Requested role"); requestVoiceField.setLabel("Requested role");
requestVoiceField.addValue("participant"); requestVoiceField.addValue("participant");
form.addField(requestVoiceField); form.addField(requestVoiceField.build());
Message message = new Message(room); Message message = new Message(room);
message.addExtension(form); message.addExtension(form);
connection.sendStanza(message); connection.sendStanza(message);

View file

@ -665,8 +665,10 @@ public class ConfigureForm extends Form {
String fieldName = nodeField.getFieldName(); String fieldName = nodeField.getFieldName();
if (getField(fieldName) == null) { if (getField(fieldName) == null) {
FormField field = new FormField(fieldName); FormField field = FormField.builder()
field.setType(type); .setVariable(fieldName)
.setType(type)
.build();
addField(field); addField(field);
} }
} }

View file

@ -209,9 +209,9 @@ public class SubscribeForm extends Form {
String fieldName = nodeField.getFieldName(); String fieldName = nodeField.getFieldName();
if (getField(fieldName) == null) { if (getField(fieldName) == null) {
FormField field = new FormField(fieldName); FormField.Builder field = FormField.builder(fieldName);
field.setType(type); field.setType(type);
addField(field); addField(field.build());
} }
} }
} }

View file

@ -175,7 +175,7 @@ public class UserSearch extends SimpleIQ {
if (eventType == XmlPullParser.Event.START_ELEMENT && !parser.getNamespace().equals("jabber:x:data")) { if (eventType == XmlPullParser.Event.START_ELEMENT && !parser.getNamespace().equals("jabber:x:data")) {
String name = parser.getName(); String name = parser.getName();
FormField field = new FormField(name); FormField.Builder field = FormField.builder(name);
// Handle hard coded values. // Handle hard coded values.
if (name.equals("first")) { if (name.equals("first")) {
@ -192,7 +192,7 @@ public class UserSearch extends SimpleIQ {
} }
field.setType(FormField.Type.text_single); field.setType(FormField.Type.text_single);
dataForm.addField(field); dataForm.addField(field.build());
} }
else if (eventType == XmlPullParser.Event.END_ELEMENT) { else if (eventType == XmlPullParser.Event.END_ELEMENT) {
if (parser.getName().equals("query")) { if (parser.getName().equals("query")) {

View file

@ -17,6 +17,7 @@
package org.jivesoftware.smackx.xdata; package org.jivesoftware.smackx.xdata;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.StringTokenizer; import java.util.StringTokenizer;
@ -107,7 +108,7 @@ public class Form {
* @throws IllegalArgumentException if the form does not include the specified variable or * @throws IllegalArgumentException if the form does not include the specified variable or
* if the answer type does not correspond with the field type.. * if the answer type does not correspond with the field type..
*/ */
public void setAnswer(String variable, String value) { public void setAnswer(String variable, CharSequence value) {
FormField field = getField(variable); FormField field = getField(variable);
if (field == null) { if (field == null) {
throw new IllegalArgumentException("Field not found for the specified variable name."); throw new IllegalArgumentException("Field not found for the specified variable name.");
@ -260,8 +261,9 @@ public class Form {
throw new IllegalStateException("Cannot set an answer if the form is not of type " + throw new IllegalStateException("Cannot set an answer if the form is not of type " +
"\"submit\""); "\"submit\"");
} }
field.resetValues();
field.addValue(value.toString()); FormField filledOutfield = field.buildAnswer().addValue(value.toString()).build();
dataForm.replaceField(filledOutfield);
} }
/** /**
@ -277,7 +279,7 @@ public class Form {
* @throws IllegalStateException if the form is not of type "submit". * @throws IllegalStateException if the form is not of type "submit".
* @throws IllegalArgumentException if the form does not include the specified variable. * @throws IllegalArgumentException if the form does not include the specified variable.
*/ */
public void setAnswer(String variable, List<? extends CharSequence> values) { public void setAnswer(String variable, Collection<? extends CharSequence> values) {
if (!isSubmitType()) { if (!isSubmitType()) {
throw new IllegalStateException("Cannot set an answer if the form is not of type " + throw new IllegalStateException("Cannot set an answer if the form is not of type " +
"\"submit\""); "\"submit\"");
@ -295,10 +297,9 @@ public class Form {
default: default:
throw new IllegalArgumentException("This field only accept list of values."); throw new IllegalArgumentException("This field only accept list of values.");
} }
// Clear the old values
field.resetValues(); FormField filledOutfield = field.buildAnswer().addValues(values).build();
// Set the new values. The string representation of each value will be actually used. dataForm.replaceField(filledOutfield);
field.addValues(values);
} }
else { else {
throw new IllegalArgumentException("Couldn't find a field for the specified variable."); throw new IllegalArgumentException("Couldn't find a field for the specified variable.");
@ -321,12 +322,12 @@ public class Form {
} }
FormField field = getField(variable); FormField field = getField(variable);
if (field != null) { if (field != null) {
// Clear the old values FormField.Builder filledOutFormFieldBuilder = field.buildAnswer();
field.resetValues();
// Set the default value // Set the default value
for (CharSequence value : field.getValues()) { for (CharSequence value : field.getValues()) {
field.addValue(value); filledOutFormFieldBuilder.addValue(value);
} }
dataForm.replaceField(filledOutFormFieldBuilder.build());
} }
else { else {
throw new IllegalArgumentException("Couldn't find a field for the specified variable."); throw new IllegalArgumentException("Couldn't find a field for the specified variable.");
@ -497,9 +498,9 @@ public class Form {
// Add to the new form any type of field that includes a variable. // Add to the new form any type of field that includes a variable.
// Note: The fields of type FIXED are the only ones that don't specify a variable // Note: The fields of type FIXED are the only ones that don't specify a variable
if (field.getVariable() != null) { if (field.getVariable() != null) {
FormField newField = new FormField(field.getVariable()); FormField.Builder newField = FormField.builder(field.getVariable());
newField.setType(field.getType()); newField.setType(field.getType());
form.addField(newField); form.addField(newField.build());
// Set the answer ONLY to the hidden fields // Set the answer ONLY to the hidden fields
if (field.getType() == FormField.Type.hidden) { if (field.getType() == FormField.Type.hidden) {
// Since a hidden field could have many values we need to collect them // Since a hidden field could have many values we need to collect them

View file

@ -1,6 +1,6 @@
/** /**
* *
* Copyright 2003-2007 Jive Software. * Copyright 2003-2007 Jive Software, 2019 Florian Schmaus.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -19,16 +19,21 @@ package org.jivesoftware.smackx.xdata;
import java.text.ParseException; import java.text.ParseException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.jivesoftware.smack.packet.NamedElement; import javax.xml.namespace.QName;
import org.jivesoftware.smack.packet.FullyQualifiedElement;
import org.jivesoftware.smack.packet.XmlEnvironment; import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.CollectionUtil;
import org.jivesoftware.smack.util.MultiMap;
import org.jivesoftware.smack.util.XmlStringBuilder; import org.jivesoftware.smack.util.XmlStringBuilder;
import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement; import org.jivesoftware.smackx.xdata.packet.DataForm;
import org.jxmpp.util.XmppDateTime; import org.jxmpp.util.XmppDateTime;
@ -39,10 +44,14 @@ import org.jxmpp.util.XmppDateTime;
* *
* @author Gaston Dombiak * @author Gaston Dombiak
*/ */
public class FormField implements NamedElement { public final class FormField implements FullyQualifiedElement {
public static final String ELEMENT = "field"; public static final String ELEMENT = "field";
public static final String NAMESPACE = DataForm.NAMESPACE;
public static final QName QNAME = new QName(NAMESPACE, ELEMENT);
/** /**
* The constant String "FORM_TYPE". * The constant String "FORM_TYPE".
*/ */
@ -140,33 +149,91 @@ public class FormField implements NamedElement {
} }
} }
/**
* The field's name. Put as value in the 'var' attribute of &lt;field/&gt;.
*/
private final String variable; private final String variable;
private String description; private final String label;
private boolean required = false;
private String label;
private Type type;
private final List<Option> options = new ArrayList<>();
private final List<CharSequence> values = new ArrayList<>();
private ValidateElement validateElement;
/** private final Type type;
* Creates a new FormField with the variable name that uniquely identifies the field
* in the context of the form. private final List<FormFieldChildElement> formFieldChildElements;
*
* @param variable the variable name of the question. private final MultiMap<QName, FormFieldChildElement> formFieldChildElementsMap;
/*
* The following four fields are cache values which are represented as child elements of </form> and hence also
* appear in formFieldChildElements.
*/ */
public FormField(String variable) { private final List<Option> options;
this.variable = StringUtils.requireNotNullNorEmpty(variable, "Variable must not be null nor empty"); private final List<CharSequence> values;
private final String description;
private final boolean required;
private MultiMap<QName, FormFieldChildElement> createChildElementsMap() {
MultiMap<QName, FormFieldChildElement> formFieldChildElementsMap = new MultiMap<>(formFieldChildElements.size());
for (FormFieldChildElement formFieldChildElement : formFieldChildElements) {
formFieldChildElementsMap.put(formFieldChildElement.getQName(), formFieldChildElement);
}
return formFieldChildElementsMap.asUnmodifiableMultiMap();
} }
/** private FormField(String value) {
* Creates a new FormField of type FIXED. The fields of type FIXED do not define a variable variable = FORM_TYPE;
* name. type = Type.hidden;
*/ label = null;
public FormField() { required = false;
this.variable = null; description = null;
this.type = Type.fixed;
formFieldChildElements = Collections.singletonList(new Value(value));
values = Collections.singletonList(value);
options = Collections.emptyList();
formFieldChildElementsMap = createChildElementsMap();
}
private FormField(Builder builder) {
variable = builder.variable;
label = builder.label;
type = builder.type;
if (builder.formFieldChildElements != null) {
formFieldChildElements = Collections.unmodifiableList(builder.formFieldChildElements);
} else {
formFieldChildElements = Collections.emptyList();
}
if (variable == null && type != Type.fixed) {
throw new IllegalArgumentException("The variable can only be null if the form is of type fixed");
}
String description = null;
boolean requiredElementAsChild = false;
ArrayList<Option> options = new ArrayList<>(formFieldChildElements.size());
ArrayList<CharSequence> values = new ArrayList<>(formFieldChildElements.size());
for (FormFieldChildElement formFieldChildElement : formFieldChildElements) {
if (formFieldChildElement instanceof Value) {
Value value = (Value) formFieldChildElement;
values.add(value.getValue());
} else if (formFieldChildElement instanceof Option) {
Option option = (Option) formFieldChildElement;
options.add(option);
} else if (formFieldChildElement instanceof Description) {
description = ((Description) formFieldChildElement).getDescription();
// Required is a singleton instance.
} else if (formFieldChildElement == Required.INSTANCE) {
requiredElementAsChild = true;
}
}
options.trimToSize();
values.trimToSize();
this.options = Collections.unmodifiableList(options);
this.values = Collections.unmodifiableList(values);
this.description = description;
required = requiredElementAsChild;
formFieldChildElementsMap = createChildElementsMap();
} }
/** /**
@ -200,9 +267,7 @@ public class FormField implements NamedElement {
* @return List of the available options. * @return List of the available options.
*/ */
public List<Option> getOptions() { public List<Option> getOptions() {
synchronized (options) { return options;
return Collections.unmodifiableList(new ArrayList<>(options));
}
} }
/** /**
@ -221,6 +286,9 @@ public class FormField implements NamedElement {
* @see Type * @see Type
*/ */
public Type getType() { public Type getType() {
if (type == null) {
return Type.text_single;
}
return type; return type;
} }
@ -289,143 +357,25 @@ public class FormField implements NamedElement {
} }
/** /**
* Returns the variable name that the question is filling out. * Returns the field's name, also known as the variable name in case this is an filled out answer form.
* <p> * <p>
* According to XEP-4 § 3.2 the variable name (the 'var' attribute) * According to XEP-4 § 3.2 the variable name (the 'var' attribute)
* "uniquely identifies the field in the context of the form" (if the field is not of type 'fixed', in which case * "uniquely identifies the field in the context of the form" (if the field is not of type 'fixed', in which case
* the field "MAY possess a 'var' attribute") * the field "MAY possess a 'var' attribute")
* </p> * </p>
* *
* @return the variable name of the question. * @return the field's name.
*/ */
public String getVariable() { public String getVariable() {
return variable; return variable;
} }
/** public FormFieldChildElement getFormFieldChildElement(QName qname) {
* Get validate element. return formFieldChildElementsMap.getFirst(qname);
*
* @return the validateElement
*/
public ValidateElement getValidateElement() {
return validateElement;
} }
/** public List<FormFieldChildElement> getFormFieldChildElements(QName qname) {
* Sets a description that provides extra clarification about the question. This information return formFieldChildElementsMap.getAll(qname);
* could be presented to the user either in tool-tip, help button, or as a section of text
* before the question.
* <p>
* If the question is of type FIXED then the description should remain empty.
* </p>
*
* @param description provides extra clarification about the question.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Sets the label of the question which should give enough information to the user to
* fill out the form.
*
* @param label the label of the question.
*/
public void setLabel(String label) {
this.label = label;
}
/**
* Sets if the question must be answered in order to complete the questionnaire.
*
* @param required if the question must be answered in order to complete the questionnaire.
*/
public void setRequired(boolean required) {
this.required = required;
}
/**
* Set validate element.
* @param validateElement the validateElement to set
*/
public void setValidateElement(ValidateElement validateElement) {
validateElement.checkConsistency(this);
this.validateElement = validateElement;
}
/**
* Sets an indicative of the format for the data to answer.
* <p>
* This method will throw an IllegalArgumentException if type is 'fixed'. To create FormFields of type 'fixed' use
* {@link #FormField()} instead.
* </p>
*
* @param type an indicative of the format for the data to answer.
* @see Type
* @throws IllegalArgumentException if type is 'fixed'.
*/
public void setType(Type type) {
if (type == Type.fixed) {
throw new IllegalArgumentException("Can not set type to fixed, use FormField constructor without arguments instead.");
}
this.type = type;
}
/**
* Adds a default value to the question if the question is part of a form to fill out.
* Otherwise, adds an answered value to the question.
*
* @param value a default value or an answered value of the question.
*/
public void addValue(CharSequence value) {
synchronized (values) {
values.add(value);
}
}
/**
* Adds the given Date as XEP-0082 formated string by invoking {@link #addValue(CharSequence)} after the date
* instance was formated.
*
* @param date the date instance to add as XEP-0082 formated string.
* @since 4.3.0
*/
public void addValue(Date date) {
String dateString = XmppDateTime.formatXEP0082Date(date);
addValue(dateString);
}
/**
* Adds a default values to the question if the question is part of a form to fill out.
* Otherwise, adds an answered values to the question.
*
* @param newValues default values or an answered values of the question.
*/
public void addValues(List<? extends CharSequence> newValues) {
synchronized (values) {
values.addAll(newValues);
}
}
/**
* Removes all the values of the field.
*/
protected void resetValues() {
synchronized (values) {
values.clear();
}
}
/**
* Adss an available options to the question that the user has in order to answer
* the question.
*
* @param option a new available option for the question.
*/
public void addOption(Option option) {
synchronized (options) {
options.add(option);
}
} }
@Override @Override
@ -433,27 +383,42 @@ public class FormField implements NamedElement {
return ELEMENT; return ELEMENT;
} }
@Override
public String getNamespace() {
return NAMESPACE;
}
@Override
public QName getQName() {
return QNAME;
}
public Builder buildAnswer() {
return asBuilder().resetValues();
}
public Builder asBuilder() {
return new Builder(this);
}
@Override @Override
public XmlStringBuilder toXML(XmlEnvironment enclosingNamespace) { public XmlStringBuilder toXML(XmlEnvironment enclosingNamespace) {
XmlStringBuilder buf = new XmlStringBuilder(this); XmlStringBuilder buf = new XmlStringBuilder(this, enclosingNamespace);
// Add attributes // Add attributes
buf.optAttribute("label", getLabel()); buf.optAttribute("label", getLabel());
buf.optAttribute("var", getVariable()); buf.optAttribute("var", getVariable());
buf.optAttribute("type", getType()); // If no 'type' is specified, the default is "text-single";
buf.attribute("type", getType(), Type.text_single);
if (formFieldChildElements.isEmpty()) {
buf.closeEmptyElement();
} else {
buf.rightAngleBracket(); buf.rightAngleBracket();
// Add elements
buf.optElement("desc", getDescription()); buf.append(formFieldChildElements, enclosingNamespace);
buf.condEmptyElement(isRequired(), "required");
// Loop through all the values and append them to the string buffer
for (CharSequence value : getValues()) {
buf.element("value", value);
}
// Loop through all the values and append them to the string buffer
for (Option option : getOptions()) {
buf.append(option.toXML());
}
buf.optElement(validateElement);
buf.closeElement(this); buf.closeElement(this);
}
return buf; return buf;
} }
@ -476,23 +441,268 @@ public class FormField implements NamedElement {
return toXML().toString().hashCode(); return toXML().toString().hashCode();
} }
public static FormField hiddenFormType(String value) {
return new FormField(value);
}
public static Builder builder(String fieldName) {
return builder().setFieldName(fieldName);
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private String variable;
private String label;
private Type type;
private List<FormFieldChildElement> formFieldChildElements;
private boolean disallowType;
private boolean disallowFurtherFormFieldChildElements;
private Builder() {
}
private Builder(FormField formField) {
variable = formField.variable;
label = formField.label;
type = formField.type;
// Create a new modifiable list.
formFieldChildElements = CollectionUtil.newListWith(formField.formFieldChildElements);
}
public Builder setFieldName(String fieldName) {
return setVariable(fieldName);
}
public Builder setVariable(String variable) {
this.variable = variable;
return this;
}
/**
* Sets an indicative of the format for the data to answer.
*
* @param type an indicative of the format for the data to answer.
* @see Type
*/
public Builder setType(Type type) {
final Type oldType = this.type;
this.type = type;
try {
checkFormFieldChildElementsConsistency();
} catch (IllegalArgumentException e) {
this.type = oldType;
throw e;
}
return this;
}
/**
* Sets a description that provides extra clarification about the question. This information
* could be presented to the user either in tool-tip, help button, or as a section of text
* before the question.
* <p>
* If the question is of type FIXED then the description should remain empty.
* </p>
*
* @param description provides extra clarification about the question.
*/
public Builder setDescription(String description) {
Description descriptionElement = new Description(description);
setOnlyElement(descriptionElement, Description.class);
return this;
}
/**
* Sets the label of the question which should give enough information to the user to
* fill out the form.
*
* @param label the label of the question.
*/
public Builder setLabel(String label) {
this.label = label;
return this;
}
/**
* Sets if the question must be answered in order to complete the questionnaire.
*
* @param required if the question must be answered in order to complete the questionnaire.
*/
public Builder setRequired(boolean required) {
setOnlyElement(Required.INSTANCE, Required.class);
return this;
}
/**
* Adds a default value to the question if the question is part of a form to fill out.
* Otherwise, adds an answered value to the question.
*
* @param value a default value or an answered value of the question.
*/
public Builder addValue(CharSequence value) {
return addFormFieldChildElement(new Value(value));
}
/**
* Adds the given Date as XEP-0082 formated string by invoking {@link #addValue(CharSequence)} after the date
* instance was formated.
*
* @param date the date instance to add as XEP-0082 formated string.
*/
public Builder addValue(Date date) {
String dateString = XmppDateTime.formatXEP0082Date(date);
return addValue(dateString);
}
/**
* Adds a default values to the question if the question is part of a form to fill out.
* Otherwise, adds an answered values to the question.
*
* @param values default values or an answered values of the question.
*/
public Builder addValues(Collection<? extends CharSequence> values) {
for (CharSequence value : values) {
addValue(value);
}
return this;
}
public Builder addOption(String option) {
return addOption(new Option(option));
}
/**
* Adds an available options to the question that the user has in order to answer
* the question.
*
* @param option a new available option for the question.
*/
public Builder addOption(Option option) {
return addFormFieldChildElement(option);
}
public Builder addFormFieldChildElement(FormFieldChildElement formFieldChildElement) {
if (disallowFurtherFormFieldChildElements) {
throw new IllegalArgumentException();
}
if (formFieldChildElement.requiresNoTypeSet() && type != null) {
throw new IllegalArgumentException("Elements of type " + formFieldChildElement.getClass()
+ " can only be added to form fields where no type is set");
}
ensureThatFormFieldChildElementsIsSet();
if (!formFieldChildElements.isEmpty() && formFieldChildElement.isExclusiveElement()) {
throw new IllegalArgumentException("Elements of type " + formFieldChildElement.getClass()
+ " must be the only child elements of a form field.");
}
disallowType = disallowType || formFieldChildElement.requiresNoTypeSet();
disallowFurtherFormFieldChildElements = formFieldChildElement.isExclusiveElement();
formFieldChildElements.add(formFieldChildElement);
return this;
}
public Builder resetValues() {
if (formFieldChildElements == null) {
return this;
}
// TODO: Use Java' stream API once Smack's minimum Android SDK level is 24 or higher.
Iterator<FormFieldChildElement> it = formFieldChildElements.iterator();
while (it.hasNext()) {
FormFieldChildElement formFieldChildElement = it.next();
if (formFieldChildElement instanceof Value) {
it.remove();
}
}
disallowType = disallowFurtherFormFieldChildElements = false;
return this;
}
public FormField build() {
return new FormField(this);
}
public Type getType() {
return type;
}
private void ensureThatFormFieldChildElementsIsSet() {
if (formFieldChildElements == null) {
formFieldChildElements = new ArrayList<>(4);
}
}
private <E extends FormFieldChildElement> void setOnlyElement(E element, Class<E> elementClass) {
ensureThatFormFieldChildElementsIsSet();
for (int i = 0; i < formFieldChildElements.size(); i++) {
if (formFieldChildElements.get(i).getClass().equals(elementClass)) {
formFieldChildElements.set(i, element);
return;
}
}
formFieldChildElements.add(0, element);
}
private void checkFormFieldChildElementsConsistency() {
if (formFieldChildElements == null) {
return;
}
for (FormFieldChildElement formFiledChildElement : formFieldChildElements) {
formFiledChildElement.checkConsistency(this);
}
}
}
/**
* Marker class for the standard, as per XEP-0004, child elements of form fields.
*/
private abstract static class StandardFormFieldChildElement implements FormFieldChildElement {
}
/** /**
* Represents the available option of a given FormField. * Represents the available option of a given FormField.
* *
* @author Gaston Dombiak * @author Gaston Dombiak
*/ */
public static final class Option implements NamedElement { public static final class Option extends StandardFormFieldChildElement {
public static final String ELEMENT = "option"; public static final String ELEMENT = "option";
private final String value; public static final QName QNAME = new QName(NAMESPACE, ELEMENT);
private String label;
private final String label;
private final Value value;
public Option(String value) { public Option(String value) {
this.value = value; this(null, value);
} }
public Option(String label, String value) { public Option(String label, String value) {
this.label = label;
this.value = new Value(value);
}
public Option(String label, Value value) {
this.label = label; this.label = label;
this.value = value; this.value = value;
} }
@ -511,10 +721,19 @@ public class FormField implements NamedElement {
* *
* @return the value of the option. * @return the value of the option.
*/ */
public String getValue() { public Value getValue() {
return value; return value;
} }
/**
* Returns the string representation of the value of the option.
*
* @return the value of the option.
*/
public String getValueString() {
return value.value.toString();
}
@Override @Override
public String toString() { public String toString() {
return getLabel(); return getLabel();
@ -525,6 +744,16 @@ public class FormField implements NamedElement {
return ELEMENT; return ELEMENT;
} }
@Override
public String getNamespace() {
return NAMESPACE;
}
@Override
public QName getQName() {
return QNAME;
}
@Override @Override
public XmlStringBuilder toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) { public XmlStringBuilder toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) {
XmlStringBuilder xml = new XmlStringBuilder(this); XmlStringBuilder xml = new XmlStringBuilder(this);
@ -533,7 +762,7 @@ public class FormField implements NamedElement {
xml.rightAngleBracket(); xml.rightAngleBracket();
// Add element // Add element
xml.element("value", getValue()); xml.element("value", getValueString());
xml.closeElement(this); xml.closeElement(this);
return xml; return xml;
@ -569,5 +798,124 @@ public class FormField implements NamedElement {
result = 37 * result + (label == null ? 0 : label.hashCode()); result = 37 * result + (label == null ? 0 : label.hashCode());
return result; return result;
} }
}
public static class Description extends StandardFormFieldChildElement {
public static final String ELEMENT = "desc";
public static final QName QNAME = new QName(NAMESPACE, ELEMENT);
private final String description;
public Description(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
@Override
public String getElementName() {
return ELEMENT;
}
@Override
public String getNamespace() {
return NAMESPACE;
}
@Override
public QName getQName() {
return QNAME;
}
@Override
public XmlStringBuilder toXML(XmlEnvironment xmlEnvironment) {
XmlStringBuilder xml = new XmlStringBuilder(this, xmlEnvironment);
xml.rightAngleBracket();
xml.escape(description);
xml.closeElement(this);
return xml;
}
}
public static final class Required extends StandardFormFieldChildElement {
public static final Required INSTANCE = new Required();
public static final String ELEMENT = "required";
public static final QName QNAME = new QName(NAMESPACE, ELEMENT);
private Required() {
}
@Override
public String getElementName() {
return ELEMENT;
}
@Override
public String getNamespace() {
return NAMESPACE;
}
@Override
public QName getQName() {
return QNAME;
}
@Override
public boolean mustBeOnlyOfHisKind() {
return true;
}
@Override
public String toXML(XmlEnvironment xmlEnvironment) {
return '<' + ELEMENT + "/>";
}
}
public static class Value extends StandardFormFieldChildElement {
public static final String ELEMENT = "value";
public static final QName QNAME = new QName(NAMESPACE, ELEMENT);
private final CharSequence value;
public Value(CharSequence value) {
this.value = value;
}
public CharSequence getValue() {
return value;
}
@Override
public String getElementName() {
return ELEMENT;
}
@Override
public String getNamespace() {
return NAMESPACE;
}
@Override
public QName getQName() {
return QNAME;
}
@Override
public XmlStringBuilder toXML(XmlEnvironment xmlEnvironment) {
XmlStringBuilder xml = new XmlStringBuilder(this, xmlEnvironment);
xml.rightAngleBracket();
xml.escape(value);
return xml.closeElement(this);
}
} }
} }

View file

@ -0,0 +1,39 @@
/**
*
* Copyright 2019 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.smackx.xdata;
import org.jivesoftware.smack.packet.FullyQualifiedElement;
public interface FormFieldChildElement extends FullyQualifiedElement {
default boolean isExclusiveElement() {
return false;
}
default boolean requiresNoTypeSet() {
return isExclusiveElement();
}
default boolean mustBeOnlyOfHisKind() {
return false;
}
default void checkConsistency(FormField.Builder formFieldBuilder) throws IllegalArgumentException {
// Does nothing per default.
}
}

View file

@ -1,6 +1,6 @@
/** /**
* *
* Copyright 2014-2015 Florian Schmaus * Copyright 2014-2019 Florian Schmaus
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -29,6 +29,11 @@ import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.xdata.packet.DataForm; import org.jivesoftware.smackx.xdata.packet.DataForm;
import org.jivesoftware.smackx.xdata.provider.DescriptionProvider;
import org.jivesoftware.smackx.xdata.provider.FormFieldChildElementProviderManager;
import org.jivesoftware.smackx.xdata.provider.OptionProvider;
import org.jivesoftware.smackx.xdata.provider.RequiredProvider;
import org.jivesoftware.smackx.xdata.provider.ValueProvider;
import org.jxmpp.jid.Jid; import org.jxmpp.jid.Jid;
@ -40,6 +45,13 @@ public final class XDataManager extends Manager {
public static final String NAMESPACE = DataForm.NAMESPACE; public static final String NAMESPACE = DataForm.NAMESPACE;
static { static {
FormFieldChildElementProviderManager.addFormFieldChildElementProvider(
new DescriptionProvider(),
new OptionProvider(),
new RequiredProvider(),
new ValueProvider()
);
XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
@Override @Override
public void connectionCreated(XMPPConnection connection) { public void connectionCreated(XMPPConnection connection) {

View file

@ -28,6 +28,7 @@ import java.util.Map;
import org.jivesoftware.smack.packet.Element; import org.jivesoftware.smack.packet.Element;
import org.jivesoftware.smack.packet.ExtensionElement; import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Stanza; import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.util.XmlStringBuilder; import org.jivesoftware.smack.util.XmlStringBuilder;
import org.jivesoftware.smackx.xdata.FormField; import org.jivesoftware.smackx.xdata.FormField;
@ -160,6 +161,17 @@ public class DataForm implements ExtensionElement {
} }
} }
public FormField replaceField(FormField field) {
String fieldVariableName = field.getVariable();
synchronized (fields) {
if (!fields.containsKey(fieldVariableName)) {
throw new IllegalArgumentException("No field with the name " + fieldVariableName + " exists");
}
return fields.put(fieldVariableName, field);
}
}
/** /**
* Check if a form field with the given variable name exists. * Check if a form field with the given variable name exists.
* *
@ -312,11 +324,16 @@ public class DataForm implements ExtensionElement {
} }
@Override @Override
public XmlStringBuilder toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) { public XmlStringBuilder toXML(XmlEnvironment xmlEnvironment) {
XmlStringBuilder buf = new XmlStringBuilder(this); XmlStringBuilder buf = new XmlStringBuilder(this);
buf.attribute("type", getType()); buf.attribute("type", getType());
buf.rightAngleBracket(); buf.rightAngleBracket();
XmlEnvironment dataFormxmlEnvironment = XmlEnvironment.builder()
.withNamespace(NAMESPACE)
.withNext(xmlEnvironment)
.build();
buf.optElement("title", getTitle()); buf.optElement("title", getTitle());
for (String instruction : getInstructions()) { for (String instruction : getInstructions()) {
buf.element("instructions", instruction); buf.element("instructions", instruction);
@ -329,10 +346,8 @@ public class DataForm implements ExtensionElement {
for (Item item : getItems()) { for (Item item : getItems()) {
buf.append(item.toXML()); buf.append(item.toXML());
} }
// Loop through all the form fields and append them to the string buffer // Add all form fields.
for (FormField field : getFields()) { buf.append(getFields(), dataFormxmlEnvironment);
buf.append(field.toXML());
}
for (Element element : extensionElements) { for (Element element : extensionElements) {
buf.append(element.toXML()); buf.append(element.toXML());
} }

View file

@ -20,21 +20,24 @@ package org.jivesoftware.smackx.xdata.provider;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import org.jivesoftware.smack.packet.XmlEnvironment; import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.parsing.SmackParsingException; import org.jivesoftware.smack.parsing.SmackParsingException;
import org.jivesoftware.smack.provider.ExtensionElementProvider; import org.jivesoftware.smack.provider.ExtensionElementProvider;
import org.jivesoftware.smack.roster.packet.RosterPacket; import org.jivesoftware.smack.roster.packet.RosterPacket;
import org.jivesoftware.smack.roster.provider.RosterPacketProvider; import org.jivesoftware.smack.roster.provider.RosterPacketProvider;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.xml.XmlPullParser; import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smack.xml.XmlPullParserException; import org.jivesoftware.smack.xml.XmlPullParserException;
import org.jivesoftware.smackx.xdata.FormField; import org.jivesoftware.smackx.xdata.FormField;
import org.jivesoftware.smackx.xdata.FormFieldChildElement;
import org.jivesoftware.smackx.xdata.packet.DataForm; import org.jivesoftware.smackx.xdata.packet.DataForm;
import org.jivesoftware.smackx.xdatalayout.packet.DataLayout; import org.jivesoftware.smackx.xdatalayout.packet.DataLayout;
import org.jivesoftware.smackx.xdatalayout.provider.DataLayoutProvider; import org.jivesoftware.smackx.xdatalayout.provider.DataLayoutProvider;
import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement;
import org.jivesoftware.smackx.xdatavalidation.provider.DataValidationProvider;
/** /**
* The DataFormProvider parses DataForm packets. * The DataFormProvider parses DataForm packets.
@ -43,6 +46,8 @@ import org.jivesoftware.smackx.xdatavalidation.provider.DataValidationProvider;
*/ */
public class DataFormProvider extends ExtensionElementProvider<DataForm> { public class DataFormProvider extends ExtensionElementProvider<DataForm> {
private static final Logger LOGGER = Logger.getLogger(DataFormProvider.class.getName());
public static final DataFormProvider INSTANCE = new DataFormProvider(); public static final DataFormProvider INSTANCE = new DataFormProvider();
@Override @Override
@ -55,6 +60,7 @@ public class DataFormProvider extends ExtensionElementProvider<DataForm> {
case START_ELEMENT: case START_ELEMENT:
String name = parser.getName(); String name = parser.getName();
String namespace = parser.getNamespace(); String namespace = parser.getNamespace();
XmlEnvironment elementXmlEnvironment = XmlEnvironment.from(parser, xmlEnvironment);
switch (name) { switch (name) {
case "instructions": case "instructions":
dataForm.addInstruction(parser.nextText()); dataForm.addInstruction(parser.nextText());
@ -63,13 +69,16 @@ public class DataFormProvider extends ExtensionElementProvider<DataForm> {
dataForm.setTitle(parser.nextText()); dataForm.setTitle(parser.nextText());
break; break;
case "field": case "field":
dataForm.addField(parseField(parser)); FormField formField = parseField(parser, elementXmlEnvironment);
dataForm.addField(formField);
break; break;
case "item": case "item":
dataForm.addItem(parseItem(parser)); DataForm.Item item = parseItem(parser, elementXmlEnvironment);
dataForm.addItem(item);
break; break;
case "reported": case "reported":
dataForm.setReportedData(parseReported(parser)); DataForm.ReportedData reported = parseReported(parser, elementXmlEnvironment);
dataForm.setReportedData(reported);
break; break;
// See XEP-133 Example 32 for a corner case where the data form contains this extension. // See XEP-133 Example 32 for a corner case where the data form contains this extension.
case RosterPacket.ELEMENT: case RosterPacket.ELEMENT:
@ -98,45 +107,35 @@ public class DataFormProvider extends ExtensionElementProvider<DataForm> {
return dataForm; return dataForm;
} }
private static FormField parseField(XmlPullParser parser) throws XmlPullParserException, IOException { private static FormField parseField(XmlPullParser parser, XmlEnvironment xmlEnvironment)
throws XmlPullParserException, IOException, SmackParsingException {
final int initialDepth = parser.getDepth(); final int initialDepth = parser.getDepth();
final String var = parser.getAttributeValue("", "var"); final String var = parser.getAttributeValue("", "var");
final FormField.Type type = FormField.Type.fromString(parser.getAttributeValue("", "type")); final FormField.Type type = FormField.Type.fromString(parser.getAttributeValue("", "type"));
final FormField formField; final FormField.Builder builder = FormField.builder();
if (type == FormField.Type.fixed) { builder.setType(type);
formField = new FormField(); if (type != FormField.Type.fixed) {
} else { builder.setVariable(var);
formField = new FormField(var); }
formField.setType(type); String label = parser.getAttributeValue("", "label");
if (StringUtils.isNotEmpty(label)) {
builder.setLabel(label);
} }
formField.setLabel(parser.getAttributeValue("", "label"));
outerloop: while (true) { outerloop: while (true) {
XmlPullParser.Event eventType = parser.next(); XmlPullParser.Event eventType = parser.next();
switch (eventType) { switch (eventType) {
case START_ELEMENT: case START_ELEMENT:
String name = parser.getName(); QName qname = parser.getQName();
String namespace = parser.getNamespace(); FormFieldChildElementProvider<?> provider = FormFieldChildElementProviderManager.getFormFieldChildElementProvider(
switch (name) { qname);
case "desc": if (provider != null) {
formField.setDescription(parser.nextText()); FormFieldChildElement formFieldChildElement = provider.parse(parser, XmlEnvironment.from(parser, xmlEnvironment));
break; builder.addFormFieldChildElement(formFieldChildElement);
case "value": } else {
formField.addValue(parser.nextText()); LOGGER.warning("Unknown form field child element " + qname + " ignored");
break;
case "required":
formField.setRequired(true);
break;
case "option":
formField.addOption(parseOption(parser));
break;
// See XEP-122 Data Forms Validation
case ValidateElement.ELEMENT:
if (namespace.equals(ValidateElement.NAMESPACE)) {
formField.setValidateElement(DataValidationProvider.parse(parser));
}
break;
} }
break; break;
case END_ELEMENT: case END_ELEMENT:
@ -149,20 +148,23 @@ public class DataFormProvider extends ExtensionElementProvider<DataForm> {
break; break;
} }
} }
return formField;
return builder.build();
} }
private static DataForm.Item parseItem(XmlPullParser parser) throws XmlPullParserException, IOException { private static DataForm.Item parseItem(XmlPullParser parser, XmlEnvironment xmlEnvironment)
throws XmlPullParserException, IOException, SmackParsingException {
final int initialDepth = parser.getDepth(); final int initialDepth = parser.getDepth();
List<FormField> fields = new ArrayList<>(); List<FormField> fields = new ArrayList<>();
outerloop: while (true) { outerloop: while (true) {
XmlPullParser.Event eventType = parser.next(); XmlPullParser.TagEvent eventType = parser.nextTag();
switch (eventType) { switch (eventType) {
case START_ELEMENT: case START_ELEMENT:
String name = parser.getName(); String name = parser.getName();
switch (name) { switch (name) {
case "field": case "field":
fields.add(parseField(parser)); FormField field = parseField(parser, XmlEnvironment.from(parser, xmlEnvironment));
fields.add(field);
break; break;
} }
break; break;
@ -171,25 +173,24 @@ public class DataFormProvider extends ExtensionElementProvider<DataForm> {
break outerloop; break outerloop;
} }
break; break;
default:
// Catch all for incomplete switch (MissingCasesInEnumSwitch) statement.
break;
} }
} }
return new DataForm.Item(fields); return new DataForm.Item(fields);
} }
private static DataForm.ReportedData parseReported(XmlPullParser parser) throws XmlPullParserException, IOException { private static DataForm.ReportedData parseReported(XmlPullParser parser, XmlEnvironment xmlEnvironment)
throws XmlPullParserException, IOException, SmackParsingException {
final int initialDepth = parser.getDepth(); final int initialDepth = parser.getDepth();
List<FormField> fields = new ArrayList<>(); List<FormField> fields = new ArrayList<>();
outerloop: while (true) { outerloop: while (true) {
XmlPullParser.Event eventType = parser.next(); XmlPullParser.TagEvent eventType = parser.nextTag();
switch (eventType) { switch (eventType) {
case START_ELEMENT: case START_ELEMENT:
String name = parser.getName(); String name = parser.getName();
switch (name) { switch (name) {
case "field": case "field":
fields.add(parseField(parser)); FormField field = parseField(parser, XmlEnvironment.from(parser, xmlEnvironment));
fields.add(field);
break; break;
} }
break; break;
@ -198,39 +199,9 @@ public class DataFormProvider extends ExtensionElementProvider<DataForm> {
break outerloop; break outerloop;
} }
break; break;
default:
// Catch all for incomplete switch (MissingCasesInEnumSwitch) statement.
break;
} }
} }
return new DataForm.ReportedData(fields); return new DataForm.ReportedData(fields);
} }
private static FormField.Option parseOption(XmlPullParser parser) throws XmlPullParserException, IOException {
final int initialDepth = parser.getDepth();
FormField.Option option = null;
String label = parser.getAttributeValue("", "label");
outerloop: while (true) {
XmlPullParser.Event eventType = parser.next();
switch (eventType) {
case START_ELEMENT:
String name = parser.getName();
switch (name) {
case "value":
option = new FormField.Option(label, parser.nextText());
break;
}
break;
case END_ELEMENT:
if (parser.getDepth() == initialDepth) {
break outerloop;
}
break;
default:
// Catch all for incomplete switch (MissingCasesInEnumSwitch) statement.
break;
}
}
return option;
}
} }

View file

@ -0,0 +1,43 @@
/**
*
* Copyright 2019 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.smackx.xdata.provider;
import java.io.IOException;
import javax.xml.namespace.QName;
import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smack.xml.XmlPullParserException;
import org.jivesoftware.smackx.xdata.FormField;
public class DescriptionProvider extends FormFieldChildElementProvider<FormField.Description> {
@Override
public FormField.Description parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment)
throws XmlPullParserException, IOException {
String description = parser.nextText();
return new FormField.Description(description);
}
@Override
public QName getQName() {
return FormField.Description.QNAME;
}
}

View file

@ -0,0 +1,29 @@
/**
*
* Copyright 2019 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.smackx.xdata.provider;
import javax.xml.namespace.QName;
import org.jivesoftware.smack.provider.Provider;
import org.jivesoftware.smackx.xdata.FormFieldChildElement;
public abstract class FormFieldChildElementProvider<F extends FormFieldChildElement> extends Provider<F> {
public abstract QName getQName();
}

View file

@ -0,0 +1,45 @@
/**
*
* Copyright 2019 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.smackx.xdata.provider;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.xml.namespace.QName;
public class FormFieldChildElementProviderManager {
private static final Map<QName, FormFieldChildElementProvider<?>> providers = new ConcurrentHashMap<>();
public static void addFormFieldChildElementProvider(
FormFieldChildElementProvider<?>... formFieldChildElementProviders) {
for (FormFieldChildElementProvider<?> formFieldChildElementProvider : formFieldChildElementProviders) {
QName qname = formFieldChildElementProvider.getQName();
providers.put(qname, formFieldChildElementProvider);
}
}
public static FormFieldChildElementProvider<?> addFormFieldChildElementProvider(QName qname,
FormFieldChildElementProvider<?> formFieldChildElementProvider) {
return providers.put(qname, formFieldChildElementProvider);
}
public static FormFieldChildElementProvider<?> getFormFieldChildElementProvider(QName qname) {
return providers.get(qname);
}
}

View file

@ -0,0 +1,63 @@
/**
*
* Copyright 2019 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.smackx.xdata.provider;
import java.io.IOException;
import javax.xml.namespace.QName;
import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.parsing.SmackParsingException;
import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smack.xml.XmlPullParserException;
import org.jivesoftware.smackx.xdata.FormField;
public class OptionProvider extends FormFieldChildElementProvider<FormField.Option> {
@Override
public FormField.Option parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment)
throws XmlPullParserException, IOException, SmackParsingException {
FormField.Option option = null;
String label = parser.getAttributeValue("", "label");
outerloop: while (true) {
XmlPullParser.TagEvent eventType = parser.nextTag();
switch (eventType) {
case START_ELEMENT:
String name = parser.getName();
switch (name) {
case "value":
option = new FormField.Option(label, parser.nextText());
break;
}
break;
case END_ELEMENT:
if (parser.getDepth() == initialDepth) {
break outerloop;
}
break;
}
}
return option;
}
@Override
public QName getQName() {
return FormField.Option.QNAME;
}
}

View file

@ -0,0 +1,43 @@
/**
*
* Copyright 2019 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.smackx.xdata.provider;
import java.io.IOException;
import javax.xml.namespace.QName;
import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.parsing.SmackParsingException;
import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smack.xml.XmlPullParserException;
import org.jivesoftware.smackx.xdata.FormField;
public class RequiredProvider extends FormFieldChildElementProvider<FormField.Required> {
@Override
public FormField.Required parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment)
throws XmlPullParserException, IOException, SmackParsingException {
return FormField.Required.INSTANCE;
}
@Override
public QName getQName() {
return FormField.Required.QNAME;
}
}

View file

@ -0,0 +1,43 @@
/**
*
* Copyright 2019 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.smackx.xdata.provider;
import java.io.IOException;
import javax.xml.namespace.QName;
import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smack.xml.XmlPullParserException;
import org.jivesoftware.smackx.xdata.FormField;
public class ValueProvider extends FormFieldChildElementProvider<FormField.Value> {
@Override
public FormField.Value parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment)
throws XmlPullParserException, IOException {
String value = parser.nextText();
return new FormField.Value(value);
}
@Override
public QName getQName() {
return FormField.Value.QNAME;
}
}

View file

@ -21,11 +21,15 @@ import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPConnectionRegistry; import org.jivesoftware.smack.XMPPConnectionRegistry;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.xdata.provider.FormFieldChildElementProviderManager;
import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement; import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement;
import org.jivesoftware.smackx.xdatavalidation.provider.DataValidationProvider;
public class XDataValidationManager { public class XDataValidationManager {
static { static {
FormFieldChildElementProviderManager.addFormFieldChildElementProvider(new DataValidationProvider());
XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
@Override @Override
public void connectionCreated(XMPPConnection connection) { public void connectionCreated(XMPPConnection connection) {

View file

@ -16,13 +16,15 @@
*/ */
package org.jivesoftware.smackx.xdatavalidation.packet; package org.jivesoftware.smackx.xdatavalidation.packet;
import org.jivesoftware.smack.packet.ExtensionElement; import javax.xml.namespace.QName;
import org.jivesoftware.smack.packet.NamedElement; import org.jivesoftware.smack.packet.NamedElement;
import org.jivesoftware.smack.util.NumberUtil; import org.jivesoftware.smack.util.NumberUtil;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.XmlStringBuilder; import org.jivesoftware.smack.util.XmlStringBuilder;
import org.jivesoftware.smackx.xdata.FormField; import org.jivesoftware.smackx.xdata.FormField;
import org.jivesoftware.smackx.xdata.FormFieldChildElement;
import org.jivesoftware.smackx.xdata.packet.DataForm; import org.jivesoftware.smackx.xdata.packet.DataForm;
import org.jivesoftware.smackx.xdatavalidation.ValidationConsistencyException; import org.jivesoftware.smackx.xdatavalidation.ValidationConsistencyException;
@ -34,12 +36,14 @@ import org.jivesoftware.smackx.xdatavalidation.ValidationConsistencyException;
* *
* @author Anno van Vliet * @author Anno van Vliet
*/ */
public abstract class ValidateElement implements ExtensionElement { public abstract class ValidateElement implements FormFieldChildElement {
public static final String DATATYPE_XS_STRING = "xs:string"; public static final String DATATYPE_XS_STRING = "xs:string";
public static final String ELEMENT = "validate"; public static final String ELEMENT = "validate";
public static final String NAMESPACE = "http://jabber.org/protocol/xdata-validate"; public static final String NAMESPACE = "http://jabber.org/protocol/xdata-validate";
public static final QName QNAME = new QName(NAMESPACE, ELEMENT);
private final String datatype; private final String datatype;
private ListRange listRange; private ListRange listRange;
@ -82,9 +86,19 @@ public abstract class ValidateElement implements ExtensionElement {
return NAMESPACE; return NAMESPACE;
} }
@Override
public QName getQName() {
return QNAME;
}
@Override
public final boolean mustBeOnlyOfHisKind() {
return true;
}
@Override @Override
public XmlStringBuilder toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) { public XmlStringBuilder toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) {
XmlStringBuilder buf = new XmlStringBuilder(this); XmlStringBuilder buf = new XmlStringBuilder(this, enclosingNamespace);
buf.optAttribute("datatype", datatype); buf.optAttribute("datatype", datatype);
buf.rightAngleBracket(); buf.rightAngleBracket();
appendXML(buf); appendXML(buf);
@ -115,11 +129,16 @@ public abstract class ValidateElement implements ExtensionElement {
} }
/** /**
* Check if this element is consistent according to the business rules in XEP=0122. * Check if this element is consistent according to the business rules in XEP-0122.
* *
* @param formField * @param formFieldBuilder the builder used to construct the form field.
*/ */
public abstract void checkConsistency(FormField formField); @Override
public abstract void checkConsistency(FormField.Builder formFieldBuilder);
public static ValidateElement from(FormField formField) {
return (ValidateElement) formField.getFormFieldChildElement(QNAME);
}
/** /**
* Validation only against the datatype itself. Indicates that the value(s) should simply match the field type and * Validation only against the datatype itself. Indicates that the value(s) should simply match the field type and
@ -146,7 +165,7 @@ public abstract class ValidateElement implements ExtensionElement {
} }
@Override @Override
public void checkConsistency(FormField formField) { public void checkConsistency(FormField.Builder formField) {
checkListRangeConsistency(formField); checkListRangeConsistency(formField);
if (formField.getType() != null) { if (formField.getType() != null) {
switch (formField.getType()) { switch (formField.getType()) {
@ -189,7 +208,7 @@ public abstract class ValidateElement implements ExtensionElement {
} }
@Override @Override
public void checkConsistency(FormField formField) { public void checkConsistency(FormField.Builder formField) {
checkListRangeConsistency(formField); checkListRangeConsistency(formField);
if (formField.getType() != null) { if (formField.getType() != null) {
switch (formField.getType()) { switch (formField.getType()) {
@ -257,7 +276,7 @@ public abstract class ValidateElement implements ExtensionElement {
} }
@Override @Override
public void checkConsistency(FormField formField) { public void checkConsistency(FormField.Builder formField) {
checkNonMultiConsistency(formField, METHOD); checkNonMultiConsistency(formField, METHOD);
if (getDatatype().equals(ValidateElement.DATATYPE_XS_STRING)) { if (getDatatype().equals(ValidateElement.DATATYPE_XS_STRING)) {
throw new ValidationConsistencyException(String.format( throw new ValidationConsistencyException(String.format(
@ -307,7 +326,7 @@ public abstract class ValidateElement implements ExtensionElement {
} }
@Override @Override
public void checkConsistency(FormField formField) { public void checkConsistency(FormField.Builder formField) {
checkNonMultiConsistency(formField, METHOD); checkNonMultiConsistency(formField, METHOD);
} }
@ -385,7 +404,7 @@ public abstract class ValidateElement implements ExtensionElement {
* *
* @param formField * @param formField
*/ */
protected void checkListRangeConsistency(FormField formField) { protected void checkListRangeConsistency(FormField.Builder formField) {
ListRange listRange = getListRange(); ListRange listRange = getListRange();
if (listRange == null) { if (listRange == null) {
return; return;
@ -403,7 +422,7 @@ public abstract class ValidateElement implements ExtensionElement {
* @param formField * @param formField
* @param method * @param method
*/ */
protected void checkNonMultiConsistency(FormField formField, String method) { protected void checkNonMultiConsistency(FormField.Builder formField, String method) {
checkListRangeConsistency(formField); checkListRangeConsistency(formField);
if (formField.getType() != null) { if (formField.getType() != null) {
switch (formField.getType()) { switch (formField.getType()) {

View file

@ -19,10 +19,14 @@ package org.jivesoftware.smackx.xdatavalidation.provider;
import java.io.IOException; import java.io.IOException;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.xml.namespace.QName;
import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.util.ParserUtils; import org.jivesoftware.smack.util.ParserUtils;
import org.jivesoftware.smack.xml.XmlPullParser; import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smack.xml.XmlPullParserException; import org.jivesoftware.smack.xml.XmlPullParserException;
import org.jivesoftware.smackx.xdata.provider.FormFieldChildElementProvider;
import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement; import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement;
import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.BasicValidateElement; import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.BasicValidateElement;
import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.ListRange; import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.ListRange;
@ -36,11 +40,12 @@ import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.RegexValid
* @author Anno van Vliet * @author Anno van Vliet
* *
*/ */
public class DataValidationProvider { public class DataValidationProvider extends FormFieldChildElementProvider<ValidateElement> {
private static final Logger LOGGER = Logger.getLogger(DataValidationProvider.class.getName()); private static final Logger LOGGER = Logger.getLogger(DataValidationProvider.class.getName());
public static ValidateElement parse(XmlPullParser parser) throws XmlPullParserException, IOException { @Override
final int initialDepth = parser.getDepth(); public ValidateElement parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment)
throws XmlPullParserException, IOException {
final String dataType = parser.getAttributeValue("", "datatype"); final String dataType = parser.getAttributeValue("", "datatype");
ValidateElement dataValidation = null; ValidateElement dataValidation = null;
ListRange listRange = null; ListRange listRange = null;
@ -98,4 +103,9 @@ public class DataValidationProvider {
return dataValidation; return dataValidation;
} }
@Override
public QName getQName() {
return ValidateElement.QNAME;
}
} }

View file

@ -117,31 +117,31 @@ public class EntityCapsManagerTest extends InitExtensions {
DataForm df = new DataForm(DataForm.Type.result); DataForm df = new DataForm(DataForm.Type.result);
FormField ff = new FormField("os"); FormField.Builder ff = FormField.builder("os");
ff.addValue("Mac"); ff.addValue("Mac");
df.addField(ff); df.addField(ff.build());
ff = new FormField("FORM_TYPE"); ff = FormField.builder("FORM_TYPE");
ff.setType(FormField.Type.hidden); ff.setType(FormField.Type.hidden);
ff.addValue("urn:xmpp:dataforms:softwareinfo"); ff.addValue("urn:xmpp:dataforms:softwareinfo");
df.addField(ff); df.addField(ff.build());
ff = new FormField("ip_version"); ff = FormField.builder("ip_version");
ff.addValue("ipv4"); ff.addValue("ipv4");
ff.addValue("ipv6"); ff.addValue("ipv6");
df.addField(ff); df.addField(ff.build());
ff = new FormField("os_version"); ff = FormField.builder("os_version");
ff.addValue("10.5.1"); ff.addValue("10.5.1");
df.addField(ff); df.addField(ff.build());
ff = new FormField("software"); ff = FormField.builder("software");
ff.addValue("Psi"); ff.addValue("Psi");
df.addField(ff); df.addField(ff.build());
ff = new FormField("software_version"); ff = FormField.builder("software_version");
ff.addValue("0.11"); ff.addValue("0.11");
df.addField(ff); df.addField(ff.build());
di.addExtension(df); di.addExtension(df);
return di; return di;
@ -174,31 +174,31 @@ public class EntityCapsManagerTest extends InitExtensions {
DataForm df = new DataForm(DataForm.Type.result); DataForm df = new DataForm(DataForm.Type.result);
FormField ff = new FormField("os"); FormField.Builder ff = FormField.builder("os");
ff.addValue("Mac"); ff.addValue("Mac");
df.addField(ff); df.addField(ff.build());
ff = new FormField("FORM_TYPE"); ff = FormField.builder("FORM_TYPE");
ff.setType(FormField.Type.hidden); ff.setType(FormField.Type.hidden);
ff.addValue("urn:xmpp:dataforms:softwareinfo"); ff.addValue("urn:xmpp:dataforms:softwareinfo");
df.addField(ff); df.addField(ff.build());
ff = new FormField("ip_version"); ff = FormField.builder("ip_version");
ff.addValue("ipv4"); ff.addValue("ipv4");
ff.addValue("ipv6"); ff.addValue("ipv6");
df.addField(ff); df.addField(ff.build());
ff = new FormField("os_version"); ff = FormField.builder("os_version");
ff.addValue("10.5.1"); ff.addValue("10.5.1");
df.addField(ff); df.addField(ff.build());
ff = new FormField("software"); ff = FormField.builder("software");
ff.addValue("Psi"); ff.addValue("Psi");
df.addField(ff); df.addField(ff.build());
ff = new FormField("software_version"); ff = FormField.builder("software_version");
ff.addValue("0.11"); ff.addValue("0.11");
df.addField(ff); df.addField(ff.build());
di.addExtension(df); di.addExtension(df);
@ -206,14 +206,14 @@ public class EntityCapsManagerTest extends InitExtensions {
// FORM_TYPE // FORM_TYPE
df = new DataForm(DataForm.Type.result); df = new DataForm(DataForm.Type.result);
ff = new FormField("FORM_TYPE"); ff = FormField.builder("FORM_TYPE");
ff.setType(FormField.Type.hidden); ff.setType(FormField.Type.hidden);
ff.addValue("urn:xmpp:dataforms:softwareinfo"); ff.addValue("urn:xmpp:dataforms:softwareinfo");
df.addField(ff); df.addField(ff.build());
ff = new FormField("software"); ff = FormField.builder("software");
ff.addValue("smack"); ff.addValue("smack");
df.addField(ff); df.addField(ff.build());
di.addExtension(df); di.addExtension(df);

View file

@ -42,17 +42,17 @@ public class RoomInfoTest {
public void validateRoomWithForm() { public void validateRoomWithForm() {
DataForm dataForm = new DataForm(DataForm.Type.result); DataForm dataForm = new DataForm(DataForm.Type.result);
FormField desc = new FormField("muc#roominfo_description"); FormField.Builder desc = FormField.builder("muc#roominfo_description");
desc.addValue("The place for all good witches!"); desc.addValue("The place for all good witches!");
dataForm.addField(desc); dataForm.addField(desc.build());
FormField subject = new FormField("muc#roominfo_subject"); FormField.Builder subject = FormField.builder("muc#roominfo_subject");
subject.addValue("Spells"); subject.addValue("Spells");
dataForm.addField(subject); dataForm.addField(subject.build());
FormField occupants = new FormField("muc#roominfo_occupants"); FormField.Builder occupants = FormField.builder("muc#roominfo_occupants");
occupants.addValue("3"); occupants.addValue("3");
dataForm.addField(occupants); dataForm.addField(occupants.build());
DiscoverInfo discoInfo = new DiscoverInfo(); DiscoverInfo discoInfo = new DiscoverInfo();
discoInfo.addExtension(dataForm); discoInfo.addExtension(dataForm);

View file

@ -20,6 +20,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import org.jivesoftware.smack.packet.Element; import org.jivesoftware.smack.packet.Element;
import org.jivesoftware.smack.test.util.SmackTestSuite;
import org.jivesoftware.smack.util.PacketParserUtils; import org.jivesoftware.smack.util.PacketParserUtils;
import org.jivesoftware.smack.xml.XmlPullParser; import org.jivesoftware.smack.xml.XmlPullParser;
@ -41,9 +42,9 @@ import org.junit.Test;
* @author Anno van Vliet * @author Anno van Vliet
* *
*/ */
public class DataFormTest { public class DataFormTest extends SmackTestSuite {
private static final String TEST_OUTPUT_1 = "<x xmlns='jabber:x:data' type='submit'><instructions>InstructionTest1</instructions><field var='testField1'></field></x>"; private static final String TEST_OUTPUT_1 = "<x xmlns='jabber:x:data' type='submit'><instructions>InstructionTest1</instructions><field var='testField1'/></x>";
private static final String TEST_OUTPUT_2 = "<x xmlns='jabber:x:data' type='submit'><instructions>InstructionTest1</instructions><field var='testField1'></field><page xmlns='http://jabber.org/protocol/xdata-layout' label='Label'><fieldref var='testField1'/><section label='section Label'><text>SectionText</text></section><text>PageText</text></page></x>"; private static final String TEST_OUTPUT_2 = "<x xmlns='jabber:x:data' type='submit'><instructions>InstructionTest1</instructions><field var='testField1'/><page xmlns='http://jabber.org/protocol/xdata-layout' label='Label'><fieldref var='testField1'/><section label='section Label'><text>SectionText</text></section><text>PageText</text></page></x>";
private static final String TEST_OUTPUT_3 = "<x xmlns='jabber:x:data' type='submit'><instructions>InstructionTest1</instructions><field var='testField1'><validate xmlns='http://jabber.org/protocol/xdata-validate' datatype='xs:integer'><range min='1111' max='9999'/></validate></field></x>"; private static final String TEST_OUTPUT_3 = "<x xmlns='jabber:x:data' type='submit'><instructions>InstructionTest1</instructions><field var='testField1'><validate xmlns='http://jabber.org/protocol/xdata-validate' datatype='xs:integer'><range min='1111' max='9999'/></validate></field></x>";
private static final DataFormProvider pr = new DataFormProvider(); private static final DataFormProvider pr = new DataFormProvider();
@ -54,7 +55,7 @@ public class DataFormTest {
DataForm df = new DataForm(DataForm.Type.submit); DataForm df = new DataForm(DataForm.Type.submit);
String instruction = "InstructionTest1"; String instruction = "InstructionTest1";
df.addInstruction(instruction); df.addInstruction(instruction);
FormField field = new FormField("testField1"); FormField field = FormField.builder("testField1").build();
df.addField(field); df.addField(field);
assertNotNull(df.toXML()); assertNotNull(df.toXML());
@ -81,7 +82,7 @@ public class DataFormTest {
DataForm df = new DataForm(DataForm.Type.submit); DataForm df = new DataForm(DataForm.Type.submit);
String instruction = "InstructionTest1"; String instruction = "InstructionTest1";
df.addInstruction(instruction); df.addInstruction(instruction);
FormField field = new FormField("testField1"); FormField field = FormField.builder("testField1").build();
df.addField(field); df.addField(field);
DataLayout layout = new DataLayout("Label"); DataLayout layout = new DataLayout("Label");
@ -123,11 +124,12 @@ public class DataFormTest {
DataForm df = new DataForm(DataForm.Type.submit); DataForm df = new DataForm(DataForm.Type.submit);
String instruction = "InstructionTest1"; String instruction = "InstructionTest1";
df.addInstruction(instruction); df.addInstruction(instruction);
FormField field = new FormField("testField1"); FormField.Builder fieldBuilder = FormField.builder("testField1");
df.addField(field);
ValidateElement dv = new RangeValidateElement("xs:integer", "1111", "9999"); ValidateElement dv = new RangeValidateElement("xs:integer", "1111", "9999");
field.setValidateElement(dv); fieldBuilder.addFormFieldChildElement(dv);
df.addField(fieldBuilder.build());
assertNotNull(df.toXML()); assertNotNull(df.toXML());
String output = df.toXML().toString(); String output = df.toXML().toString();
@ -140,7 +142,7 @@ public class DataFormTest {
assertNotNull(df); assertNotNull(df);
assertNotNull(df.getFields()); assertNotNull(df.getFields());
assertEquals(1 , df.getFields().size()); assertEquals(1 , df.getFields().size());
Element element = df.getFields().get(0).getValidateElement(); Element element = ValidateElement.from(df.getFields().get(0));
assertNotNull(element); assertNotNull(element);
dv = (ValidateElement) element; dv = (ValidateElement) element;

View file

@ -17,7 +17,7 @@
package org.jivesoftware.smackx.xdatavalidation; package org.jivesoftware.smackx.xdatavalidation;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertThrows;
import org.jivesoftware.smackx.xdata.FormField; import org.jivesoftware.smackx.xdata.FormField;
import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.BasicValidateElement; import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.BasicValidateElement;
@ -26,7 +26,7 @@ import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.OpenValida
import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.RangeValidateElement; import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.RangeValidateElement;
import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.RegexValidateElement; import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.RegexValidateElement;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Data validation helper test. * Data validation helper test.
@ -35,81 +35,55 @@ import org.junit.Test;
*/ */
public class DataValidationHelperTest { public class DataValidationHelperTest {
@Test @Test
public void testCheckConsistencyFormFieldBasicValidateElement() { public void testCheckConsistencyFormFieldBasicValidateElement() {
FormField field = new FormField("var"); FormField.Builder field = FormField.builder("var")
field.setType(FormField.Type.jid_single); .setType(FormField.Type.jid_single);
BasicValidateElement element = new BasicValidateElement(null); BasicValidateElement element = new BasicValidateElement(null);
try { ValidationConsistencyException vce = assertThrows(ValidationConsistencyException.class,
element.checkConsistency(field); () -> element.checkConsistency(field));
fail("No correct check on consistency"); assertEquals("Field type 'jid-single' is not consistent with validation method 'basic'.", vce.getMessage());
}
catch (ValidationConsistencyException e) {
assertEquals("Field type 'jid-single' is not consistent with validation method 'basic'.", e.getMessage());
}
try { IllegalArgumentException iae = assertThrows(IllegalArgumentException.class,
new ListRange(-1L, 1L); () -> new ListRange(-1L, 1L));
fail("No correct check on consistency"); assertEquals("unsigned 32-bit integers can't be negative", iae.getMessage());
}
catch (IllegalArgumentException e) {
assertEquals("unsigned 32-bit integers can't be negative", e.getMessage());
}
element.setListRange(new ListRange(10L, 100L)); element.setListRange(new ListRange(10L, 100L));
try { vce = assertThrows(ValidationConsistencyException.class, () -> element.checkConsistency(field));
element.checkConsistency(field); assertEquals("Field type is not of type 'list-multi' while a 'list-range' is defined.", vce.getMessage());
fail("No correct check on consistency");
}
catch (ValidationConsistencyException e) {
assertEquals("Field type is not of type 'list-multi' while a 'list-range' is defined.", e.getMessage());
}
field.setType(FormField.Type.list_multi); FormField.Builder fieldListMulti = field.setType(FormField.Type.list_multi);
element.checkConsistency(field); element.checkConsistency(fieldListMulti);
} }
@Test @Test
public void testCheckConsistencyFormFieldOpenValidateElement() { public void testCheckConsistencyFormFieldOpenValidateElement() {
FormField field = new FormField("var"); FormField.Builder field = FormField.builder("var")
field.setType(FormField.Type.hidden); .setType(FormField.Type.hidden);
OpenValidateElement element = new OpenValidateElement(null); OpenValidateElement element = new OpenValidateElement(null);
try { ValidationConsistencyException e = assertThrows(ValidationConsistencyException.class,
element.checkConsistency(field); () -> element.checkConsistency(field));
fail("No correct check on consistency");
}
catch (ValidationConsistencyException e) {
assertEquals("Field type 'hidden' is not consistent with validation method 'open'.", e.getMessage()); assertEquals("Field type 'hidden' is not consistent with validation method 'open'.", e.getMessage());
} }
}
@Test @Test
public void testCheckConsistencyFormFieldRangeValidateElement() { public void testCheckConsistencyFormFieldRangeValidateElement() {
FormField field = new FormField("var"); FormField.Builder field = FormField.builder("var")
field.setType(FormField.Type.text_multi); .setType(FormField.Type.text_multi);
RangeValidateElement element = new RangeValidateElement("xs:integer", null, "99"); RangeValidateElement element = new RangeValidateElement("xs:integer", null, "99");
try { ValidationConsistencyException e = assertThrows(ValidationConsistencyException.class,
element.checkConsistency(field); () -> element.checkConsistency(field));
fail("No correct check on consistency");
}
catch (ValidationConsistencyException e) {
assertEquals("Field type 'text-multi' is not consistent with validation method 'range'.", e.getMessage()); assertEquals("Field type 'text-multi' is not consistent with validation method 'range'.", e.getMessage());
} }
}
@Test @Test
public void testCheckConsistencyFormFieldRegexValidateElement() { public void testCheckConsistencyFormFieldRegexValidateElement() {
FormField field = new FormField("var"); FormField.Builder field = FormField.builder("var")
field.setType(FormField.Type.list_multi); .setType(FormField.Type.list_multi);
RegexValidateElement element = new RegexValidateElement(null, ".*"); RegexValidateElement element = new RegexValidateElement(null, ".*");
try { ValidationConsistencyException e = assertThrows(ValidationConsistencyException.class,
element.checkConsistency(field); () -> element.checkConsistency(field));
fail("No correct check on consistency");
}
catch (ValidationConsistencyException e) {
assertEquals("Field type 'list-multi' is not consistent with validation method 'regex'.", e.getMessage()); assertEquals("Field type 'list-multi' is not consistent with validation method 'regex'.", e.getMessage());
} }
} }
}

View file

@ -19,12 +19,13 @@ package org.jivesoftware.smackx.xdatavalidation.provider;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException; import java.io.IOException;
import org.jivesoftware.smack.parsing.SmackParsingException;
import org.jivesoftware.smack.test.util.SmackTestSuite;
import org.jivesoftware.smack.test.util.SmackTestUtil; import org.jivesoftware.smack.test.util.SmackTestUtil;
import org.jivesoftware.smack.test.util.TestUtils;
import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smack.xml.XmlPullParserException; import org.jivesoftware.smack.xml.XmlPullParserException;
import org.jivesoftware.smackx.xdata.FormField; import org.jivesoftware.smackx.xdata.FormField;
@ -35,7 +36,7 @@ import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.BasicValid
import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.ListRange; import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.ListRange;
import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.RangeValidateElement; import org.jivesoftware.smackx.xdatavalidation.packet.ValidateElement.RangeValidateElement;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.EnumSource;
@ -44,7 +45,7 @@ import org.junit.jupiter.params.provider.EnumSource;
* @author Anno van Vliet * @author Anno van Vliet
* *
*/ */
public class DataValidationTest { public class DataValidationTest extends SmackTestSuite {
private static final String TEST_INPUT_MIN = "<validate xmlns='http://jabber.org/protocol/xdata-validate'></validate>"; private static final String TEST_INPUT_MIN = "<validate xmlns='http://jabber.org/protocol/xdata-validate'></validate>";
private static final String TEST_OUTPUT_MIN = "<validate xmlns='http://jabber.org/protocol/xdata-validate'><basic/></validate>"; private static final String TEST_OUTPUT_MIN = "<validate xmlns='http://jabber.org/protocol/xdata-validate'><basic/></validate>";
private static final String TEST_OUTPUT_RANGE = "<validate xmlns='http://jabber.org/protocol/xdata-validate' datatype='xs:string'><range min='min-val' max='max-val'/><list-range min='111' max='999'/></validate>"; private static final String TEST_OUTPUT_RANGE = "<validate xmlns='http://jabber.org/protocol/xdata-validate' datatype='xs:string'><range min='min-val' max='max-val'/><list-range min='111' max='999'/></validate>";
@ -52,42 +53,50 @@ public class DataValidationTest {
private static final String TEST_OUTPUT_FAIL = "<validate xmlns='http://jabber.org/protocol/xdata-validate'><list-range min='1-1-1' max='999'/></validate>"; private static final String TEST_OUTPUT_FAIL = "<validate xmlns='http://jabber.org/protocol/xdata-validate'><list-range min='1-1-1' max='999'/></validate>";
@Test @Test
public void testMin() throws XmlPullParserException, IOException { public void testBasic() {
ValidateElement dv = new BasicValidateElement(null); ValidateElement dv = new BasicValidateElement(null);
assertNotNull(dv.toXML()); assertNotNull(dv.toXML());
String output = dv.toXML().toString(); String output = dv.toXML().toString();
assertEquals(TEST_OUTPUT_MIN, output); assertEquals(TEST_OUTPUT_MIN, output);
}
XmlPullParser parser = getParser(TEST_INPUT_MIN); @ParameterizedTest
@EnumSource(SmackTestUtil.XmlPullParserKind.class)
dv = DataValidationProvider.parse(parser); public void testMin(SmackTestUtil.XmlPullParserKind parserKind) throws XmlPullParserException, IOException, SmackParsingException {
ValidateElement dv = SmackTestUtil.parse(TEST_INPUT_MIN, DataValidationProvider.class, parserKind);
assertNotNull(dv); assertNotNull(dv);
assertEquals("xs:string", dv.getDatatype()); assertEquals("xs:string", dv.getDatatype());
assertTrue(dv instanceof BasicValidateElement); assertTrue(dv instanceof BasicValidateElement);
assertNotNull(dv.toXML()); assertNotNull(dv.toXML());
output = dv.toXML().toString(); String output = dv.toXML().toString();
assertEquals(TEST_OUTPUT_MIN, output); assertEquals(TEST_OUTPUT_MIN, output);
} }
@Test @Test
public void testRange() throws XmlPullParserException, IOException { public void testRangeToXml() {
ValidateElement dv = new RangeValidateElement("xs:string", "min-val", "max-val"); ValidateElement dv = new RangeValidateElement("xs:string", "min-val", "max-val");
ListRange listRange = new ListRange(111L, 999L); ListRange listRange = new ListRange(111L, 999L);
dv.setListRange(listRange); dv.setListRange(listRange);
assertNotNull(dv.toXML()); assertNotNull(dv.toXML());
String output = dv.toXML().toString(); String output = dv.toXML().toString();
assertEquals(TEST_OUTPUT_RANGE, output); assertEquals(TEST_OUTPUT_RANGE, output);
}
XmlPullParser parser = getParser(output); @ParameterizedTest
@EnumSource(SmackTestUtil.XmlPullParserKind.class)
public void testRange(SmackTestUtil.XmlPullParserKind parserKind)
throws XmlPullParserException, IOException, SmackParsingException {
ValidateElement dv = new RangeValidateElement("xs:string", "min-val", "max-val");
ListRange listRange = new ListRange(111L, 999L);
dv.setListRange(listRange);
dv = DataValidationProvider.parse(parser); String xml = dv.toXML().toString();
dv = SmackTestUtil.parse(xml, DataValidationProvider.class, parserKind);
assertNotNull(dv); assertNotNull(dv);
assertEquals("xs:string", dv.getDatatype()); assertEquals("xs:string", dv.getDatatype());
@ -99,24 +108,27 @@ public class DataValidationTest {
assertEquals(Long.valueOf(111), rdv.getListRange().getMin()); assertEquals(Long.valueOf(111), rdv.getListRange().getMin());
assertEquals(999, rdv.getListRange().getMax().intValue()); assertEquals(999, rdv.getListRange().getMax().intValue());
assertNotNull(dv.toXML()); assertNotNull(dv.toXML());
output = dv.toXML().toString(); xml = dv.toXML().toString();
assertEquals(TEST_OUTPUT_RANGE, output); assertEquals(TEST_OUTPUT_RANGE, xml);
} }
@Test @Test
public void testRange2() throws XmlPullParserException, IOException { public void testRange2ToXml() {
ValidateElement dv = new RangeValidateElement(null, null, null); ValidateElement dv = new RangeValidateElement(null, null, null);
assertNotNull(dv.toXML()); assertNotNull(dv.toXML());
String output = dv.toXML().toString(); String output = dv.toXML().toString();
assertEquals(TEST_OUTPUT_RANGE2, output); assertEquals(TEST_OUTPUT_RANGE2, output);
}
XmlPullParser parser = getParser(output); @ParameterizedTest
@EnumSource(SmackTestUtil.XmlPullParserKind.class)
public void testRange2(SmackTestUtil.XmlPullParserKind parserKind) throws XmlPullParserException, IOException, SmackParsingException {
ValidateElement dv = new RangeValidateElement(null, null, null);
String xml = dv.toXML().toString();
dv = DataValidationProvider.parse(parser); dv = SmackTestUtil.parse(xml, DataValidationProvider.class, parserKind);
assertNotNull(dv); assertNotNull(dv);
assertEquals("xs:string", dv.getDatatype()); assertEquals("xs:string", dv.getDatatype());
@ -126,14 +138,15 @@ public class DataValidationTest {
assertEquals(null, rdv.getMax()); assertEquals(null, rdv.getMax());
assertNotNull(rdv.toXML()); assertNotNull(rdv.toXML());
output = rdv.toXML().toString(); xml = rdv.toXML().toString();
assertEquals(TEST_OUTPUT_RANGE2, output); assertEquals(TEST_OUTPUT_RANGE2, xml);
} }
@Test(expected = NumberFormatException.class) @ParameterizedTest
public void testRangeFailure() throws IOException, XmlPullParserException { @EnumSource(SmackTestUtil.XmlPullParserKind.class)
XmlPullParser parser = getParser(TEST_OUTPUT_FAIL); public void testRangeFailure(SmackTestUtil.XmlPullParserKind parserKind) throws IOException, XmlPullParserException {
DataValidationProvider.parse(parser); assertThrows(NumberFormatException.class,
() -> SmackTestUtil.parse(TEST_OUTPUT_FAIL, DataValidationProvider.class, parserKind));
} }
@ParameterizedTest @ParameterizedTest
@ -168,18 +181,8 @@ public class DataValidationTest {
assertEquals("Event Name", nameField.getLabel()); assertEquals("Event Name", nameField.getLabel());
FormField dataStartField = dataForm.getField("date/start"); FormField dataStartField = dataForm.getField("date/start");
ValidateElement dataStartValidateElement = dataStartField.getValidateElement(); ValidateElement dataStartValidateElement = ValidateElement.from(dataStartField);
assertEquals("xs:date", dataStartValidateElement.getDatatype()); assertEquals("xs:date", dataStartValidateElement.getDatatype());
assertTrue(dataStartValidateElement instanceof BasicValidateElement); assertTrue(dataStartValidateElement instanceof BasicValidateElement);
} }
/**
* @param output
* @return
* @throws XmlPullParserException
* @throws IOException
*/
private static XmlPullParser getParser(String output) throws XmlPullParserException, IOException {
return TestUtils.getParser(output, "validate");
}
} }

View file

@ -25,7 +25,7 @@ import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.StanzaCollector; import org.jivesoftware.smack.StanzaCollector;
import org.jivesoftware.smack.filter.ThreadFilter; import org.jivesoftware.smack.filter.ThreadFilter;
import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.xdata.FormField.Type;
import org.jivesoftware.smackx.xdata.packet.DataForm; import org.jivesoftware.smackx.xdata.packet.DataForm;
import org.igniterealtime.smack.inttest.AbstractSmackIntegrationTest; import org.igniterealtime.smack.inttest.AbstractSmackIntegrationTest;
@ -59,34 +59,35 @@ public class FormTest extends AbstractSmackIntegrationTest {
"Fill out this form to report your case.\nThe case will be created automatically."); "Fill out this form to report your case.\nThe case will be created automatically.");
formToSend.setTitle("Case configurations"); formToSend.setTitle("Case configurations");
// Add a hidden variable // Add a hidden variable
FormField field = new FormField("hidden_var"); FormField.Builder field = FormField.builder("hidden_var");
field.setType(FormField.Type.hidden); field.setType(FormField.Type.hidden);
field.addValue("Some value for the hidden variable"); field.addValue("Some value for the hidden variable");
formToSend.addField(field); formToSend.addField(field.build());
// Add a fixed variable // Add a fixed variable
field = new FormField(); field = FormField.builder();
field.addValue("Section 1: Case description"); field.addValue("Section 1: Case description");
formToSend.addField(field); field.setType(Type.fixed);
formToSend.addField(field.build());
// Add a text-single variable // Add a text-single variable
field = new FormField("name"); field = FormField.builder("name");
field.setLabel("Enter a name for the case"); field.setLabel("Enter a name for the case");
field.setType(FormField.Type.text_single); field.setType(FormField.Type.text_single);
formToSend.addField(field); formToSend.addField(field.build());
// Add a text-multi variable // Add a text-multi variable
field = new FormField("description"); field = FormField.builder("description");
field.setLabel("Enter a description"); field.setLabel("Enter a description");
field.setType(FormField.Type.text_multi); field.setType(FormField.Type.text_multi);
formToSend.addField(field); formToSend.addField(field.build());
// Add a boolean variable // Add a boolean variable
field = new FormField("time"); field = FormField.builder("time");
field.setLabel("Is this your first case?"); field.setLabel("Is this your first case?");
field.setType(FormField.Type.bool); field.setType(FormField.Type.bool);
formToSend.addField(field); formToSend.addField(field.build());
// Add a text variable where an int value is expected // Add a text variable where an int value is expected
field = new FormField("age"); field = FormField.builder("age");
field.setLabel("How old are you?"); field.setLabel("How old are you?");
field.setType(FormField.Type.text_single); field.setType(FormField.Type.text_single);
formToSend.addField(field); formToSend.addField(field.build());
// Create the chats between the two participants // Create the chats between the two participants
org.jivesoftware.smack.chat.Chat chat = org.jivesoftware.smack.chat.ChatManager.getInstanceFor(conOne).createChat(conTwo.getUser(), null); org.jivesoftware.smack.chat.Chat chat = org.jivesoftware.smack.chat.ChatManager.getInstanceFor(conOne).createChat(conTwo.getUser(), null);

View file

@ -403,9 +403,9 @@ public class Workgroup {
String name = iter.next(); String name = iter.next();
String value = metadata.get(name).toString(); String value = metadata.get(name).toString();
FormField field = new FormField(name); FormField.Builder field = FormField.builder(name);
field.setType(FormField.Type.text_single); field.setType(FormField.Type.text_single);
form.addField(field); form.addField(field.build());
form.setAnswer(name, value); form.setAnswer(name, value);
} }
joinQueue(form, userID); joinQueue(form, userID);