blob: 3b849d1d7cc11937011cbb40cb7ddab59326073b [file] [log] [blame]
Jian Li0bbbb1c2018-06-22 22:01:17 +09001/*
2 * Copyright 2018-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.openstacktelemetry.codec;
17
18import org.onosproject.openstacktelemetry.api.FlowInfo;
19
20import java.nio.ByteBuffer;
21import java.util.Set;
22
23/**
24 * Tina Message ByteBuffer Codec.
25 */
26public class TinaMessageByteBufferCodec {
27
28 private static final int HEADER_SIZE = 8;
29 private static final int ENTRY_SIZE = 88;
30 private static final int MILLISECONDS = 1000;
31 private static final short KAFKA_MESSAGE_TYPE = 1;
32
33 /**
34 * Encodes a collection flow infos into byte buffer.
35 *
36 * @param flowInfos a collection of flow info
37 * @return encoded byte buffer
38 */
39 public ByteBuffer encode(Set<FlowInfo> flowInfos) {
40 ByteBuffer byteBuffer =
41 ByteBuffer.allocate(HEADER_SIZE + flowInfos.size() * ENTRY_SIZE);
42
43 byteBuffer.put(buildMessageHeader(flowInfos));
44 byteBuffer.put(buildMessageBody(flowInfos));
45
46 return byteBuffer;
47 }
48
49 private byte[] buildMessageHeader(Set<FlowInfo> flowInfos) {
50 ByteBuffer byteBuffer = ByteBuffer.allocate(HEADER_SIZE);
51
52 byteBuffer.putShort((short) flowInfos.size());
53 byteBuffer.putShort(KAFKA_MESSAGE_TYPE);
54 byteBuffer.putInt((int) (System.currentTimeMillis() / MILLISECONDS));
55
56 return byteBuffer.array();
57 }
58
59 private byte[] buildMessageBody(Set<FlowInfo> flowInfos) {
60 ByteBuffer byteBuffer = ByteBuffer.allocate(flowInfos.size() * ENTRY_SIZE);
61
62 TinaFlowInfoByteBufferCodec codec = new TinaFlowInfoByteBufferCodec();
63 flowInfos.forEach(flowInfo -> byteBuffer.put(codec.encode(flowInfo)));
64
65 return byteBuffer.array();
66 }
67}