Question.java

 1package de.measite.minidns;
 2
 3import java.io.ByteArrayOutputStream;
 4import java.io.DataInputStream;
 5import java.io.DataOutputStream;
 6import java.io.IOException;
 7
 8import de.measite.minidns.Record.CLASS;
 9import de.measite.minidns.Record.TYPE;
10import de.measite.minidns.util.NameUtil;
11
12public class Question {
13
14    private final String name;
15
16    private final TYPE type;
17
18    private final CLASS clazz;
19
20    private byte[] byteArray;
21
22    public Question(String name, TYPE type, CLASS clazz) {
23        this.name = name;
24        this.type = type;
25        this.clazz = clazz;
26    }
27
28    public TYPE getType() {
29        return type;
30    }
31
32    public CLASS getClazz() {
33        return clazz;
34    }
35
36    public String getName() {
37        return name;
38    }
39
40    public static Question parse(DataInputStream dis, byte[] data) throws IOException {
41        String name = NameUtil.parse(dis, data);
42        TYPE type = TYPE.getType(dis.readUnsignedShort());
43        CLASS clazz = CLASS.getClass(dis.readUnsignedShort());
44        return new Question (name, type, clazz);
45    }
46
47    public byte[] toByteArray() {
48        if (byteArray == null) {
49            ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
50            DataOutputStream dos = new DataOutputStream(baos);
51
52            try {
53                dos.write(NameUtil.toByteArray(this.name));
54                dos.writeShort(type.getValue());
55                dos.writeShort(clazz.getValue());
56                dos.flush();
57            } catch (IOException e) {
58                // Should never happen
59                throw new IllegalStateException(e);
60            }
61            byteArray = baos.toByteArray();
62        }
63        return byteArray;
64    }
65
66    @Override
67    public int hashCode() {
68        return toByteArray().hashCode();
69    }
70
71    @Override
72    public boolean equals(Object other) {
73        if (this == other) {
74            return true;
75        }
76        if (!(other instanceof Question)) {
77            return false;
78        }
79        return this.hashCode() == other.hashCode();
80    }
81}