1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package io.netty5.example.http2;
16
17 import io.netty5.buffer.api.Buffer;
18 import io.netty5.handler.codec.http.QueryStringDecoder;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.util.List;
23
24 import static io.netty5.buffer.api.DefaultBufferAllocators.preferredAllocator;
25 import static java.util.Objects.requireNonNull;
26
27
28
29
30 public final class Http2ExampleUtil {
31
32
33
34
35 public static final String UPGRADE_RESPONSE_HEADER = "http-to-http2-upgrade";
36
37
38
39
40 private static final int BLOCK_SIZE = 1024;
41
42 private Http2ExampleUtil() { }
43
44
45
46
47
48
49 public static int toInt(String string, int defaultValue) {
50 if (string != null && !string.isEmpty()) {
51 return Integer.parseInt(string);
52 }
53 return defaultValue;
54 }
55
56
57
58
59
60
61
62 public static Buffer toBuffer(InputStream input) throws IOException {
63 Buffer buf = preferredAllocator().allocate(BLOCK_SIZE);
64 byte[] array = new byte[BLOCK_SIZE];
65 for (;;) {
66 int n = input.read(array);
67 if (n < 0) {
68 return buf;
69 }
70 buf.writeBytes(array, 0, n);
71 }
72 }
73
74
75
76
77
78
79 public static String firstValue(QueryStringDecoder query, String key) {
80 requireNonNull(query, "Query can't be null!");
81 List<String> values = query.parameters().get(key);
82 if (values == null || values.isEmpty()) {
83 return null;
84 }
85 return values.get(0);
86 }
87 }