2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.pcep.impl;
10 import io.netty.buffer.ByteBuf;
11 import io.netty.buffer.Unpooled;
12 import io.netty.channel.ChannelHandler.Sharable;
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.handler.codec.MessageToByteEncoder;
16 import org.opendaylight.protocol.pcep.spi.MessageHandlerRegistry;
17 import org.opendaylight.protocol.pcep.spi.MessageSerializer;
18 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
22 import com.google.common.base.Preconditions;
23 import com.google.common.primitives.UnsignedBytes;
29 public final class PCEPMessageToByteEncoder extends MessageToByteEncoder<Message> {
30 private static final Logger LOG = LoggerFactory.getLogger(PCEPMessageToByteEncoder.class);
31 private static final int VERSION_SF_LENGTH = 3;
32 private final MessageHandlerRegistry registry;
34 public PCEPMessageToByteEncoder(final MessageHandlerRegistry registry) {
35 this.registry = Preconditions.checkNotNull(registry);
39 protected void encode(final ChannelHandlerContext ctx, final Message msg, final ByteBuf out) throws Exception {
40 Preconditions.checkNotNull(msg);
41 LOG.debug("Sent to encode : {}", msg);
43 final ByteBuf body = Unpooled.buffer();
44 final MessageSerializer serializer = this.registry.getMessageSerializer(msg);
45 serializer.serializeMessage(msg, body);
47 final int msgLength = body.readableBytes() + PCEPMessageConstants.COMMON_HEADER_LENGTH;
48 final byte[] header = new byte[] {
49 UnsignedBytes.checkedCast(PCEPMessageConstants.PCEP_VERSION << (Byte.SIZE - VERSION_SF_LENGTH)),
50 UnsignedBytes.checkedCast(serializer.getMessageType()),
51 UnsignedBytes.checkedCast(msgLength / 256),
52 UnsignedBytes.checkedCast(msgLength % 256)
54 Preconditions.checkState(header.length == PCEPMessageConstants.COMMON_HEADER_LENGTH);
55 out.writeBytes(header);