org.aotorrent.client.OutboundHandshakeHandler.java Source code

Java tutorial

Introduction

Here is the source code for org.aotorrent.client.OutboundHandshakeHandler.java

Source

/*
 * Copyright 2014 Napolov Dmitry
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.aotorrent.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import org.aotorrent.common.TorrentEngine;
import org.aotorrent.common.connection.PeerConnection;
import org.aotorrent.common.protocol.peer.HandshakeRequest;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author dmitry 16.07.14 1:18
 */
class OutboundHandshakeHandler extends SimpleChannelInboundHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(OutboundHandshakeHandler.class);

    private final TorrentEngine torrentEngine;
    private boolean handshakeDone = false;

    public OutboundHandshakeHandler(TorrentEngine torrentEngine) {
        super(false);
        this.torrentEngine = torrentEngine;
    }

    @Override
    protected synchronized void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        final ByteBuf buf = (ByteBuf) msg;

        if (handshakeDone) {
            super.channelRead(ctx, msg);
            return;
        }

        try {

            HandshakeRequest handshakeRequest = new HandshakeRequest(buf);

            if (ArrayUtils.isEquals(handshakeRequest.getInfoHash(), torrentEngine.getInfoHash())) {
                handshakeDone = true;
                PeerConnection peerConnection = new PeerConnection(torrentEngine, ctx);
                torrentEngine.registerConnection(ctx.channel().remoteAddress(), peerConnection);
                final ChannelPipeline pipeline = ctx.pipeline();
                pipeline.addLast("peerConnection", peerConnection);
                pipeline.remove(this);
                ByteBuf out = ((ByteBuf) msg).copy();
                ctx.fireChannelRead(out);
                peerConnection.sendBitField();
            }

        } finally {
            buf.release();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.error("Handshake failed: ", cause);
    }
}