<commit_before>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

package com.microsoft.signalr.messagepack;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.msgpack.core.MessageBufferPacker;
import org.msgpack.core.MessageFormat;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessagePackException;
import org.msgpack.core.MessagePacker;
import org.msgpack.core.MessageUnpacker;
import org.msgpack.jackson.dataformat.MessagePackFactory;
import org.msgpack.value.ValueType;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

import com.microsoft.signalr.CancelInvocationMessage;
import com.microsoft.signalr.CloseMessage;
import com.microsoft.signalr.CompletionMessage;
import com.microsoft.signalr.HubMessage;
import com.microsoft.signalr.HubMessageType;
import com.microsoft.signalr.HubProtocol;
import com.microsoft.signalr.InvocationBinder;
import com.microsoft.signalr.InvocationBindingFailureMessage;
import com.microsoft.signalr.InvocationMessage;
import com.microsoft.signalr.PingMessage;
import com.microsoft.signalr.StreamBindingFailureMessage;
import com.microsoft.signalr.StreamInvocationMessage;
import com.microsoft.signalr.StreamItem;

public class MessagePackHubProtocol implements HubProtocol {
    
    private static final int ERROR_RESULT = 1;
    private static final int VOID_RESULT = 2;
    private static final int NON_VOID_RESULT = 3;
    
    private ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
    private TypeFactory typeFactory = objectMapper.getTypeFactory();

    @Override
    public String getName() {
        return "messagepack";
    }

    @Override
    public int getVersion() {
        return 1;
    }

    @Override
    public List<HubMessage> parseMessages(ByteBuffer payload, InvocationBinder binder) {
        if (payload.remaining() == 0) {
            return null;
        }
        
         // MessagePack library can't handle read-only ByteBuffer - copy into an array-backed ByteBuffer if this is the case
        if (payload.isReadOnly()) {
            byte[] payloadBytes = new byte[payload.remaining()];
            payload.get(payloadBytes, 0, payloadBytes.length);
            payload = ByteBuffer.wrap(payloadBytes);
        }

        List<HubMessage> hubMessages = new ArrayList<>();
        
        while (payload.hasRemaining()) {
            int length;
            try {
                length = Utils.readLengthHeader(payload);
                // Throw if remaining buffer is shorter than length header
                if (payload.remaining() < length) {
                    throw new RuntimeException(String.format("MessagePack message was length %d but claimed to be length %d.", payload.remaining(), length));
                }
            } catch (IOException ex) {
                throw new RuntimeException("Error reading length header.", ex);
            }
            // Instantiate MessageUnpacker
            try(MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(payload)) {

                int itemCount = unpacker.unpackArrayHeader();
                HubMessageType messageType = HubMessageType.values()[unpacker.unpackInt() - 1];

                switch (messageType) {
                    case INVOCATION:
                        hubMessages.add(createInvocationMessage(unpacker, binder, itemCount, payload));
                        break;
                    case STREAM_ITEM:
                        hubMessages.add(createStreamItemMessage(unpacker, binder, payload));
                        break;
                    case COMPLETION:
                        hubMessages.add(createCompletionMessage(unpacker, binder, payload));
                        break;
                    case STREAM_INVOCATION:
                        hubMessages.add(createStreamInvocationMessage(unpacker, binder, itemCount, payload));
                        break;
                    case CANCEL_INVOCATION:
                        hubMessages.add(createCancelInvocationMessage(unpacker));
                        break;
                    case PING:
                        hubMessages.add(PingMessage.getInstance());
                        break;
                    case CLOSE:
                        hubMessages.add(createCloseMessage(unpacker, itemCount));
                        break;
                    default:
                        break;
                }
                // Make sure that we actually read the right number of bytes
                int readBytes = (int) unpacker.getTotalReadBytes();
                if (readBytes != length) {
                    // Check what the last message was
                    // If it was an invocation binding failure, we have to correct the position of the buffer
                    if (hubMessages.get(hubMessages.size() - 1).getMessageType() == HubMessageType.INVOCATION_BINDING_FAILURE) {
                        payload.position(payload.position() + (length - readBytes));
                    } else {
                        throw new RuntimeException(String.format("MessagePack message was length %d but claimed to be length %d.", readBytes, length));
                    }
                }
                unpacker.close();
                payload.position(payload.position() + readBytes);
            } catch (MessagePackException | IOException ex) {
                throw new RuntimeException("Error reading MessagePack data.", ex);
            }
        }
        return hubMessages;
    }
    
    @Override
    public ByteBuffer writeMessage(HubMessage hubMessage) {<commit_msg>Cast ByteBuffer to Buffer before calling position(int) (#26614)<commit_after>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

package com.microsoft.signalr.messagepack;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.msgpack.core.MessageBufferPacker;
import org.msgpack.core.MessageFormat;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessagePackException;
import org.msgpack.core.MessagePacker;
import org.msgpack.core.MessageUnpacker;
import org.msgpack.jackson.dataformat.MessagePackFactory;
import org.msgpack.value.ValueType;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

import com.microsoft.signalr.CancelInvocationMessage;
import com.microsoft.signalr.CloseMessage;
import com.microsoft.signalr.CompletionMessage;
import com.microsoft.signalr.HubMessage;
import com.microsoft.signalr.HubMessageType;
import com.microsoft.signalr.HubProtocol;
import com.microsoft.signalr.InvocationBinder;
import com.microsoft.signalr.InvocationBindingFailureMessage;
import com.microsoft.signalr.InvocationMessage;
import com.microsoft.signalr.PingMessage;
import com.microsoft.signalr.StreamBindingFailureMessage;
import com.microsoft.signalr.StreamInvocationMessage;
import com.microsoft.signalr.StreamItem;

public class MessagePackHubProtocol implements HubProtocol {
    
    private static final int ERROR_RESULT = 1;
    private static final int VOID_RESULT = 2;
    private static final int NON_VOID_RESULT = 3;
    
    private ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
    private TypeFactory typeFactory = objectMapper.getTypeFactory();

    @Override
    public String getName() {
        return "messagepack";
    }

    @Override
    public int getVersion() {
        return 1;
    }

    @Override
    public List<HubMessage> parseMessages(ByteBuffer payload, InvocationBinder binder) {
        if (payload.remaining() == 0) {
            return null;
        }
        
         // MessagePack library can't handle read-only ByteBuffer - copy into an array-backed ByteBuffer if this is the case
        if (payload.isReadOnly()) {
            byte[] payloadBytes = new byte[payload.remaining()];
            payload.get(payloadBytes, 0, payloadBytes.length);
            payload = ByteBuffer.wrap(payloadBytes);
        }

        List<HubMessage> hubMessages = new ArrayList<>();
        
        while (payload.hasRemaining()) {
            int length;
            try {
                length = Utils.readLengthHeader(payload);
                // Throw if remaining buffer is shorter than length header
                if (payload.remaining() < length) {
                    throw new RuntimeException(String.format("MessagePack message was length %d but claimed to be length %d.", payload.remaining(), length));
                }
            } catch (IOException ex) {
                throw new RuntimeException("Error reading length header.", ex);
            }
            // Instantiate MessageUnpacker
            try(MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(payload)) {

                int itemCount = unpacker.unpackArrayHeader();
                HubMessageType messageType = HubMessageType.values()[unpacker.unpackInt() - 1];

                switch (messageType) {
                    case INVOCATION:
                        hubMessages.add(createInvocationMessage(unpacker, binder, itemCount, payload));
                        break;
                    case STREAM_ITEM:
                        hubMessages.add(createStreamItemMessage(unpacker, binder, payload));
                        break;
                    case COMPLETION:
                        hubMessages.add(createCompletionMessage(unpacker, binder, payload));
                        break;
                    case STREAM_INVOCATION:
                        hubMessages.add(createStreamInvocationMessage(unpacker, binder, itemCount, payload));
                        break;
                    case CANCEL_INVOCATION:
                        hubMessages.add(createCancelInvocationMessage(unpacker));
                        break;
                    case PING:
                        hubMessages.add(PingMessage.getInstance());
                        break;
                    case CLOSE:
                        hubMessages.add(createCloseMessage(unpacker, itemCount));
                        break;
                    default:
                        break;
                }
                // Make sure that we actually read the right number of bytes
                int readBytes = (int) unpacker.getTotalReadBytes();
                if (readBytes != length) {
                    // Check what the last message was
                    // If it was an invocation binding failure, we have to correct the position of the buffer
                    if (hubMessages.get(hubMessages.size() - 1).getMessageType() == HubMessageType.INVOCATION_BINDING_FAILURE) {
                        // Cast to a Buffer to avoid the Java 9+ behavior where ByteBuffer.position(int) overrides Buffer.position(int),
                        // Returning a ByteBuffer rather than a Buffer. This causes issues on Android - see https://github.com/dotnet/aspnetcore/pull/26614
                        ((Buffer) payload).position(payload.position() + (length - readBytes));
                    } else {
                        throw new RuntimeException(String.format("MessagePack message was length %d but claimed to be length %d.", readBytes, length));
                    }
                }
                unpacker.close();
                // Cast to a Buffer to avoid the Java 9+ behavior where ByteBuffer.position(int) overrides Buffer.position(int),
                // Returning a ByteBuffer rather than a Buffer. This causes issues on Android - see https://github.com/dotnet/aspnetcore/pull/26614
                ((Buffer) payload).position(payload.position() + readBytes);
            } catch (MessagePackException | IOException ex) {
                throw new RuntimeException("Error reading MessagePack data.", ex);
            }
        }
        return hubMessages;
    }
    
    @Override
    public ByteBuffer writeMessage(HubMessage hubMessage) {
{'fraction_non_alphanumeric': 0.08138238573021182, 'fraction_numerical': 0.002946329033285555, 'mean_word_length': 2.1956743002544528, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 9, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 4}, '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': '7493864', 'n_tokens_mistral': 3185, 'n_tokens_neox': 2979, 'n_words': 789}