1 /* 2 * Copyright 2015 The gRPC Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package io.grpc.examples.header; 18 19 import com.google.common.annotations.VisibleForTesting; 20 import io.grpc.ForwardingServerCall.SimpleForwardingServerCall; 21 import io.grpc.Metadata; 22 import io.grpc.ServerCall; 23 import io.grpc.ServerCallHandler; 24 import io.grpc.ServerInterceptor; 25 import java.util.logging.Logger; 26 27 /** 28 * A interceptor to handle server header. 29 */ 30 public class HeaderServerInterceptor implements ServerInterceptor { 31 32 private static final Logger logger = Logger.getLogger(HeaderServerInterceptor.class.getName()); 33 34 @VisibleForTesting 35 static final Metadata.Key<String> CUSTOM_HEADER_KEY = 36 Metadata.Key.of("custom_server_header_key", Metadata.ASCII_STRING_MARSHALLER); 37 38 39 @Override interceptCall( ServerCall<ReqT, RespT> call, final Metadata requestHeaders, ServerCallHandler<ReqT, RespT> next)40 public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall( 41 ServerCall<ReqT, RespT> call, 42 final Metadata requestHeaders, 43 ServerCallHandler<ReqT, RespT> next) { 44 logger.info("header received from client:" + requestHeaders); 45 return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) { 46 @Override 47 public void sendHeaders(Metadata responseHeaders) { 48 responseHeaders.put(CUSTOM_HEADER_KEY, "customRespondValue"); 49 super.sendHeaders(responseHeaders); 50 } 51 }, requestHeaders); 52 } 53 } 54