Open Kilda Java Documentation
BaseMessage.java
Go to the documentation of this file.
1 /* Copyright 2017 Telstra Open Source
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 package org.openkilda.messaging;
17 
18 import static org.openkilda.messaging.Utils.MAPPER;
19 import static org.openkilda.messaging.Utils.TIMESTAMP;
20 
21 import com.fasterxml.jackson.annotation.JsonCreator;
22 import com.fasterxml.jackson.annotation.JsonInclude;
23 import com.fasterxml.jackson.annotation.JsonProperty;
24 import com.fasterxml.jackson.annotation.JsonTypeInfo;
25 
26 import com.fasterxml.jackson.databind.annotation.JsonSerialize;
27 
28 import java.io.Serializable;
29 
41 @JsonSerialize
42 @JsonInclude(JsonInclude.Include.NON_NULL)
43 @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="clazz")
44 public abstract class BaseMessage implements Serializable {
48  static final long serialVersionUID = 1L;
49 
53  @JsonProperty(TIMESTAMP)
54  protected long timestamp = 0L;
55 
56 
62  @JsonCreator
63  public BaseMessage(@JsonProperty(TIMESTAMP) final long timestamp) {
64  this.timestamp = timestamp;
65  }
66 
70  public BaseMessage() {
71  this(System.currentTimeMillis());
72  }
73 
74 
80  public long getTimestamp() {
81  return timestamp;
82  }
83 
89  public void setTimestamp(long timestamp) {
90  this.timestamp = timestamp;
91  }
92 
101  public static final <T extends BaseMessage> T getMessage(String json, Class<T> type)
102  throws java.io.IOException {
103  return type.cast(MAPPER.readValue(json, type));
104  }
105 
118  public static final <T extends BaseMessage> T tryGetMessage(String json, Class<T> type) {
119  try {
120  return getMessage(json, type);
121  } catch (Exception e) {
122  /* Do Nothing */
123  }
124  return null;
125 
126  }
127 
128 }
void setTimestamp(long timestamp)
static final ObjectMapper MAPPER
Definition: Utils.java:31
static final< T extends BaseMessage > T getMessage(String json, Class< T > type)
static final< T extends BaseMessage > T tryGetMessage(String json, Class< T > type)
static final String TIMESTAMP
Definition: Utils.java:35