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

io.axoniq.axonserver.connector.impl.HeaderAttachingInterceptor Maven / Gradle / Ivy

There is a newer version: 2024.1.1
Show newest version
/*
 * Copyright (c) 2020. AxonIQ
 *
 * 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 io.axoniq.axonserver.connector.impl;

import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ForwardingClientCall;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;

/**
 * Interceptor around a gRPC request to add header information as metadata to a message.
 *
 * @param  the key and value type of the header this interceptor will attach
 * @author Marc Gathier
 * @since 4.0
 */
public class HeaderAttachingInterceptor implements ClientInterceptor {

    private final Metadata.Key header;
    private final T value;

    /**
     * Constructs a {@link HeaderAttachingInterceptor} attaching metadata using the given {@code header} as key, paired
     * with the given {@code value}
     *
     * @param header the {@link Metadata.Key} to attach on intercepted messages
     * @param value  the object of type {@code T} to attach on intercepted messages
     */
    public HeaderAttachingInterceptor(Metadata.Key header, T value) {
        this.header = header;
        this.value = value;
    }

    @Override
    public  ClientCall interceptCall(MethodDescriptor methodDescriptor,
                                                           CallOptions callOptions,
                                                           Channel channel) {
        ClientCall call = channel.newCall(methodDescriptor, callOptions);
        return value == null ? call : new HeaderAttachedCall<>(call);
    }

    private class HeaderAttachedCall extends ForwardingClientCall.SimpleForwardingClientCall {

        public HeaderAttachedCall(ClientCall call) {
            super(call);
        }

        @Override
        public void start(Listener responseListener, Metadata headers) {
            headers.put(header, value);
            super.start(responseListener, headers);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy