Remove ByteBufWriteUtil.writeInt()
[bgpcep.git] / bmp / bmp-spi / src / main / java / org / opendaylight / protocol / bmp / spi / parser / AbstractBmpMessageParser.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.protocol.bmp.spi.parser;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static org.opendaylight.protocol.bmp.spi.parser.BmpMessageConstants.BMP_VERSION;
12 import static org.opendaylight.protocol.bmp.spi.parser.BmpMessageConstants.COMMON_HEADER_LENGTH;
13
14 import io.netty.buffer.ByteBuf;
15 import io.netty.buffer.ByteBufUtil;
16 import io.netty.buffer.Unpooled;
17 import org.opendaylight.yangtools.yang.binding.Notification;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 public abstract class AbstractBmpMessageParser implements BmpMessageParser, BmpMessageSerializer {
22
23     private static final Logger LOG = LoggerFactory.getLogger(AbstractBmpMessageParser.class);
24
25     @Override
26     public final void serializeMessage(final Notification message, final ByteBuf buffer) {
27         checkArgument(message != null, "BMP message is mandatory.");
28         final ByteBuf bodyBuffer = Unpooled.buffer();
29         serializeMessageBody(message, bodyBuffer);
30         formatMessage(bodyBuffer, buffer);
31         LOG.trace("Serialized BMP message: {}", ByteBufUtil.hexDump(buffer));
32     }
33
34     @Override
35     public final Notification parseMessage(final ByteBuf bytes) throws BmpDeserializationException {
36         checkArgument(bytes != null && bytes.isReadable());
37         final Notification parsedMessage = parseMessageBody(bytes);
38         LOG.trace("Parsed BMP message: {}", parsedMessage);
39         return parsedMessage;
40     }
41
42     private void formatMessage(final ByteBuf body, final ByteBuf output) {
43         output.writeByte(BMP_VERSION);
44         output.writeInt(body.writerIndex() + COMMON_HEADER_LENGTH);
45         output.writeByte(getBmpMessageType());
46         output.writeBytes(body);
47     }
48
49     public abstract void serializeMessageBody(Notification message, ByteBuf buffer);
50
51     public abstract Notification parseMessageBody(ByteBuf bytes) throws BmpDeserializationException;
52
53     public abstract int getBmpMessageType();
54
55 }