1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.dns;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.channel.AddressedEnvelope;
20 import io.netty.channel.ChannelHandler;
21 import io.netty.channel.ChannelHandlerContext;
22 import io.netty.channel.socket.DatagramPacket;
23 import io.netty.handler.codec.MessageToMessageEncoder;
24
25 import java.net.InetSocketAddress;
26 import java.util.List;
27
28
29
30
31
32 @ChannelHandler.Sharable
33 public class DatagramDnsQueryEncoder extends MessageToMessageEncoder<AddressedEnvelope<DnsQuery, InetSocketAddress>> {
34
35 private final DnsQueryEncoder encoder;
36
37
38
39
40 public DatagramDnsQueryEncoder() {
41 this(DnsRecordEncoder.DEFAULT);
42 }
43
44
45
46
47 public DatagramDnsQueryEncoder(DnsRecordEncoder recordEncoder) {
48 this.encoder = new DnsQueryEncoder(recordEncoder);
49 }
50
51 @Override
52 protected void encode(
53 ChannelHandlerContext ctx,
54 AddressedEnvelope<DnsQuery, InetSocketAddress> in, List<Object> out) throws Exception {
55
56 final InetSocketAddress recipient = in.recipient();
57 final DnsQuery query = in.content();
58 final ByteBuf buf = allocateBuffer(ctx, in);
59
60 boolean success = false;
61 try {
62 encoder.encode(query, buf);
63 success = true;
64 } finally {
65 if (!success) {
66 buf.release();
67 }
68 }
69
70 out.add(new DatagramPacket(buf, recipient, null));
71 }
72
73
74
75
76
77 protected ByteBuf allocateBuffer(
78 ChannelHandlerContext ctx,
79 @SuppressWarnings("unused") AddressedEnvelope<DnsQuery, InetSocketAddress> msg) throws Exception {
80 return ctx.alloc().ioBuffer(1024);
81 }
82 }