<commit_before>package org.menacheri.handlers.netty;

import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandler.Sharable;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.menacheri.app.IGameRoom;
import org.menacheri.app.IPlayer;
import org.menacheri.app.IPlayerSession;
import org.menacheri.event.Events;
import org.menacheri.event.IEvent;
import org.menacheri.service.ILookupService;
import org.menacheri.service.ISessionRegistryService;
import org.menacheri.util.Credentials;
import org.menacheri.util.ICredentials;
import org.menacheri.util.NettyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Sharable
public class LoginHandler extends SimpleChannelUpstreamHandler
{
	private static final Logger LOG = LoggerFactory
			.getLogger(LoginHandler.class);

	private ILookupService lookupService;
	ISessionRegistryService sessionRegistryService;
	/**
	 * Stores reference to all connected channels to the server. This can be
	 * used for graceful shutdown later.
	 */
	public static final ChannelGroup ALL_CHANNELS = new DefaultChannelGroup("jetserver");
	/**
	 * Used for book keeping purpose. It will count all open channels. Currently
	 * closed channels will not lead to a decrement.
	 */
	private static final AtomicInteger CHANNEL_COUNTER =  new AtomicInteger(0);
	
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception
	{
		IEvent event = (IEvent)e.getMessage();
		ChannelBuffer buffer = (ChannelBuffer) event.getSource();
		Channel channel = e.getChannel();
		switch(event.getType())
		{
		case Events.LOG_IN:
			LOG.trace("Login attempt from {}",channel.getRemoteAddress());
			IPlayer player = lookupPlayer(buffer, channel);
			handleLogin(buffer, channel,player);
			break;
		}
	}

	@Override
	public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		ALL_CHANNELS.add(e.getChannel());
		LOG.debug("Added Channel with id: {} as the {}th open channel", e
				.getChannel().getId(), CHANNEL_COUNTER.incrementAndGet());
	}
	
	public IPlayer lookupPlayer(ChannelBuffer buffer, Channel channel)
	{
		ICredentials credentials = new Credentials(buffer);
		IPlayer player = lookupService.playerLookup(credentials);
		if (null != player)
		{
			channel.write(NettyUtils
					.createBufferForOpcode(Events.LOG_IN_SUCCESS));
		}
		else
		{
			// Write future and close channel
			ChannelFuture future = channel.write(NettyUtils
					.createBufferForOpcode(Events.LOG_IN_FAILURE));
			future.addListener(ChannelFutureListener.CLOSE);
			LOG.error("Invalid credentials provided by user: {}",credentials);
		}
		return player;
	}
	
	public void handleLogin(ChannelBuffer buffer, Channel channel,IPlayer player)
	{
		String refKey = NettyUtils.readString(buffer);
		
		IGameRoom gameRoom = lookupService.gameRoomLookup(refKey);
		if(null != gameRoom)
		{
			IPlayerSession playerSession = gameRoom.createPlayerSession();
			playerSession.setConnectParameter(NettyUtils.NETTY_CHANNEL,
					channel);
			gameRoom.onLogin(playerSession);
			LOG.trace("Sending GAME_ROOM_JOIN_SUCCESS to channel {}", channel.getId());
			ChannelFuture future = channel.write(NettyUtils.createBufferForOpcode(Events.GAME_ROOM_JOIN_SUCCESS));
			connectToGameRoom(gameRoom, playerSession, future);
			loginUdp(buffer, playerSession);
		}
		else
		{
			// Write failure and close channel.
			ChannelFuture future = channel.write(NettyUtils.createBufferForOpcode(Events.GAME_ROOM_JOIN_FAILURE));
			future.addListener(ChannelFutureListener.CLOSE);
			LOG.error("Invalid ref key provided by client: {}",refKey);
		}
	}
	
	public void connectToGameRoom(final IGameRoom gameRoom, final IPlayerSession playerSession, ChannelFuture future)
	{
		future.addListener(new ChannelFutureListener()
		{
			@Override
			public void operationComplete(ChannelFuture future)
					throws Exception
			{
				Channel channel = future.getChannel();<commit_msg>Refactored methods to have more meaningful names.<commit_after>package org.menacheri.handlers.netty;

import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandler.Sharable;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.menacheri.app.IGameRoom;
import org.menacheri.app.IPlayer;
import org.menacheri.app.IPlayerSession;
import org.menacheri.event.Events;
import org.menacheri.event.IEvent;
import org.menacheri.service.ILookupService;
import org.menacheri.service.ISessionRegistryService;
import org.menacheri.util.Credentials;
import org.menacheri.util.ICredentials;
import org.menacheri.util.NettyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Sharable
public class LoginHandler extends SimpleChannelUpstreamHandler
{
	private static final Logger LOG = LoggerFactory
			.getLogger(LoginHandler.class);

	private ILookupService lookupService;
	ISessionRegistryService sessionRegistryService;
	/**
	 * Stores reference to all connected channels to the server. This can be
	 * used for graceful shutdown later.
	 */
	public static final ChannelGroup ALL_CHANNELS = new DefaultChannelGroup("jetserver");
	/**
	 * Used for book keeping purpose. It will count all open channels. Currently
	 * closed channels will not lead to a decrement.
	 */
	private static final AtomicInteger CHANNEL_COUNTER =  new AtomicInteger(0);
	
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception
	{
		IEvent event = (IEvent)e.getMessage();
		ChannelBuffer buffer = (ChannelBuffer) event.getSource();
		Channel channel = e.getChannel();
		switch(event.getType())
		{
		case Events.LOG_IN:
			LOG.trace("Login attempt from {}",channel.getRemoteAddress());
			IPlayer player = lookupPlayer(buffer, channel);
			handleLogin(player,channel);
			handleGameRoomJoin(player, channel,buffer);
			break;
		default:
			LOG.error("Invalid event {} sent from remote address {}. "
					+ "Going to close channel {}",
					new Object[] { event.getType(), channel.getRemoteAddress(),
							channel.getId() });
			closeChannelWithLoginFailure(channel);
		}
	}

	@Override
	public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		ALL_CHANNELS.add(e.getChannel());
		LOG.debug("Added Channel with id: {} as the {}th open channel", e
				.getChannel().getId(), CHANNEL_COUNTER.incrementAndGet());
	}
	
	public IPlayer lookupPlayer(ChannelBuffer buffer, Channel channel)
	{
		ICredentials credentials = new Credentials(buffer);
		IPlayer player = lookupService.playerLookup(credentials);
		if(null == player){
			LOG.error("Invalid credentials provided by user: {}",credentials);
		}
		return player;
	}
	
	public void handleLogin(IPlayer player,Channel channel)
	{
		if (null != player)
		{
			channel.write(NettyUtils
					.createBufferForOpcode(Events.LOG_IN_SUCCESS));
		}
		else
		{
			// Write future and close channel
			closeChannelWithLoginFailure(channel);
		}
	}
	
	/**
	 * Helper method which will close the channel after writing
	 * {@link Events#LOG_IN_FAILURE} to remote connection.
	 * 
	 * @param channel
	 *            The tcp connection to remote machine that will be closed.
	 */
	private void closeChannelWithLoginFailure(Channel channel)
	{
		ChannelFuture future = channel.write(NettyUtils
				.createBufferForOpcode(Events.LOG_IN_FAILURE));
		future.addListener(ChannelFutureListener.CLOSE);
	}
	
	public void handleGameRoomJoin(IPlayer player, Channel channel, ChannelBuffer buffer)
	{
		String refKey = NettyUtils.readString(buffer);
		
		IGameRoom gameRoom = lookupService.gameRoomLookup(refKey);
		if(null != gameRoom)
		{
			IPlayerSession playerSession = gameRoom.createPlayerSession();
			playerSession.setConnectParameter(NettyUtils.NETTY_CHANNEL,
					channel);
			gameRoom.onLogin(playerSession);
			LOG.trace("Sending GAME_ROOM_JOIN_SUCCESS to channel {}", channel.getId());
			ChannelFuture future = channel.write(NettyUtils.createBufferForOpcode(Events.GAME_ROOM_JOIN_SUCCESS));
			connectToGameRoom(gameRoom, playerSession, future);
			loginUdp(buffer, playerSession);
		}
		else
		{
			// Write failure and close channel.
			ChannelFuture future = channel.write(NettyUtils.createBufferForOpcode(Events.GAME_ROOM_JOIN_FAILURE));
			future.addListener(ChannelFutureListener.CLOSE);
			LOG.error("Invalid ref key provided by client: {}. Channel {} will be closed",refKey,channel.getId());
		}
	}
	
	public void connectToGameRoom(final IGameRoom gameRoom, final IPlayerSession playerSession, ChannelFuture future)
	{
		future.addListener(new ChannelFutureListener()
		{
			@Override
			public void operationComplete(ChannelFuture future)
					throws Exception
			{
				Channel channel = future.getChannel();
{'fraction_non_alphanumeric': 0.09554798058051854, 'fraction_numerical': 0.0006197706848466068, 'mean_word_length': 5.198463508322663, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4045827', 'n_tokens_mistral': 3109, 'n_tokens_neox': 2828, 'n_words': 635}