Open Kilda Java Documentation
JsonMessage.java
Go to the documentation of this file.
1 package org.openkilda.wfm.protocol;
2 
3 import com.fasterxml.jackson.core.JsonProcessingException;
4 import org.apache.storm.tuple.Fields;
5 import org.apache.storm.tuple.Tuple;
8 
9 import java.io.IOException;
10 
11 abstract public class JsonMessage<T> extends AbstractMessage {
12  public static final String FIELD_ID_JSON = "json";
13 
14  public static final Fields FORMAT = new Fields(FIELD_ID_JSON);
15 
16  private T payload;
17 
18  public JsonMessage(Tuple raw) throws MessageFormatException {
19  super();
20 
21  String json = raw.getString(getFormat().fieldIndex(FIELD_ID_JSON));
22  try {
23  payload = unpackJson(json);
24  } catch (IOException e) {
25  throw new MessageFormatException(raw, e);
26  }
27  }
28 
29  public JsonMessage(T payload) {
30  this.payload = payload;
31  }
32 
33  protected abstract T unpackJson(String json) throws IOException;
34 
35  public T getPayload() {
36  return payload;
37  }
38 
39  @Override
40  protected Object packField(String fieldId) throws JsonProcessingException {
41  if (fieldId.equals(FIELD_ID_JSON)) {
42  return Utils.MAPPER.writeValueAsString(getPayload());
43  }
44  return super.packField(fieldId);
45  }
46 
47  @Override
48  protected Fields getFormat() {
49  return FORMAT;
50  }
51 }
static final ObjectMapper MAPPER
Definition: Utils.java:31
abstract T unpackJson(String json)