All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.apache.kafka.common.requests.KopResponseUtils Maven / Gradle / Ivy

There is a newer version: 4.0.0.4
Show newest version
/**
 * 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.apache.kafka.common.requests;

import io.netty.buffer.ByteBuf;
import java.nio.ByteBuffer;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.protocol.ByteBufferAccessor;
import org.apache.kafka.common.protocol.Message;
import org.apache.kafka.common.protocol.ObjectSerializationCache;
import org.apache.pulsar.common.allocator.PulsarByteBufAllocator;

/**
 * Provide util classes to access protected fields in kafka structures.
 */
@Slf4j
public class KopResponseUtils {

    /**
     * Serialize a kafka response into a byte buf.
     * @param version
     * @param responseHeader
     * @param response
     * @return
     */
    public static ByteBuf serializeResponse(short version,
                                            ResponseHeader responseHeader,
                                            AbstractResponse response) {
        return serialize(responseHeader.data(), responseHeader.headerVersion(), response.data(), version);
    }

    public static ByteBuffer serializeRequest(RequestHeader requestHeader, AbstractRequest request) {
        return RequestUtils.serialize(requestHeader.data(), requestHeader.headerVersion(),
                request.data(), request.version());
    }

    public static ByteBuf serializeRequestToPooledBuffer(RequestHeader header, AbstractRequest request) {
        return serialize(header.data(), header.headerVersion(), request.data(), request.version());
    }

    private static ByteBuf serialize(Message header, short headerVersion, Message apiMessage, short apiVersion) {
        final var cache = new ObjectSerializationCache();
        int headerSize = header.size(cache, headerVersion);
        int messageSize = apiMessage.size(cache, apiVersion);
        final var buffer = PulsarByteBufAllocator.DEFAULT.buffer(headerSize + messageSize);
        buffer.writerIndex(headerSize + messageSize);
        final var nioBuffer = buffer.nioBuffer();
        final var writable = new ByteBufferAccessor(nioBuffer);
        header.write(writable, cache, headerVersion);
        apiMessage.write(writable, cache, apiVersion);
        return buffer;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy