f4f7f97dfa54d737adf657e0d95ffd2bcbe621c4
[openflowplugin.git] / openflowjava / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / protocol / impl / core / OFDatagramPacketEncoder.java
1 /*
2  * Copyright (c) 2014 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.buffer.PooledByteBufAllocator;
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.channel.socket.DatagramPacket;
15 import io.netty.handler.codec.MessageToMessageEncoder;
16 import io.netty.util.concurrent.Future;
17 import java.util.List;
18 import org.opendaylight.openflowjava.protocol.impl.core.connection.UdpMessageListenerWrapper;
19 import org.opendaylight.openflowjava.protocol.impl.serialization.SerializationFactory;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22
23 /**
24  * Encoder for datagram packets.
25  *
26  * @author michal.polkorab
27  */
28 public class OFDatagramPacketEncoder extends MessageToMessageEncoder<UdpMessageListenerWrapper> {
29
30     private static final Logger LOG = LoggerFactory.getLogger(OFDatagramPacketEncoder.class);
31     private SerializationFactory serializationFactory;
32
33     @Override
34     @SuppressWarnings("checkstyle:IllegalCatch")
35     protected void encode(final ChannelHandlerContext ctx,
36             final UdpMessageListenerWrapper wrapper, final List<Object> out) throws Exception {
37         LOG.trace("Encoding");
38         try {
39             ByteBuf buffer = PooledByteBufAllocator.DEFAULT.buffer();
40             serializationFactory.messageToBuffer(wrapper.getMsg().getVersion(), buffer, wrapper.getMsg());
41             out.add(new DatagramPacket(buffer, wrapper.getAddress()));
42         } catch (RuntimeException e) {
43             LOG.warn("Message serialization failed: {}", e.getMessage());
44             Future<Void> newFailedFuture = ctx.newFailedFuture(e);
45             wrapper.getListener().operationComplete(newFailedFuture);
46             return;
47         }
48     }
49
50     public void setSerializationFactory(final SerializationFactory serializationFactory) {
51         this.serializationFactory = serializationFactory;
52     }
53 }