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; 18 19 import static com.google.common.base.Preconditions.checkArgument; 20 21 import com.google.common.annotations.VisibleForTesting; 22 import java.util.concurrent.ConcurrentHashMap; 23 import java.util.concurrent.ConcurrentMap; 24 import javax.annotation.Nullable; 25 import javax.annotation.concurrent.ThreadSafe; 26 27 /** 28 * Encloses classes related to the compression and decompression of messages. 29 */ 30 @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1704") 31 @ThreadSafe 32 public final class CompressorRegistry { 33 private static final CompressorRegistry DEFAULT_INSTANCE = new CompressorRegistry( 34 new Codec.Gzip(), 35 Codec.Identity.NONE); 36 37 /** 38 * Returns the default instance used by gRPC when the registry is not specified. 39 * Currently the registry just contains support for gzip. 40 */ getDefaultInstance()41 public static CompressorRegistry getDefaultInstance() { 42 return DEFAULT_INSTANCE; 43 } 44 45 /** 46 * Returns a new instance with no registered compressors. 47 */ newEmptyInstance()48 public static CompressorRegistry newEmptyInstance() { 49 return new CompressorRegistry(); 50 } 51 52 private final ConcurrentMap<String, Compressor> compressors; 53 54 @VisibleForTesting CompressorRegistry(Compressor ....cs)55 CompressorRegistry(Compressor ...cs) { 56 compressors = new ConcurrentHashMap<String, Compressor>(); 57 for (Compressor c : cs) { 58 compressors.put(c.getMessageEncoding(), c); 59 } 60 } 61 62 @Nullable lookupCompressor(String compressorName)63 public Compressor lookupCompressor(String compressorName) { 64 return compressors.get(compressorName); 65 } 66 67 /** 68 * Registers a compressor for both decompression and message encoding negotiation. 69 * 70 * @param c The compressor to register 71 */ register(Compressor c)72 public void register(Compressor c) { 73 String encoding = c.getMessageEncoding(); 74 checkArgument(!encoding.contains(","), "Comma is currently not allowed in message encoding"); 75 compressors.put(encoding, c); 76 } 77 } 78