1package im.conversations.android.xmpp.model.stanza;
2
3import com.google.common.base.Strings;
4import eu.siacs.conversations.xml.Element;
5import im.conversations.android.annotation.XmlElement;
6import im.conversations.android.xmpp.model.Extension;
7import im.conversations.android.xmpp.model.error.Error;
8import java.util.Arrays;
9import java.util.Locale;
10
11@XmlElement
12public class Iq extends Stanza {
13
14 public static Iq TIMEOUT = new Iq(Type.TIMEOUT);
15
16 public Iq() {
17 super(Iq.class);
18 }
19
20 public Iq(final Type type) {
21 super(Iq.class);
22 this.setAttribute("type", type.toString().toLowerCase(Locale.ROOT));
23 }
24
25 public Iq(final Type type, final Extension... extensions) {
26 this(type);
27 this.addExtensions(Arrays.asList(extensions));
28 }
29
30 // TODO get rid of timeout
31 public enum Type {
32 SET,
33 GET,
34 ERROR,
35 RESULT,
36 TIMEOUT
37 }
38
39 public Type getType() {
40 return Type.valueOf(
41 Strings.nullToEmpty(this.getAttribute("type")).toUpperCase(Locale.ROOT));
42 }
43
44 @Override
45 public boolean isInvalid() {
46 final var id = getId();
47 if (Strings.isNullOrEmpty(id)) {
48 return true;
49 }
50 return super.isInvalid();
51 }
52
53 // Legacy methods that need to be refactored:
54
55 public Element query() {
56 final Element query = findChild("query");
57 if (query != null) {
58 return query;
59 }
60 return addChild("query");
61 }
62
63 public Element query(final String xmlns) {
64 final Element query = query();
65 query.setAttribute("xmlns", xmlns);
66 return query();
67 }
68
69 public Iq generateResponse(final Iq.Type type) {
70 final var packet = new Iq(type);
71 packet.setTo(this.getFrom());
72 packet.setId(this.getId());
73 return packet;
74 }
75
76 public String getErrorCondition() {
77 final Error error = getError();
78 final var condition = error == null ? null : error.getCondition();
79 return condition == null ? null : condition.getName();
80 }
81}