1 /* 2 * Copyright 2014 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.netty; 18 19 import static io.netty.util.CharsetUtil.UTF_8; 20 21 import com.google.common.io.ByteStreams; 22 import io.grpc.internal.ObjectPool; 23 import io.netty.buffer.ByteBuf; 24 import io.netty.buffer.Unpooled; 25 import java.io.ByteArrayOutputStream; 26 import java.io.DataOutputStream; 27 import java.io.InputStream; 28 import java.util.concurrent.Executor; 29 30 /** 31 * Utility methods for supporting Netty tests. 32 */ 33 public class NettyTestUtil { 34 toString(InputStream in)35 static String toString(InputStream in) throws Exception { 36 byte[] bytes = new byte[in.available()]; 37 ByteStreams.readFully(in, bytes); 38 return new String(bytes, UTF_8); 39 } 40 messageFrame(String message)41 static ByteBuf messageFrame(String message) throws Exception { 42 ByteArrayOutputStream os = new ByteArrayOutputStream(); 43 DataOutputStream dos = new DataOutputStream(os); 44 dos.write(message.getBytes(UTF_8)); 45 dos.close(); 46 47 // Write the compression header followed by the context frame. 48 return compressionFrame(os.toByteArray()); 49 } 50 compressionFrame(byte[] data)51 static ByteBuf compressionFrame(byte[] data) { 52 ByteBuf buf = Unpooled.buffer(); 53 buf.writeByte(0); 54 buf.writeInt(data.length); 55 buf.writeBytes(data); 56 return buf; 57 } 58 59 // A simple implementation of ObjectPool<Executor> that could track if the resource is returned. 60 public static class TrackingObjectPoolForTest implements ObjectPool<Executor> { 61 private boolean inUse; 62 TrackingObjectPoolForTest()63 public TrackingObjectPoolForTest() { } 64 65 @Override getObject()66 public Executor getObject() { 67 inUse = true; 68 return new Executor() { 69 @Override 70 public void execute(Runnable var1) { 71 var1.run(); 72 } 73 }; 74 } 75 76 @Override returnObject(Object object)77 public Executor returnObject(Object object) { 78 inUse = false; 79 return null; 80 } 81 isInUse()82 public boolean isInUse() { 83 return this.inUse; 84 } 85 } 86 } 87