Java tutorial
/* * Copyright (C) 2015 An Honest Effort LLC, coping. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.anhonesteffort.chnlbrkr.stream; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import org.anhonesteffort.chnlzr.CapnpUtil; import org.anhonesteffort.chnlzr.WriteQueuingContext; import org.capnproto.MessageBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.anhonesteffort.chnlzr.Proto.BaseMessage; import static org.anhonesteffort.chnlzr.Proto.Error; public class ChannelStreamer extends ChannelHandlerAdapter { private static final Logger log = LoggerFactory.getLogger(ChannelStreamer.class); private final WriteQueuingContext client; private final String chnlzrId; protected ChannelStreamer(ChannelHandlerContext chnlzr, WriteQueuingContext client, MessageBuilder capabilities, MessageBuilder channelState, String chnlzrId) { this.client = client; this.chnlzrId = chnlzrId; client.getCloseFuture().addListener(close -> chnlzr.close()); chnlzr.channel().closeFuture().addListener(close -> client.close()); client.writeOrQueue(capabilities); client.writeOrQueue(channelState); } @Override public void channelRead(ChannelHandlerContext chnlzr, Object msg) { BaseMessage.Reader message = (BaseMessage.Reader) msg; switch (message.getType()) { case CHANNEL_STATE: case SAMPLES: case ERROR: client.writeOrQueue(CapnpUtil.builder(message)); break; default: log.warn(chnlzrId + " chnlzr sent unexpected " + message.getType().name()); client.writeAndClose(CapnpUtil.error(Error.ERROR_UNKNOWN)); chnlzr.close(); } } @Override public void exceptionCaught(ChannelHandlerContext chnlzr, Throwable cause) { log.error(chnlzrId + " caught unexpected exception", cause); client.writeAndClose(CapnpUtil.error(Error.ERROR_UNKNOWN)); chnlzr.close(); } }