Skip to content

Package: KuraBinaryPayloadCodec

KuraBinaryPayloadCodec

nameinstructionbranchcomplexitylinemethod
decode(ByteBuffer)
M: 16 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 4 C: 0
0%
M: 1 C: 0
0%
encode(Payload, ByteBuffer)
M: 55 C: 0
0%
M: 4 C: 0
0%
M: 3 C: 0
0%
M: 15 C: 0
0%
M: 1 C: 0
0%

Coverage

1: /*******************************************************************************
2: * Copyright (c) 2017, 2022 Red Hat Inc and others.
3: *
4: * This program and the accompanying materials are made
5: * available under the terms of the Eclipse Public License 2.0
6: * which is available at https://www.eclipse.org/legal/epl-2.0/
7: *
8: * SPDX-License-Identifier: EPL-2.0
9: *
10: * Contributors:
11: * Red Hat Inc - initial API and implementation
12: *******************************************************************************/
13: package org.eclipse.kapua.client.gateway.kura;
14:
15: import org.eclipse.kapua.client.gateway.BinaryPayloadCodec;
16: import org.eclipse.kapua.client.gateway.Payload;
17: import org.eclipse.kapua.client.gateway.kura.internal.Metrics;
18: import org.eclipse.kapua.client.gateway.kura.proto.KuraPayloadProto;
19: import org.eclipse.kapua.client.gateway.kura.proto.KuraPayloadProto.KuraPayload;
20: import org.eclipse.kapua.client.gateway.spi.util.Buffers;
21:
22: import java.nio.ByteBuffer;
23: import java.time.Instant;
24: import java.util.Map;
25: import java.util.Objects;
26:
27: public class KuraBinaryPayloadCodec implements BinaryPayloadCodec {
28:
29: public static class Builder {
30:
31: public KuraBinaryPayloadCodec build() {
32: return new KuraBinaryPayloadCodec();
33: }
34: }
35:
36: private KuraBinaryPayloadCodec() {
37: }
38:
39: @Override
40: public ByteBuffer encode(final Payload payload, final ByteBuffer buffer) throws Exception {
41:
42: Objects.requireNonNull(payload);
43:
44: final KuraPayloadProto.KuraPayload.Builder builder = KuraPayload.newBuilder();
45: builder.setTimestamp(payload.getTimestamp().toEpochMilli());
46: Metrics.buildMetrics(builder, payload.getValues());
47:
48: final byte[] data = builder.build().toByteArray();
49:
50:• if (buffer == null) {
51: // create a wrapped buffer
52: return Buffers.wrap(data);
53:• } else if (buffer.remaining() < data.length) {
54: // create a new, merged buffer
55: buffer.flip();
56: final ByteBuffer newBuffer = ByteBuffer.allocate(buffer.remaining() + data.length);
57: newBuffer.put(buffer);
58: newBuffer.put(data);
59: return newBuffer;
60: } else {
61: buffer.put(data);
62: return buffer;
63: }
64: }
65:
66: @Override
67: public Payload decode(final ByteBuffer buffer) throws Exception {
68: Objects.requireNonNull(buffer);
69:
70: final KuraPayload payload = KuraPayload.parseFrom(Buffers.toByteArray(buffer));
71: final Map<String, Object> values = Metrics.extractMetrics(payload);
72: return Payload.of(Instant.ofEpochMilli(payload.getTimestamp()), values);
73: }
74:
75: }