blob: 3d9f8eeaa05bf9dc0cd2e60ff5c300c820719bc1 [file] [log] [blame]
Hyunsun Moon90163ba2016-10-12 13:35:14 -07001/*
2 * Copyright 2017-present Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.ofagent.impl;
17
18import io.netty.buffer.ByteBuf;
Daniel Parkbe6b6732016-11-11 15:52:19 +090019import io.netty.buffer.PooledByteBufAllocator;
Hyunsun Moon90163ba2016-10-12 13:35:14 -070020import io.netty.channel.ChannelHandlerContext;
Daniel Parkbe6b6732016-11-11 15:52:19 +090021import io.netty.handler.codec.EncoderException;
Hyunsun Moon90163ba2016-10-12 13:35:14 -070022import io.netty.handler.codec.MessageToByteEncoder;
23import org.projectfloodlight.openflow.protocol.OFMessage;
Daniel Parkbe6b6732016-11-11 15:52:19 +090024import org.slf4j.Logger;
25import org.slf4j.LoggerFactory;
Hyunsun Moon90163ba2016-10-12 13:35:14 -070026
27/**
28 * Encodes OFMessage to a byte buffer.
29 */
30public final class OFMessageEncoder extends MessageToByteEncoder<Iterable<OFMessage>> {
Daniel Parkbe6b6732016-11-11 15:52:19 +090031 private final Logger log = LoggerFactory.getLogger(getClass());
Hyunsun Moon90163ba2016-10-12 13:35:14 -070032
33 @Override
34 protected void encode(ChannelHandlerContext ctx, Iterable<OFMessage> msgList, ByteBuf out)
35 throws Exception {
36
Daniel Parkbe6b6732016-11-11 15:52:19 +090037 if (!ctx.channel().isActive()) {
38 return;
39 }
40
41 if (msgList instanceof Iterable) {
42 msgList.forEach(msg -> {
43 try {
44 ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer();
45 msg.writeTo(byteBuf);
46
47 ctx.writeAndFlush(byteBuf);
48 } catch (Exception e) {
49 log.error("error occured because of {}", e.getMessage());
50 }
51 });
52 }
53 }
54
55 @Override
56 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
57 if (cause instanceof EncoderException) {
58 log.error("Connection closed because of EncoderException {}", cause.getMessage());
59 ctx.close();
60 } else {
61 log.error("Exception occured while processing encoding because of {}", cause.getMessage());
62 ctx.close();
63 }
Hyunsun Moon90163ba2016-10-12 13:35:14 -070064 }
65}