<commit_before>package com.tesora.dve.db.mysql.portal.protocol;

/*
 * #%L
 * Tesora Inc.
 * Database Virtualization Engine
 * %%
 * Copyright (C) 2011 - 2014 Tesora Inc.
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 * 
 * 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 Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * #L%
 */


import com.tesora.dve.db.mysql.MysqlMessage;
import com.tesora.dve.db.mysql.libmy.MyMessage;
import com.tesora.dve.db.mysql.libmy.MyResponseMessage;
import com.tesora.dve.exceptions.PESQLStateException;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.EncoderException;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.PlatformDependent;

import java.nio.ByteOrder;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.log4j.Logger;

import com.tesora.dve.exceptions.PEException;

public class MSPEncoder extends MessageToByteEncoder<MysqlMessage> {
    private static final Logger logger = Logger.getLogger(MSPEncoder.class);
    public static final int SLAB_SIZE = 1024 * 8;//start with a 8K slab for transcoding outbound writes.

    static boolean PREFER_DIRECT = PlatformDependent.directBufferPreferred();

    ByteBuf cachedSlab;

    @Override
    protected void encode(ChannelHandlerContext ctx, MysqlMessage msg, ByteBuf out) throws Exception {
        ByteBuf leBuf = out.order(ByteOrder.LITTLE_ENDIAN);

        if (msg instanceof MyMessage)
            encodeMyMessage(leBuf, (MyMessage)msg);
        else
            encodeMSPMessage((MSPMessage)msg,leBuf);
    }

    protected void encodeMSPMessage(MSPMessage msg, ByteBuf littleEnd) throws Exception {
        msg.writeTo(littleEnd);
    }



    private void allocateSlabIfNeeded(ChannelHandlerContext ctx) {
        if (cachedSlab != null) //we already have a slab.
            return;

        if (PREFER_DIRECT) {
            cachedSlab = ctx.alloc().ioBuffer(SLAB_SIZE);
        } else {
            cachedSlab = ctx.alloc().heapBuffer(SLAB_SIZE);
        }

        cachedSlab = cachedSlab.order(ByteOrder.LITTLE_ENDIAN);
    }

    private void releaseSlab() {
        ReferenceCountUtil.release(cachedSlab);
        cachedSlab = null;
    }

    @Override
    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        try {
            super.disconnect(ctx,promise);
        } finally {
            releaseSlab();
        }
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        try {
            super.handlerRemoved(ctx);
        } finally {
            releaseSlab();
        }
    }

    // Taken from Netty so that we can control the size and location of the
	// buffer we allocate
	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		try {
			if (acceptOutboundMessage(msg)) {
				@SuppressWarnings("unchecked")<commit_msg>Make sure MSPEncoder decrements ref count for all written messages.<commit_after>package com.tesora.dve.db.mysql.portal.protocol;

/*
 * #%L
 * Tesora Inc.
 * Database Virtualization Engine
 * %%
 * Copyright (C) 2011 - 2014 Tesora Inc.
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 * 
 * 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 Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * #L%
 */


import com.tesora.dve.db.mysql.MysqlMessage;
import com.tesora.dve.db.mysql.libmy.MyMessage;
import com.tesora.dve.db.mysql.libmy.MyResponseMessage;
import com.tesora.dve.exceptions.PESQLStateException;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.EncoderException;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.PlatformDependent;

import java.nio.ByteOrder;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.log4j.Logger;

import com.tesora.dve.exceptions.PEException;

public class MSPEncoder extends MessageToByteEncoder<MysqlMessage> {
    private static final Logger logger = Logger.getLogger(MSPEncoder.class);
    public static final int SLAB_SIZE = 1024 * 8;//start with a 8K slab for transcoding outbound writes.

    static boolean PREFER_DIRECT = PlatformDependent.directBufferPreferred();

    ByteBuf cachedSlab;

    @Override
    protected void encode(ChannelHandlerContext ctx, MysqlMessage msg, ByteBuf out) throws Exception {
        ByteBuf leBuf = out.order(ByteOrder.LITTLE_ENDIAN);

        try{
            if (msg instanceof MyMessage)
                encodeMyMessage(leBuf, (MyMessage)msg);
            else
                encodeMSPMessage((MSPMessage)msg,leBuf);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    protected void encodeMSPMessage(MSPMessage msg, ByteBuf littleEnd) throws Exception {
        msg.writeTo(littleEnd);
    }



    private void allocateSlabIfNeeded(ChannelHandlerContext ctx) {
        if (cachedSlab != null) //we already have a slab.
            return;

        if (PREFER_DIRECT) {
            cachedSlab = ctx.alloc().ioBuffer(SLAB_SIZE);
        } else {
            cachedSlab = ctx.alloc().heapBuffer(SLAB_SIZE);
        }

        cachedSlab = cachedSlab.order(ByteOrder.LITTLE_ENDIAN);
    }

    private void releaseSlab() {
        ReferenceCountUtil.release(cachedSlab);
        cachedSlab = null;
    }

    @Override
    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        try {
            super.disconnect(ctx, promise);
        } finally {
            releaseSlab();
        }
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        try {
            super.handlerRemoved(ctx);
        } finally {
            releaseSlab();
        }
    }

    // Taken from Netty so that we can control the size and location of the
	// buffer we allocate
	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		try {
			if (acceptOutboundMessage(msg)) {
				@SuppressWarnings("unchecked")
{'fraction_non_alphanumeric': 0.08475968779953444, 'fraction_numerical': 0.004381760920169793, 'mean_word_length': 3.200115008625647, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '3321201', 'n_tokens_mistral': 2142, 'n_tokens_neox': 2048, 'n_words': 582}