|
| 1 | +package org.msgpack.core.example; |
| 2 | + |
| 3 | +import org.msgpack.core.*; |
| 4 | +import org.msgpack.core.buffer.MessageBuffer; |
| 5 | +import org.msgpack.value.*; |
| 6 | +import org.msgpack.value.holder.FloatHolder; |
| 7 | +import org.msgpack.value.holder.IntegerHolder; |
| 8 | +import org.msgpack.value.holder.ValueHolder; |
| 9 | + |
| 10 | +import java.io.*; |
| 11 | +import java.math.BigInteger; |
| 12 | +import java.nio.ByteBuffer; |
| 13 | +import java.nio.charset.CodingErrorAction; |
| 14 | +import java.util.Random; |
| 15 | + |
| 16 | +/** |
| 17 | + * This class describes the usage of MessagePack v07 |
| 18 | + */ |
| 19 | +public class MessagePackExample { |
| 20 | + |
| 21 | + |
| 22 | + /** |
| 23 | + * Basic usage example |
| 24 | + * @throws IOException |
| 25 | + */ |
| 26 | + public static void basicUsage() throws IOException { |
| 27 | + |
| 28 | + // Serialize with MessagePacker |
| 29 | + ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 30 | + MessagePacker packer = MessagePackFactory.newDefaultPacker(out); |
| 31 | + packer |
| 32 | + .packInt(1) |
| 33 | + .packString("leo") |
| 34 | + .packArrayHeader(2) |
| 35 | + .packString("xxx-xxxx") |
| 36 | + .packString("yyy-yyyy"); |
| 37 | + packer.close(); |
| 38 | + |
| 39 | + // Deserialize with MessageUnpacker |
| 40 | + MessageUnpacker unpacker = MessagePackFactory.newDefaultUnpacker(out.toByteArray()); |
| 41 | + int id = unpacker.unpackInt(); // 1 |
| 42 | + String name = unpacker.unpackString(); // "leo" |
| 43 | + int numPhones = unpacker.unpackArrayHeader(); // 2 |
| 44 | + String[] phones = new String[numPhones]; |
| 45 | + for(int i=0; i < numPhones; ++i) { |
| 46 | + phones[i] = unpacker.unpackString(); // phones = {"xxx-xxxx", "yyy-yyyy"} |
| 47 | + } |
| 48 | + unpacker.close(); |
| 49 | + |
| 50 | + System.out.println(String.format("id:%d, name:%s, phone:[%s]", id, name, join(phones))); |
| 51 | + } |
| 52 | + |
| 53 | + private static String join(String[] in) { |
| 54 | + StringBuilder s = new StringBuilder(); |
| 55 | + for(int i=0; i<in.length; ++i) { |
| 56 | + if(i > 0) { |
| 57 | + s.append(", "); |
| 58 | + } |
| 59 | + s.append(in[i]); |
| 60 | + } |
| 61 | + return s.toString(); |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * Packing various types of data |
| 66 | + * @throws IOException |
| 67 | + */ |
| 68 | + public static void packer() throws IOException { |
| 69 | + |
| 70 | + // Create a MesagePacker (encoder) instance |
| 71 | + ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 72 | + MessagePacker packer = MessagePackFactory.newDefaultPacker(out); |
| 73 | + |
| 74 | + // pack (encode) primitive values in message pack format |
| 75 | + packer.packBoolean(true); |
| 76 | + packer.packShort((short) 34); |
| 77 | + packer.packInt(1); |
| 78 | + packer.packLong(33000000000L); |
| 79 | + |
| 80 | + packer.packFloat(0.1f); |
| 81 | + packer.packDouble(3.14159263); |
| 82 | + packer.packByte((byte) 0x80); |
| 83 | + |
| 84 | + packer.packNil(); |
| 85 | + |
| 86 | + // pack strings (in UTF-8) |
| 87 | + packer.packString("hello message pack!"); |
| 88 | + |
| 89 | + // [Advanced] write a raw UTF-8 string |
| 90 | + byte[] s = "utf-8 strings".getBytes(MessagePack.UTF8); |
| 91 | + packer.packRawStringHeader(s.length); |
| 92 | + packer.writePayload(s); |
| 93 | + |
| 94 | + // pack arrays |
| 95 | + int[] arr = new int[]{3, 5, 1, 0, -1, 255}; |
| 96 | + packer.packArrayHeader(arr.length); |
| 97 | + for(int v : arr) { |
| 98 | + packer.packInt(v); |
| 99 | + } |
| 100 | + |
| 101 | + // pack map (key -> value) elements |
| 102 | + packer.packMapHeader(2); // the number of (key, value) pairs |
| 103 | + // Put "apple" -> 1 |
| 104 | + packer.packString("apple"); |
| 105 | + packer.packInt(1); |
| 106 | + // Put "banana" -> 2 |
| 107 | + packer.packString("banana"); |
| 108 | + packer.packInt(2); |
| 109 | + |
| 110 | + // pack binary data |
| 111 | + byte[] ba = new byte[]{1, 2, 3, 4}; |
| 112 | + packer.packBinaryHeader(ba.length); |
| 113 | + packer.writePayload(ba); |
| 114 | + |
| 115 | + |
| 116 | + // Write ext type data: https://github.com/msgpack/msgpack/blob/master/spec.md#ext-format-family |
| 117 | + byte[] extData = "custom data type".getBytes(MessagePack.UTF8); |
| 118 | + packer.packExtendedTypeHeader(1, 10); // type number [0, 127], data byte length |
| 119 | + packer.writePayload(extData); |
| 120 | + |
| 121 | + // Succinct syntax for packing |
| 122 | + packer |
| 123 | + .packInt(1) |
| 124 | + .packString("leo") |
| 125 | + .packArrayHeader(2) |
| 126 | + .packString("xxx-xxxx") |
| 127 | + .packString("yyy-yyyy"); |
| 128 | + |
| 129 | + |
| 130 | + // [Advanced] ByteBuffer |
| 131 | + ByteBuffer.wrap(new byte[] {'b', 'i', 'n', 'a', 'r', 'y', 'd', 'a', 't', 'a'}); |
| 132 | + |
| 133 | + } |
| 134 | + |
| 135 | + |
| 136 | + /** |
| 137 | + * An example of reading and writing MessagePack data |
| 138 | + * @throws IOException |
| 139 | + */ |
| 140 | + public static void readAndWriteFile() throws IOException { |
| 141 | + |
| 142 | + File tempFile = File.createTempFile("target/tmp", ".txt"); |
| 143 | + tempFile.deleteOnExit(); |
| 144 | + |
| 145 | + // Write packed data to a file. No need exists to wrap the file stream with BufferedOutputStream, since MessagePacker has its own buffer |
| 146 | + MessagePacker packer = MessagePackFactory.newDefaultPacker(new FileOutputStream(tempFile)); |
| 147 | + packer.packInt(1); |
| 148 | + packer.packString("Hello Message Pack!"); |
| 149 | + packer.packArrayHeader(2).packFloat(0.1f).packDouble(0.342); |
| 150 | + packer.close(); |
| 151 | + |
| 152 | + // Read packed data from a file. No need exists to wrap the file stream with an buffer |
| 153 | + MessageUnpacker unpacker = MessagePackFactory.newDefaultUnpacker(new FileInputStream(tempFile)); |
| 154 | + |
| 155 | + while(unpacker.hasNext()) { |
| 156 | + // [Advanced] You can check the detailed data format with getNextFormat() |
| 157 | + // Here is a list of message pack data format: https://github.com/msgpack/msgpack/blob/master/spec.md#overview |
| 158 | + MessageFormat format = unpacker.getNextFormat(); |
| 159 | + |
| 160 | + // Alternatively you can use ValueHolder to extract a value of any type |
| 161 | + // NOTE: Value interface is in a preliminary state, so the following code might change in future releases |
| 162 | + ValueHolder v = new ValueHolder(); |
| 163 | + format = unpacker.unpackValue(v); |
| 164 | + switch(format.getValueType()) { |
| 165 | + case NIL: |
| 166 | + Value nil = v.get(); |
| 167 | + nil.isNil(); // true |
| 168 | + System.out.println("read nil"); |
| 169 | + break; |
| 170 | + case BOOLEAN: |
| 171 | + boolean b = v.get().asBoolean().toBoolean(); |
| 172 | + System.out.println("read boolean: " + b); |
| 173 | + break; |
| 174 | + case INTEGER: |
| 175 | + IntegerHolder ih = v.getIntegerHolder(); |
| 176 | + if(ih.isValidInt()) { // int range check [-2^31-1, 2^31-1] |
| 177 | + int i = ih.asInt(); |
| 178 | + System.out.println("read int: " + i); |
| 179 | + } |
| 180 | + else { |
| 181 | + long l = ih.asLong(); |
| 182 | + System.out.println("read long: " + l); |
| 183 | + } |
| 184 | + break; |
| 185 | + case FLOAT: |
| 186 | + FloatHolder fh = v.getFloatHolder(); |
| 187 | + float f = fh.toFloat(); // read as float |
| 188 | + double d = fh.toDouble(); // read as double |
| 189 | + System.out.println("read float: " + d); |
| 190 | + break; |
| 191 | + case STRING: |
| 192 | + String s = v.get().asString().toString(); |
| 193 | + System.out.println("read string: " + s); |
| 194 | + break; |
| 195 | + case BINARY: |
| 196 | + // Message buffer is an efficient byte buffer |
| 197 | + MessageBuffer mb = v.get().asBinary().toMessageBuffer(); |
| 198 | + System.out.println("read binary: " + mb.toHexString(0, mb.size())); |
| 199 | + break; |
| 200 | + case ARRAY: |
| 201 | + ArrayValue arr = v.get().asArrayValue(); |
| 202 | + for(ValueRef a : arr) { |
| 203 | + System.out.println("read array element: " + a); |
| 204 | + } |
| 205 | + break; |
| 206 | + case EXTENDED: |
| 207 | + ExtendedValue ev = v.get().asExtended(); |
| 208 | + int extType = ev.getExtType(); |
| 209 | + byte[] extValue = ev.toByteArray(); |
| 210 | + break; |
| 211 | + } |
| 212 | + } |
| 213 | + |
| 214 | + } |
| 215 | + |
| 216 | + /** |
| 217 | + * Example of using custom MessagePack configuration |
| 218 | + * @throws IOException |
| 219 | + */ |
| 220 | + public static void configuration() throws IOException { |
| 221 | + |
| 222 | + // Build a conifiguration |
| 223 | + MessagePack.Config config = new MessagePack.ConfigBuilder() |
| 224 | + .onMalFormedInput(CodingErrorAction.REPLACE) // Drop malformed and unmappable UTF-8 characters |
| 225 | + .onUnmappableCharacter(CodingErrorAction.REPLACE) |
| 226 | + .packerBufferSize(8192 * 2) |
| 227 | + .build(); |
| 228 | + // Create a factory that uses this configuration |
| 229 | + MessagePackFactory mf = new MessagePackFactory(config); |
| 230 | + |
| 231 | + // Pack data |
| 232 | + ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 233 | + MessagePacker packer = mf.newPacker(out); |
| 234 | + packer.packInt(10); |
| 235 | + packer.packBoolean(true); |
| 236 | + packer.close(); |
| 237 | + |
| 238 | + // Unpack data |
| 239 | + byte[] packedData = out.toByteArray(); |
| 240 | + MessageUnpacker unpacker = mf.newUnpacker(packedData); |
| 241 | + int i = unpacker.unpackInt(); // 10 |
| 242 | + boolean b = unpacker.unpackBoolean(); // true |
| 243 | + unpacker.close(); |
| 244 | + } |
| 245 | + |
| 246 | + |
| 247 | + |
| 248 | + |
| 249 | + |
| 250 | +} |
0 commit comments