aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/thedevstack/conversationsplus/xmpp/jid/Jid.java
blob: a85c0bed338b5321ddead0803a26bcbfc5a84b1b (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
package de.thedevstack.conversationsplus.xmpp.jid;

import java.net.IDN;

/**
 * The `Jid' class provides an immutable representation of a JID.
 */
public final class Jid {

	private final String localpart;
	private final String domainpart;
	private final String resourcepart;

	// It's much more efficient to store the ful JID as well as the parts instead of figuring them
	// all out every time (since some characters are displayed but aren't used for comparisons).
	private final String displayjid;

	public String getLocalpart() {
		return localpart;
	}

	public String getDomainpart() {
		return IDN.toUnicode(domainpart);
	}

	public String getResourcepart() {
		return resourcepart;
	}

	Jid(String displayjid, String local, String domain, String resource) throws InvalidJidException {
		this.displayjid = displayjid;
		this.localpart = local;
		this.domainpart = (null == domain) ? "" : domain;
		this.resourcepart = (null == resource) ? "" : resource;
	}

	public Jid toBareJid() {
		try {
			return resourcepart.isEmpty() ? this : JidUtil.fromParts(localpart, domainpart, "");
		} catch (final InvalidJidException e) {
			// This should never happen.
			throw new AssertionError("Jid " + this.toString() + " invalid");
		}
	}

	public Jid toDomainJid() {
		try {
			return resourcepart.isEmpty() && localpart.isEmpty() ? this : JidUtil.fromString(getDomainpart());
		} catch (final InvalidJidException e) {
			// This should never happen.
			throw new AssertionError("Jid " + this.toString() + " invalid");
		}
	}

	@Override
	public String toString() {
		return displayjid;
	}

	@Override
	public boolean equals(final Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;

		final Jid jid = (Jid) o;

		return jid.hashCode() == this.hashCode();
	}

	@Override
	public int hashCode() {
		int result = localpart.hashCode();
		result = 31 * result + domainpart.hashCode();
		result = 31 * result + resourcepart.hashCode();
		return result;
	}

	public boolean hasLocalpart() {
		return !localpart.isEmpty();
	}

	public boolean isBareJid() {
		return this.resourcepart.isEmpty();
	}

	public boolean isDomainJid() {
		return !this.hasLocalpart();
	}
}