aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/measite/minidns/Question.java
blob: 8efe19f116d549b9d76651c1190da1803a988bd1 (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
package de.measite.minidns;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import de.measite.minidns.Record.CLASS;
import de.measite.minidns.Record.TYPE;
import de.measite.minidns.util.NameUtil;

public class Question {

    private final String name;

    private final TYPE type;

    private final CLASS clazz;

    private byte[] byteArray;

    public Question(String name, TYPE type, CLASS clazz) {
        this.name = name;
        this.type = type;
        this.clazz = clazz;
    }

    public TYPE getType() {
        return type;
    }

    public CLASS getClazz() {
        return clazz;
    }

    public String getName() {
        return name;
    }

    public static Question parse(DataInputStream dis, byte[] data) throws IOException {
        String name = NameUtil.parse(dis, data);
        TYPE type = TYPE.getType(dis.readUnsignedShort());
        CLASS clazz = CLASS.getClass(dis.readUnsignedShort());
        return new Question (name, type, clazz);
    }

    public byte[] toByteArray() {
        if (byteArray == null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
            DataOutputStream dos = new DataOutputStream(baos);

            try {
                dos.write(NameUtil.toByteArray(this.name));
                dos.writeShort(type.getValue());
                dos.writeShort(clazz.getValue());
                dos.flush();
            } catch (IOException e) {
                // Should never happen
                throw new IllegalStateException(e);
            }
            byteArray = baos.toByteArray();
        }
        return byteArray;
    }

    @Override
    public int hashCode() {
        return toByteArray().hashCode();
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }
        if (!(other instanceof Question)) {
            return false;
        }
        return this.hashCode() == other.hashCode();
    }
}