aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/thedevstack/conversationsplus/xmpp/forms/Data.java
blob: caa1890ef509b3d8f60736331166920d56696be7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package de.thedevstack.conversationsplus.xmpp.forms;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import de.thedevstack.conversationsplus.xml.Element;

public class Data extends Element {

	private static final String FORM_TYPE = "FORM_TYPE";

	public Data() {
		super("x");
		this.setAttribute("xmlns","jabber:x:data");
	}

	public List<Field> getFields() {
		ArrayList<Field> fields = new ArrayList<Field>();
		for(Element child : getChildren()) {
			if (child.getName().equals("field")
					&& !FORM_TYPE.equals(child.getAttribute("var"))) {
				fields.add(Field.parse(child));
			}
		}
		return fields;
	}

	public Field getFieldByName(String needle) {
		for(Element child : getChildren()) {
			if (child.getName().equals("field")
					&& needle.equals(child.getAttribute("var"))) {
				return Field.parse(child);
			}
		}
		return null;
	}

	public void put(String name, String value) {
		Field field = getFieldByName(name);
		if (field == null) {
			field = new Field(name);
			this.addChild(field);
		}
		field.setValue(value);
	}

	public void put(String name, Collection<String> values) {
		Field field = getFieldByName(name);
		if (field == null) {
			field = new Field(name);
			this.addChild(field);
		}
		field.setValues(values);
	}

	public void submit() {
		this.setAttribute("type","submit");
		removeUnnecessaryChildren();
		for(Field field : getFields()) {
			field.removeNonValueChildren();
		}
	}

	private void removeUnnecessaryChildren() {
		for(Iterator<Element> iterator = this.children.iterator(); iterator.hasNext();) {
			Element element = iterator.next();
			if (!element.getName().equals("field") && !element.getName().equals("title")) {
				iterator.remove();
			}
		}
	}

	public static Data parse(Element element) {
		Data data = new Data();
		data.setAttributes(element.getAttributes());
		data.setChildren(element.getChildren());
		return data;
	}

	public void setFormType(String formType) {
		this.put(FORM_TYPE, formType);
	}

	public String getFormType() {
		String type = getValue(FORM_TYPE);
		return type == null ? "" : type;
	}

	public String getValue(String name) {
		Field field = this.getFieldByName(name);
		return field == null ? null : field.getValue();
	}

	public String getTitle() {
		return findChildContent("title");
	}
}