Extensibility support (serialization part)
[openflowjava.git] / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / protocol / impl / core / OFEncoder.java
1 /*
2  * Copyright (c) 2013 Pantheon Technologies s.r.o. 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
9 package org.opendaylight.openflowjava.protocol.impl.core;
10
11 import io.netty.buffer.ByteBuf;
12 import io.netty.channel.ChannelHandlerContext;
13 import io.netty.handler.codec.MessageToByteEncoder;
14
15 import org.opendaylight.openflowjava.protocol.impl.serialization.SerializationFactory;
16 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20 /**
21  * Transforms OpenFlow Protocol messages to POJOs
22  * @author michal.polkorab
23  * @author timotej.kubas
24  */
25 public class OFEncoder extends MessageToByteEncoder<OfHeader> {
26
27     private static final Logger LOGGER = LoggerFactory.getLogger(OFEncoder.class);
28     private SerializationFactory serializationFactory;
29
30     /** Constructor of class */
31     public OFEncoder() {
32         LOGGER.trace("Creating OF13Encoder");
33     }
34
35     @Override
36     protected void encode(ChannelHandlerContext ctx, OfHeader msg, ByteBuf out)
37             throws Exception {
38         LOGGER.trace("Encoding");
39         try {
40             serializationFactory.messageToBuffer(msg.getVersion(), out, msg);
41         } catch(Exception e) {
42             LOGGER.error("Message serialization failed");
43             LOGGER.error(e.getMessage(), e);
44             out.clear();
45             return;
46         }
47         if (out.readableBytes() > 0) {
48             out.retain();
49             ctx.writeAndFlush(out);
50         } else {
51             LOGGER.warn("Translated buffer is empty");
52         }
53     }
54
55     /**
56      * @param serializationFactory
57      */
58     public void setSerializationFactory(SerializationFactory serializationFactory) {
59         this.serializationFactory = serializationFactory;
60     }
61
62 }