Debian Codegraph @

minidns-client/src/main/java/org/minidns/RrSet.java

raw
1 /*
2 * Copyright 2015-2020 the original author or authors
3 *
4 * This software is licensed under the Apache License, Version 2.0,
5 * the GNU Lesser General Public License version 2 or later ("LGPL")
6 * and the WTFPL.
7 * You may choose either license to govern your use of this software only
8 * upon the condition that you accept all of the terms of either
9 * the Apache License 2.0, the LGPL 2.1+ or the WTFPL.
10 */
11 package org.minidns;
12
13 import java.util.Collections;
14 import java.util.LinkedHashSet;
15 import java.util.Set;
16
17 import org.minidns.dnsname.DnsName;
18 import org.minidns.record.Data;
19 import org.minidns.record.Record;
20 import org.minidns.record.Record.CLASS;
21 import org.minidns.record.Record.TYPE;
22
23 public final class RrSet {
24
25 public final DnsName name;
26 public final TYPE type;
27 public final CLASS clazz;
28 public final Set<Record<? extends Data>> records;
29
30 private RrSet(DnsName name, TYPE type, CLASS clazz, Set<Record<? extends Data>> records) {
31 this.name = name;
32 this.type = type;
33 this.clazz = clazz;
34 this.records = Collections.unmodifiableSet(records);
35 }
36
37 @Override
38 public String toString() {
39 StringBuilder sb = new StringBuilder();
40 sb.append(name).append('\t').append(clazz).append('\t').append(type).append('\n');
41 for (Record<?> record : records) {
42 sb.append(record).append('\n');
43 }
44 return sb.toString();
45 }
46
47 public static Builder builder() {
48 return new Builder();
49 }
50
51 public static final class Builder {
52 private DnsName name;
53 private TYPE type;
54 private CLASS clazz;
55 Set<Record<? extends Data>> records = new LinkedHashSet<>(8);
56
57 private Builder() {
58 }
59
60 public Builder addRecord(Record<? extends Data> record) {
61 if (name == null) {
62 name = record.name;
63 type = record.type;
64 clazz = record.clazz;
65 } else if (!couldContain(record)) {
66 throw new IllegalArgumentException(
67 "Can not add " + record + " to RRSet " + name + ' ' + type + ' ' + clazz);
68 }
69
70 boolean didNotExist = records.add(record);
71 assert didNotExist;
72
73 return this;
74 }
75
76 public boolean couldContain(Record<? extends Data> record) {
77 if (name == null) {
78 return true;
79 }
80 return name.equals(record.name) && type == record.type && clazz == record.clazz;
81 }
82
83 public boolean addIfPossible(Record<? extends Data> record) {
84 if (!couldContain(record)) {
85 return false;
86 }
87 addRecord(record);
88 return true;
89 }
90
91 public RrSet build() {
92 if (name == null) {
93 // There is no RR added to this builder.
94 throw new IllegalStateException();
95 }
96 return new RrSet(name, type, clazz, records);
97 }
98 }
99 }