|
| 1 | +package dev.latvian.apps.tinyserver.http; |
| 2 | + |
| 3 | +import dev.latvian.apps.tinyserver.OptionalString; |
| 4 | +import dev.latvian.apps.tinyserver.content.MimeType; |
| 5 | + |
| 6 | +import java.io.ByteArrayOutputStream; |
| 7 | +import java.net.URLDecoder; |
| 8 | +import java.nio.ByteBuffer; |
| 9 | +import java.nio.charset.StandardCharsets; |
| 10 | +import java.util.Collections; |
| 11 | +import java.util.LinkedHashMap; |
| 12 | +import java.util.Map; |
| 13 | + |
| 14 | +public class Body { |
| 15 | + ByteBuffer byteBuffer; |
| 16 | + Map<String, OptionalString> properties; // new LinkedHashMap<>() |
| 17 | + String name = ""; |
| 18 | + String fileName = ""; |
| 19 | + String contentType = MimeType.TEXT; |
| 20 | + |
| 21 | + public ByteBuffer byteBuffer() { |
| 22 | + return byteBuffer.position(0); |
| 23 | + } |
| 24 | + |
| 25 | + public String text() { |
| 26 | + return StandardCharsets.UTF_8.decode(byteBuffer()).toString(); |
| 27 | + } |
| 28 | + |
| 29 | + public byte[] bytes() { |
| 30 | + var buf = byteBuffer(); |
| 31 | + |
| 32 | + try { |
| 33 | + return buf.array(); |
| 34 | + } catch (Exception ex) { |
| 35 | + var out = new ByteArrayOutputStream(buf.remaining()); |
| 36 | + |
| 37 | + while (buf.hasRemaining()) { |
| 38 | + out.write(buf.get()); |
| 39 | + } |
| 40 | + |
| 41 | + return out.toByteArray(); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + public OptionalString property(String key) { |
| 46 | + return properties == null || properties.isEmpty() ? OptionalString.MISSING : properties.getOrDefault(key.toLowerCase(), OptionalString.MISSING); |
| 47 | + } |
| 48 | + |
| 49 | + public String name() { |
| 50 | + return name; |
| 51 | + } |
| 52 | + |
| 53 | + public String fileName() { |
| 54 | + return fileName; |
| 55 | + } |
| 56 | + |
| 57 | + public String contentType() { |
| 58 | + return contentType; |
| 59 | + } |
| 60 | + |
| 61 | + public Map<String, OptionalString> getPostData() { |
| 62 | + var text = text(); |
| 63 | + |
| 64 | + if (text.isEmpty()) { |
| 65 | + return Collections.emptyMap(); |
| 66 | + } |
| 67 | + |
| 68 | + var map = new LinkedHashMap<String, OptionalString>(4); |
| 69 | + |
| 70 | + for (var s : text.split("&")) { |
| 71 | + var p = s.split("=", 2); |
| 72 | + |
| 73 | + try { |
| 74 | + var k = URLDecoder.decode(p[0], StandardCharsets.UTF_8); |
| 75 | + |
| 76 | + if (!k.isEmpty()) { |
| 77 | + if (p.length == 2) { |
| 78 | + map.put(k, OptionalString.of(URLDecoder.decode(p[1], StandardCharsets.UTF_8))); |
| 79 | + } else { |
| 80 | + map.put(k, OptionalString.EMPTY); |
| 81 | + } |
| 82 | + } |
| 83 | + } catch (Exception ex) { |
| 84 | + ex.printStackTrace(); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + return map; |
| 89 | + } |
| 90 | + |
| 91 | + @Override |
| 92 | + public String toString() { |
| 93 | + return name.isEmpty() ? "body" : name; |
| 94 | + } |
| 95 | +} |
| 96 | + |
0 commit comments