Cleaning up various compiler warnings in preparation for opensource.

overview:
1) Lots of @SuppressWarnings :)

2) Remove dependencies on StandardCharsets.XXX (which is Java 7)

3) Moved testing/utils/ssl/* to .../stubby/util so that the netty transport doesn't depend directly on the testing module.
-------------
Created by MOE: http://code.google.com/p/moe-java
MOE_MIGRATED_REVID=78460727
This commit is contained in:
nathanmittler 2014-10-24 13:39:13 -07:00 committed by Eric Anderson
parent 96e6ed9c53
commit 0304b3d6b2
47 changed files with 172 additions and 138 deletions

View File

@ -11,8 +11,10 @@ import javax.annotation.Nullable;
/**
* The base class for channel builders.
*
* @param <BuilderT> The concrete type of this builder.
*/
public abstract class AbstractChannelBuilder<BuilderT extends AbstractChannelBuilder>
public abstract class AbstractChannelBuilder<BuilderT extends AbstractChannelBuilder<?>>
extends AbstractServiceBuilder<ChannelImpl, BuilderT> {
@Override

View File

@ -8,8 +8,10 @@ import java.util.concurrent.ExecutorService;
/**
* The base class for server builders.
*
* @param <BuilderT> The concrete type for this builder.
*/
public abstract class AbstractServerBuilder<BuilderT extends AbstractServerBuilder>
public abstract class AbstractServerBuilder<BuilderT extends AbstractServerBuilder<?>>
extends AbstractServiceBuilder<ServerImpl, BuilderT> {
private final HandlerRegistry registry;
@ -34,6 +36,7 @@ public abstract class AbstractServerBuilder<BuilderT extends AbstractServerBuild
* <p>This is supported only if the user didn't provide a handler registry, or the provided one is
* a {@link MutableHandlerRegistry}. Otherwise it throws an UnsupportedOperationException.
*/
@SuppressWarnings("unchecked")
public final BuilderT addService(ServerServiceDefinition service) {
if (registry instanceof MutableHandlerRegistry) {
((MutableHandlerRegistry) registry).addService(service);

View File

@ -17,9 +17,12 @@ import javax.annotation.Nullable;
* <p>The ownership rule: a builder generally does not take ownership of any objects passed to it.
* The caller is responsible for closing them if needed. The builder is only responsible for the
* life-cycle of objects created inside.
*
* @param <ProductT> The product that is built by this builder.
* @param <BuilderT> The concrete type of this builder.
*/
abstract class AbstractServiceBuilder<ProductT extends Service,
BuilderT extends AbstractServiceBuilder> {
BuilderT extends AbstractServiceBuilder<?, ?>> {
@Nullable
private ExecutorService userExecutor;
@ -33,6 +36,7 @@ abstract class AbstractServiceBuilder<ProductT extends Service,
* <p>The service won't take ownership of the given executor. It's caller's responsibility to
* shut down the executor when it's desired.
*/
@SuppressWarnings("unchecked")
public final BuilderT executor(ExecutorService executor) {
userExecutor = executor;
return (BuilderT) this;

View File

@ -16,9 +16,9 @@ public abstract class HandlerRegistry {
/** A method definition and its parent's service definition. */
public static final class Method {
private final ServerServiceDefinition serviceDef;
private final ServerMethodDefinition methodDef;
private final ServerMethodDefinition<?, ?> methodDef;
public Method(ServerServiceDefinition serviceDef, ServerMethodDefinition methodDef) {
public Method(ServerServiceDefinition serviceDef, ServerMethodDefinition<?, ?> methodDef) {
this.serviceDef = serviceDef;
this.methodDef = methodDef;
}
@ -27,7 +27,7 @@ public abstract class HandlerRegistry {
return serviceDef;
}
public ServerMethodDefinition getMethodDefinition() {
public ServerMethodDefinition<?, ?> getMethodDefinition() {
return methodDef;
}
}

View File

@ -160,7 +160,7 @@ public abstract class Metadata {
/**
* Returns true if a value is defined for the given key.
*/
public <T> boolean containsKey(Key key) {
public boolean containsKey(Key<?> key) {
return store.containsKey(key.name);
}
@ -274,13 +274,14 @@ public abstract class Metadata {
/**
* Merge values for the given set of keys into this set of metadata.
*/
public void merge(Metadata other, Set<Key> keys) {
@SuppressWarnings({"rawtypes", "unchecked"})
public void merge(Metadata other, Set<Key<?>> keys) {
Preconditions.checkNotNull(other);
for (Key key : keys) {
for (Key<?> key : keys) {
if (other.containsKey(key)) {
Iterable values = other.getAll(key);
Iterable<?> values = other.getAll(key);
for (Object value : values) {
put(key, value);
put((Key) key, value);
}
}
}
@ -350,7 +351,7 @@ public abstract class Metadata {
}
@Override
public void merge(Metadata other, Set<Key> keys) {
public void merge(Metadata other, Set<Key<?>> keys) {
super.merge(other, keys);
mergePathAndAuthority(other);
}
@ -470,7 +471,7 @@ public abstract class Metadata {
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Key key = (Key) o;
Key<?> key = (Key<?>) o;
return !(name != null ? !name.equals(key.name) : key.name != null);
}
@ -487,6 +488,8 @@ public abstract class Metadata {
private static class MetadataEntry {
Object parsed;
@SuppressWarnings("rawtypes")
Key key;
byte[] serializedBinary;
String serializedAscii;
@ -494,7 +497,7 @@ public abstract class Metadata {
/**
* Constructor used when application layer adds a parsed value.
*/
private MetadataEntry(Key key, Object parsed) {
private MetadataEntry(Key<?> key, Object parsed) {
this.parsed = Preconditions.checkNotNull(parsed);
this.key = Preconditions.checkNotNull(key);
}
@ -514,8 +517,8 @@ public abstract class Metadata {
this.serializedAscii = Preconditions.checkNotNull(serializedAscii);
}
@SuppressWarnings("unchecked")
public <T> T getParsed(Key<T> key) {
@SuppressWarnings("unchecked")
T value = (T) parsed;
if (value != null) {
if (this.key != key) {

View File

@ -3,10 +3,6 @@ package com.google.net.stubby;
import com.google.common.base.Preconditions;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import javax.annotation.concurrent.Immutable;

View File

@ -1,9 +1,5 @@
package com.google.net.stubby;
import com.google.net.stubby.ServerMethodDefinition;
import com.google.net.stubby.ServerServiceDefinition;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@ -43,7 +39,7 @@ public final class MutableHandlerRegistryImpl extends MutableHandlerRegistry {
if (service == null) {
return null;
}
ServerMethodDefinition method = service.getMethod(methodName.substring(index + 1));
ServerMethodDefinition<?, ?> method = service.getMethod(methodName.substring(index + 1));
if (method == null) {
return null;
}

View File

@ -192,11 +192,10 @@ public final class Status {
* Return a {@link Status} given a canonical error {@link Code} value.
*/
public static Status fromCodeValue(int codeValue) {
Status status;
if (codeValue < 0 || codeValue > STATUS_LIST.size()) {
return UNKNOWN.withDescription("Unknown code " + codeValue);
} else {
return status = STATUS_LIST.get(codeValue);
return STATUS_LIST.get(codeValue);
}
}

View File

@ -55,7 +55,8 @@ public abstract class ForwardingChannel implements Channel {
}
/**
* A {@link Call.Listener} which forwards all of its methods to another {@link Call.Listener}.
* A {@link com.google.net.stubby.Call.Listener} which forwards all of its methods to another
* {@link com.google.net.stubby.Call.Listener}.
*/
public static class ForwardingListener<T> extends Call.Listener<T> {

View File

@ -8,7 +8,7 @@ public interface ClientStream extends Stream {
/**
* Used to abnormally terminate the stream. After calling this method, no further messages will be
* sent or received, however it may still be possible to receive buffered messages for a brief
* period until {@link StreamListener#closed} is called.
* period until {@link ClientStreamListener#closed} is called.
*/
void cancel();

View File

@ -21,7 +21,7 @@ public interface ClientStreamListener extends StreamListener {
/**
* Called when the stream is fully closed. {@link
* com.google.net.stubby.transport.Transport.Code#OK} is the only status code that is guaranteed
* com.google.net.stubby.Status.Code#OK} is the only status code that is guaranteed
* to have been sent from the remote server. Any other status code may have been caused by
* abnormal stream termination. This is guaranteed to always be the final call on a listener. No
* further callbacks will be issued.

View File

@ -197,7 +197,7 @@ class CompressionFramer {
}
}
if (message instanceof DeferredInputStream) {
return ((DeferredInputStream) message).flushTo(outputStreamAdapter);
return ((DeferredInputStream<?>) message).flushTo(outputStreamAdapter);
} else {
// This could be optimized when compression is off, but we expect performance-critical code
// to provide a DeferredInputStream.

View File

@ -46,15 +46,14 @@ public class MessageFramer2 implements Framer {
try {
if (compression == Compression.NONE) {
writeFrame(message, messageLength, false);
} else if (compression != Compression.GZIP) {
throw new AssertionError("Unknown compression type");
} else {
// compression == GZIP
DirectAccessByteArrayOutputStream out = new DirectAccessByteArrayOutputStream();
if (compression == Compression.GZIP) {
gzipCompressTo(message, messageLength, out);
} else {
throw new AssertionError("Unknown compression type");
}
InputStream compressedMessage
= new DeferredByteArrayInputStream(out.getBuf(), 0, out.getCount());
gzipCompressTo(message, messageLength, out);
InputStream compressedMessage =
new DeferredByteArrayInputStream(out.getBuf(), 0, out.getCount());
writeFrame(compressedMessage, out.getCount(), true);
}
} catch (IOException ex) {
@ -88,6 +87,7 @@ public class MessageFramer2 implements Framer {
}
}
@SuppressWarnings("rawtypes")
private static long writeToOutputStream(InputStream message, OutputStream outputStream)
throws IOException {
if (message instanceof DeferredInputStream) {

View File

@ -14,7 +14,7 @@ public interface ServerStreamListener extends StreamListener {
/**
* Called when the stream is fully closed. A status code of {@link
* com.google.net.stubby.transport.Transport.Code#OK} implies normal termination of the stream.
* com.google.net.stubby.Status.Code#OK} implies normal termination of the stream.
* Any other value implies abnormal termination. Since clients cannot send status, the passed
* status is always library-generated and only is concerned with transport-level stream shutdown
* (the call itself may have had a failing status, but if the stream terminated cleanly with the

View File

@ -25,8 +25,7 @@ public interface Stream {
* called. The definition of what it means to be "accepted" is up to the transport implementation,
* but this is a general indication that the transport is capable of handling more out-bound data
* on the stream. If the stream/connection is closed for any reason before the write could be
* accepted, the callback will never be invoked. Any writes that are still pending upon receiving
* a {@link StreamListener#closed} callback are assumed to be cancelled.
* accepted, the callback will never be invoked.
*
* @param message stream containing the serialized message to be sent
* @param length the length of the {@link InputStream}.

View File

@ -13,7 +13,7 @@ import com.google.net.stubby.newtransport.ClientStream;
import com.google.net.stubby.newtransport.ClientStreamListener;
import com.google.net.stubby.newtransport.ClientTransport;
import com.google.net.stubby.newtransport.netty.NettyClientTransportFactory.NegotiationType;
import com.google.net.stubby.testing.utils.ssl.SslContextFactory;
import com.google.net.stubby.util.ssl.SslContextFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;

View File

@ -76,8 +76,10 @@ public final class NettyServerBuilder extends AbstractServerBuilder<NettyServerB
@Override
protected Service buildTransportServer(ServerListener serverListener) {
@SuppressWarnings("resource")
final EventLoopGroup bossEventLoopGroup = (userBossEventLoopGroup == null)
? new NioEventLoopGroup() : userBossEventLoopGroup;
@SuppressWarnings("resource")
final EventLoopGroup workerEventLoopGroup = (userWorkerEventLoopGroup == null)
? new NioEventLoopGroup() : userWorkerEventLoopGroup;
NettyServer server =

View File

@ -2,7 +2,6 @@ package com.google.net.stubby.newtransport.okhttp;
import com.google.common.util.concurrent.SettableFuture;
import com.google.net.stubby.SerializingExecutor;
import com.google.net.stubby.Status;
import com.squareup.okhttp.internal.spdy.ErrorCode;
import com.squareup.okhttp.internal.spdy.FrameWriter;

View File

@ -29,6 +29,7 @@ public class DeferredProtoInputStream extends DeferredInputStream<MessageLite> {
/**
* Returns the original protobuf message. Returns null after this stream has been read.
*/
@Override
@Nullable
public MessageLite getDeferred() {
return message;

View File

@ -1,4 +1,4 @@
package com.google.net.stubby.testing.utils.ssl;
package com.google.net.stubby.util.ssl;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
@ -19,6 +19,7 @@ public class InsecureTrustManager implements X509TrustManager {
* @throws CertificateException never, even if the certificate chain
* is invalid.
*/
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// Doing absolutely no checking of client certificate chain.
@ -31,6 +32,7 @@ public class InsecureTrustManager implements X509TrustManager {
* @throws CertificateException never, even if the certificate chain
* is invalid.
*/
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// Doing absolutely no checking of server certificate chain.
@ -39,6 +41,7 @@ public class InsecureTrustManager implements X509TrustManager {
/**
* @return null, always.
*/
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}

View File

@ -1,4 +1,4 @@
package com.google.net.stubby.testing.utils.ssl;
package com.google.net.stubby.util.ssl;
import java.security.KeyStore;

View File

@ -1,4 +1,4 @@
package com.google.net.stubby.testing.utils.ssl;
package com.google.net.stubby.util.ssl;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

View File

@ -1,5 +1,6 @@
package com.google.net.stubby;
import static com.google.common.base.Charsets.UTF_8;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -24,7 +25,7 @@ public class MetadataTest {
private static final Metadata.Marshaller<Fish> FISH_MARSHALLER = new Metadata.Marshaller<Fish>() {
@Override
public byte[] toBytes(Fish fish) {
return fish.name.getBytes(StandardCharsets.UTF_8);
return fish.name.getBytes(UTF_8);
}
@Override
@ -34,7 +35,7 @@ public class MetadataTest {
@Override
public Fish parseBytes(byte[] serialized) {
return new Fish(new String(serialized, StandardCharsets.UTF_8));
return new Fish(new String(serialized, UTF_8));
}
@Override

View File

@ -22,17 +22,23 @@ import org.mockito.Mockito;
@RunWith(JUnit4.class)
public class MutableHandlerRegistryImplTest {
private MutableHandlerRegistry registry = new MutableHandlerRegistryImpl();
@SuppressWarnings("unchecked")
private Marshaller<String> requestMarshaller = mock(Marshaller.class);
@SuppressWarnings("unchecked")
private Marshaller<Integer> responseMarshaller = mock(Marshaller.class);
@SuppressWarnings("unchecked")
private ServerCallHandler<String, Integer> handler = mock(ServerCallHandler.class);
private ServerServiceDefinition basicServiceDefinition = ServerServiceDefinition.builder("basic")
.addMethod("flow", requestMarshaller, responseMarshaller, handler).build();
.addMethod("flow", requestMarshaller, responseMarshaller, handler).build();
@SuppressWarnings("rawtypes")
private ServerMethodDefinition flowMethodDefinition = basicServiceDefinition.getMethods().get(0);
private ServerServiceDefinition multiServiceDefinition = ServerServiceDefinition.builder("multi")
.addMethod("couple", requestMarshaller, responseMarshaller, handler)
.addMethod("few", requestMarshaller, responseMarshaller, handler).build();
private ServerMethodDefinition coupleMethodDefinition
= multiServiceDefinition.getMethod("couple");
.addMethod("couple", requestMarshaller, responseMarshaller, handler)
.addMethod("few", requestMarshaller, responseMarshaller, handler).build();
@SuppressWarnings("rawtypes")
private ServerMethodDefinition coupleMethodDefinition =
multiServiceDefinition.getMethod("couple");
@SuppressWarnings("rawtypes")
private ServerMethodDefinition fewMethodDefinition = multiServiceDefinition.getMethod("few");
@After
@ -93,7 +99,8 @@ public class MutableHandlerRegistryImplTest {
assertNotNull(registry.lookupMethod("/basic.flow"));
ServerServiceDefinition replaceServiceDefinition = ServerServiceDefinition.builder("basic")
.addMethod("another", requestMarshaller, responseMarshaller, handler).build();
ServerMethodDefinition anotherMethodDefinition = replaceServiceDefinition.getMethods().get(0);
ServerMethodDefinition<?, ?> anotherMethodDefinition =
replaceServiceDefinition.getMethods().get(0);
assertSame(basicServiceDefinition, registry.addService(replaceServiceDefinition));
assertNull(registry.lookupMethod("/basic.flow"));

View File

@ -1,18 +1,18 @@
package com.google.net.stubby;
import static com.google.common.base.Charsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNull;
import static org.mockito.Matchers.notNull;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.common.base.Charsets;
import com.google.common.io.ByteStreams;
import com.google.common.util.concurrent.AbstractService;
import com.google.common.util.concurrent.ListenableFuture;
@ -21,7 +21,6 @@ import com.google.common.util.concurrent.SettableFuture;
import com.google.net.stubby.newtransport.ServerStream;
import com.google.net.stubby.newtransport.ServerStreamListener;
import com.google.net.stubby.newtransport.ServerTransportListener;
import com.google.net.stubby.newtransport.StreamListener;
import org.junit.After;
import org.junit.Before;
@ -29,18 +28,20 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
/** Unit tests for {@link ServerImpl}. */
@ -55,10 +56,14 @@ public class ServerImplTest {
private ServerImpl server = new ServerImpl(executor, registry)
.setTransportServer(transportServer);
private ServerStream stream = Mockito.mock(ServerStream.class);
private ServerCall.Listener<String> callListener = Mockito.mock(ServerCall.Listener.class);
@Mock
private ServerCall.Listener<String> callListener;
@Before
public void startup() {
MockitoAnnotations.initMocks(this);
server.startAsync();
server.awaitRunning();
}
@ -345,13 +350,13 @@ public class ServerImplTest {
private static class StringMarshaller implements Marshaller<String> {
@Override
public InputStream stream(String value) {
return new ByteArrayInputStream(value.getBytes(Charsets.UTF_8));
return new ByteArrayInputStream(value.getBytes(UTF_8));
}
@Override
public String parse(InputStream stream) {
try {
return new String(ByteStreams.toByteArray(stream), Charsets.UTF_8);
return new String(ByteStreams.toByteArray(stream), UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}

View File

@ -28,12 +28,11 @@ import java.util.List;
@RunWith(JUnit4.class)
public class ServerInterceptorsTest {
@SuppressWarnings("unchecked")
private Marshaller<String> requestMarshaller = (Marshaller<String>) mock(Marshaller.class);
private Marshaller<String> requestMarshaller = mock(Marshaller.class);
@SuppressWarnings("unchecked")
private Marshaller<Integer> responseMarshaller = (Marshaller<Integer>) mock(Marshaller.class);
private Marshaller<Integer> responseMarshaller = mock(Marshaller.class);
@SuppressWarnings("unchecked")
private ServerCallHandler<String, Integer> handler
= (ServerCallHandler<String, Integer>) mock(ServerCallHandler.class);
private ServerCallHandler<String, Integer> handler = mock(ServerCallHandler.class);
@Mock private ServerCall.Listener<String> listener;
private String methodName = "/someRandom.Name";
@Mock private ServerCall<Integer> call;
@ -63,7 +62,7 @@ public class ServerInterceptorsTest {
@Test(expected = NullPointerException.class)
public void npeForNullInterceptorList() {
ServerInterceptors.intercept(serviceDefinition, (List) null);
ServerInterceptors.intercept(serviceDefinition, (List<ServerInterceptor>) null);
}
@Test(expected = NullPointerException.class)

View File

@ -1,6 +1,6 @@
package com.google.net.stubby.newtransport;
import static java.nio.charset.StandardCharsets.UTF_8;
import static com.google.common.base.Charsets.UTF_8;
import static org.junit.Assert.assertEquals;
import org.junit.Test;

View File

@ -1,7 +1,7 @@
package com.google.net.stubby.newtransport;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.net.stubby.newtransport.Buffers.wrap;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

View File

@ -1,6 +1,6 @@
package com.google.net.stubby.newtransport;
import static java.nio.charset.StandardCharsets.UTF_8;
import static com.google.common.base.Charsets.UTF_8;
import java.nio.ByteBuffer;

View File

@ -1,6 +1,6 @@
package com.google.net.stubby.newtransport;
import static io.netty.util.CharsetUtil.UTF_8;
import static com.google.common.base.Charsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

View File

@ -2,7 +2,6 @@ package com.google.net.stubby.newtransport;
import static com.google.net.stubby.newtransport.TransportFrameUtil.PAYLOAD_FRAME;
import static com.google.net.stubby.newtransport.TransportFrameUtil.STATUS_FRAME;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
@ -15,6 +14,7 @@ import com.google.common.io.ByteStreams;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import com.google.net.stubby.Status;
import com.google.common.base.Charsets;
import com.google.protobuf.ByteString;
import org.junit.Before;
@ -161,7 +161,7 @@ public class GrpcDeframerTest {
try {
byte[] bytes = new byte[length];
ByteStreams.readFully(in, bytes);
return new String(bytes, UTF_8);
return new String(bytes, Charsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}

View File

@ -3,16 +3,19 @@ package com.google.net.stubby.newtransport;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import com.google.common.primitives.Bytes;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.io.ByteArrayInputStream;
import java.nio.ByteBuffer;
@ -25,10 +28,21 @@ import java.util.List;
public class MessageFramer2Test {
private static final int TRANSPORT_FRAME_SIZE = 12;
private Framer.Sink<List<Byte>> sink = mock(Framer.Sink.class);
private Framer.Sink<ByteBuffer> copyingSink = new ByteArrayConverterSink(sink);
private MessageFramer2 framer = new MessageFramer2(copyingSink, TRANSPORT_FRAME_SIZE);
private ArgumentCaptor<List<Byte>> frameCaptor = ArgumentCaptor.forClass((Class) List.class);
@Mock
private Framer.Sink<List<Byte>> sink;
private Framer.Sink<ByteBuffer> copyingSink;
private MessageFramer2 framer;
@Captor
private ArgumentCaptor<List<Byte>> frameCaptor;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
copyingSink = new ByteArrayConverterSink(sink);
framer = new MessageFramer2(copyingSink, TRANSPORT_FRAME_SIZE);
}
@Test
public void simplePayload() {

View File

@ -1,10 +1,10 @@
package com.google.net.stubby.newtransport.netty;
import static java.nio.charset.StandardCharsets.UTF_8;
import static com.google.common.base.Charsets.UTF_8;
import static org.junit.Assert.assertEquals;
import com.google.net.stubby.newtransport.BufferTestBase;
import com.google.net.stubby.newtransport.Buffer;
import com.google.net.stubby.newtransport.BufferTestBase;
import org.junit.Before;
import org.junit.Test;

View File

@ -1,11 +1,11 @@
package com.google.net.stubby.newtransport.netty;
import static com.google.net.stubby.newtransport.netty.Utils.CONTENT_TYPE_HEADER;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.net.stubby.newtransport.netty.Utils.CONTENT_TYPE_GRPC;
import static com.google.net.stubby.newtransport.netty.Utils.CONTENT_TYPE_HEADER;
import static com.google.net.stubby.newtransport.netty.Utils.HTTPS;
import static com.google.net.stubby.newtransport.netty.Utils.HTTP_METHOD;
import static com.google.net.stubby.newtransport.netty.Utils.STATUS_OK;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;

View File

@ -1,5 +1,6 @@
package com.google.net.stubby.newtransport.netty;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.net.stubby.newtransport.Buffers.readAsStringUtf8;
import static com.google.net.stubby.newtransport.TransportFrameUtil.COMPRESSION_HEADER_LENGTH;
import static com.google.net.stubby.newtransport.TransportFrameUtil.FLATE_FLAG;
@ -21,7 +22,6 @@ import io.netty.buffer.UnpooledByteBufAllocator;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.zip.DeflaterOutputStream;
@ -157,7 +157,7 @@ public class NettyDecompressorTest {
}
private byte[] bytes(String str) {
return str.getBytes(StandardCharsets.UTF_8);
return str.getBytes(UTF_8);
}
private byte[] compress(byte[] data) throws Exception {

View File

@ -1,11 +1,11 @@
package com.google.net.stubby.newtransport.netty;
import static com.google.net.stubby.newtransport.netty.Utils.CONTENT_TYPE_HEADER;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.net.stubby.newtransport.netty.Utils.CONTENT_TYPE_GRPC;
import static com.google.net.stubby.newtransport.netty.Utils.CONTENT_TYPE_HEADER;
import static com.google.net.stubby.newtransport.netty.Utils.HTTP_METHOD;
import static io.netty.handler.codec.http2.Http2CodecUtil.toByteBuf;
import static io.netty.handler.codec.http2.Http2Exception.protocolError;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;

View File

@ -1,15 +1,15 @@
package com.google.net.stubby.newtransport.okhttp;
import static com.google.common.base.Charsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ -45,7 +45,6 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
@ -178,7 +177,7 @@ public class OkHttpClientTransportTest {
MockStreamListener listener = new MockStreamListener();
clientTransport.newStream(method,new Metadata.Headers(), listener);
OkHttpClientStream stream = streams.get(3);
InputStream input = new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8));
InputStream input = new ByteArrayInputStream(message.getBytes(UTF_8));
assertEquals(12, input.available());
stream.writeMessage(input, input.available(), null);
stream.flush();
@ -312,7 +311,7 @@ public class OkHttpClientTransportTest {
final String sentMessage = "Should I also go away?";
OkHttpClientStream stream = streams.get(3);
InputStream input =
new ByteArrayInputStream(sentMessage.getBytes(StandardCharsets.UTF_8));
new ByteArrayInputStream(sentMessage.getBytes(UTF_8));
assertEquals(22, input.available());
stream.writeMessage(input, input.available(), null);
stream.flush();
@ -361,7 +360,7 @@ public class OkHttpClientTransportTest {
}
private static Buffer createMessageFrame(String message) {
return createMessageFrame(message.getBytes(StandardCharsets.UTF_8));
return createMessageFrame(message.getBytes(UTF_8));
}
private static Buffer createMessageFrame(byte[] message) {
@ -452,7 +451,7 @@ public class OkHttpClientTransportTest {
static String getContent(InputStream message) {
BufferedReader br =
new BufferedReader(new InputStreamReader(message, StandardCharsets.UTF_8));
new BufferedReader(new InputStreamReader(message, UTF_8));
try {
// Only one line message is used in this test.
return br.readLine();

View File

@ -1,6 +1,5 @@
package com.google.net.stubby.testing.integration;
import com.google.common.base.Randoms;
import com.google.common.collect.Lists;
import com.google.common.collect.Queues;
import com.google.net.stubby.stub.StreamObserver;
@ -33,7 +32,7 @@ public class TestServiceImpl implements TestServiceGrpc.TestService {
"/com/google/net/stubby/testing/integration/testdata/compressable.txt";
private static final String UNCOMPRESSABLE_FILE =
"/com/google/net/stubby/testing/integration/testdata/uncompressable.bin";
private final Random random = Randoms.insecureRandom();
private final Random random = new Random();
private final ScheduledExecutorService executor;
private final ByteString uncompressableBuffer;

View File

@ -3,11 +3,9 @@ package com.google.net.stubby.testing.integration;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.net.stubby.MutableHandlerRegistry;
import com.google.net.stubby.MutableHandlerRegistryImpl;
import com.google.net.stubby.ServerImpl;
import com.google.net.stubby.ServerInterceptors;
import com.google.net.stubby.newtransport.netty.NettyServer;
import com.google.net.stubby.newtransport.netty.NettyServerBuilder;
import com.google.net.stubby.testing.TestUtils;
import io.netty.handler.ssl.SslContext;
@ -181,12 +179,12 @@ public class TestServiceServer {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
}
MutableHandlerRegistry handlerRegistry = new MutableHandlerRegistryImpl();
handlerRegistry.addService(
ServerInterceptors.intercept(TestServiceGrpc.bindService(testService),
TestUtils.echoRequestHeadersInterceptor(Util.METADATA_KEY)));
server = new ServerImpl(executor, handlerRegistry);
server.setTransportServer(new NettyServer(server.serverListener(), port));
server = NettyServerBuilder.forPort(port)
.executor(executor)
.sslContext(sslContext)
.addService(ServerInterceptors.intercept(TestServiceGrpc.bindService(testService),
TestUtils.echoRequestHeadersInterceptor(Util.METADATA_KEY)))
.build();
}
@Override

View File

@ -7,16 +7,18 @@ import java.util.Map;
/**
* Base class for all stub configurations.
*
* @param <T> The concrete class type.
*/
public abstract class AbstractServiceDescriptor<T extends AbstractServiceDescriptor> {
public abstract class AbstractServiceDescriptor<T extends AbstractServiceDescriptor<?>> {
/**
* Returns the list of operations defined in the stub configuration.
*/
public abstract ImmutableList<MethodDescriptor> methods();
public abstract ImmutableList<MethodDescriptor<?, ?>> methods();
/**
* Returns a new stub configuration for the provided method configurations.
*/
protected abstract T build(Map<String, MethodDescriptor> methodMap);
protected abstract T build(Map<String, MethodDescriptor<?, ?>> methodMap);
}

View File

@ -9,11 +9,15 @@ import java.util.concurrent.TimeUnit;
/**
* Common base type for stub implementations. Allows for reconfiguration.
*
* @param <S> the concrete type of this stub.
* @param <C> the service descriptor type
*/
// TODO(user): Move into 3rd party when tidy
// TOOD(lryan/kevinb): Excessive parameterization can be a pain, try to eliminate once the generated
// TODO(lryan/kevinb): Excessive parameterization can be a pain, try to eliminate once the generated
// code is more tangible.
public abstract class AbstractStub<S extends AbstractStub, C extends AbstractServiceDescriptor<C>> {
public abstract class AbstractStub<S extends AbstractStub<?, ?>,
C extends AbstractServiceDescriptor<C>> {
protected final Channel channel;
protected final C config;
@ -47,13 +51,13 @@ public abstract class AbstractStub<S extends AbstractStub, C extends AbstractSer
*/
public class StubConfigBuilder {
private final Map<String, MethodDescriptor> methodMap;
private Channel channel;
private final Map<String, MethodDescriptor<?, ?>> methodMap;
private Channel stubChannel;
private StubConfigBuilder() {
this.channel = AbstractStub.this.channel;
this.stubChannel = AbstractStub.this.channel;
methodMap = Maps.newHashMapWithExpectedSize(config.methods().size());
for (MethodDescriptor method : AbstractStub.this.config.methods()) {
for (MethodDescriptor<?, ?> method : AbstractStub.this.config.methods()) {
methodMap.put(method.getName(), method);
}
}
@ -62,7 +66,7 @@ public abstract class AbstractStub<S extends AbstractStub, C extends AbstractSer
* Set a timeout for all methods in the stub.
*/
public StubConfigBuilder setTimeout(long timeout, TimeUnit unit) {
for (Map.Entry<String, MethodDescriptor> entry : methodMap.entrySet()) {
for (Map.Entry<String, MethodDescriptor<?, ?>> entry : methodMap.entrySet()) {
entry.setValue(entry.getValue().withTimeout(timeout, unit));
}
return this;
@ -72,7 +76,7 @@ public abstract class AbstractStub<S extends AbstractStub, C extends AbstractSer
* Set the channel to be used by the stub.
*/
public StubConfigBuilder setChannel(Channel channel) {
this.channel = channel;
this.stubChannel = channel;
return this;
}
@ -80,7 +84,7 @@ public abstract class AbstractStub<S extends AbstractStub, C extends AbstractSer
* Create a new stub configuration
*/
public S build() {
return AbstractStub.this.build(channel, config.build(methodMap));
return AbstractStub.this.build(stubChannel, config.build(methodMap));
}
}
}

View File

@ -33,7 +33,7 @@ public class Calls {
* @param method carries all invariants of the method
*/
public static <RequestT, ResponseT> MethodDescriptor<RequestT, ResponseT> createMethodDescriptor(
String fullServiceName, Method method) {
String fullServiceName, Method<RequestT, ResponseT> method) {
// TODO(user): if timeout is not defined in proto file, use a default timeout here.
// If timeout is defined in proto file, Method should carry the timeout.
return MethodDescriptor.create(method.getType(), fullServiceName + "/" + method.getName(),
@ -288,7 +288,8 @@ public class Calls {
}
/**
* Convert events on a {@link Call.Listener} into a blocking {@link Iterator}.
* Convert events on a {@link com.google.net.stubby.Call.Listener} into a blocking
* {@link Iterator}.
*
* <p>The class is not thread-safe, but it does permit Call.Listener calls in a separate thread
* from Iterator calls.

View File

@ -1,24 +1,16 @@
package com.google.net.stubby.stub;
import com.google.common.collect.ImmutableList;
import com.google.common.io.BaseEncoding;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.net.stubby.Call;
import com.google.net.stubby.Channel;
import com.google.net.stubby.Metadata;
import com.google.net.stubby.MethodDescriptor;
import com.google.net.stubby.ServerCall;
import com.google.net.stubby.ServerCallHandler;
import com.google.net.stubby.ServerInterceptor;
import com.google.net.stubby.ServerInterceptors;
import com.google.net.stubby.ServerServiceDefinition;
import com.google.net.stubby.Status;
import com.google.net.stubby.context.ForwardingChannel;
import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
/**
@ -32,7 +24,7 @@ public class MetadataUtils {
* @param extraHeaders the headers to be passed by each call on the returned stub.
* @return an implementation of the stub with extraHeaders bound to each call.
*/
@SuppressWarnings("unchecked")
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T extends AbstractStub> T attachHeaders(
T stub,
final Metadata.Headers extraHeaders) {
@ -70,7 +62,7 @@ public class MetadataUtils {
* @param trailersCapture to record the last received trailers
* @return an implementation of the stub with extraHeaders bound to each call.
*/
@SuppressWarnings("unchecked")
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T extends AbstractStub> T captureMetadata(
T stub,
AtomicReference<Metadata.Headers> headersCapture,

View File

@ -28,7 +28,7 @@ public class Method<RequestT, ResponseT> {
public static <RequestT, ResponseT> Method<RequestT, ResponseT> create(
MethodType type, String name,
Marshaller<RequestT> requestMarshaller, Marshaller<ResponseT> responseMarshaller) {
return new Method(type, name, requestMarshaller, responseMarshaller);
return new Method<RequestT, ResponseT>(type, name, requestMarshaller, responseMarshaller);
}
private Method(MethodType type, String name, Marshaller<RequestT> requestMarshaller,

View File

@ -16,7 +16,7 @@ public class ServerCalls {
}
public static <ReqT, RespT> ServerMethodDefinition<ReqT, RespT> createMethodDefinition(
Method method, ServerCallHandler<ReqT, RespT> handler) {
Method<ReqT, RespT> method, ServerCallHandler<ReqT, RespT> handler) {
return ServerMethodDefinition.create(method.getName(), method.getRequestMarshaller(),
method.getResponseMarshaller(), handler);
}
@ -27,7 +27,7 @@ public class ServerCalls {
@Override
public ServerCall.Listener<ReqT> startCall(
String fullMethodName, final ServerCall<RespT> call, Metadata.Headers headers) {
final ResponseObserver responseObserver = new ResponseObserver<RespT>(call);
final ResponseObserver<RespT> responseObserver = new ResponseObserver<RespT>(call);
return new EmptyServerCallListener<ReqT>() {
ReqT request;
@Override
@ -70,7 +70,7 @@ public class ServerCalls {
@Override
public ServerCall.Listener<ReqT> startCall(String fullMethodName, ServerCall<RespT> call,
Metadata.Headers headers) {
final ResponseObserver responseObserver = new ResponseObserver<RespT>(call);
final ResponseObserver<RespT> responseObserver = new ResponseObserver<RespT>(call);
final StreamObserver<ReqT> requestObserver = method.invoke(responseObserver);
return new EmptyServerCallListener<ReqT>() {
boolean halfClosed = false;

View File

@ -89,10 +89,12 @@ public class InProcessUtils {
return new NoOpClientStream();
}
@SuppressWarnings("rawtypes")
final ServerMethodDefinition serverMethod = resolvedMethod.getMethodDefinition();
final AtomicBoolean cancelled = new AtomicBoolean();
// Implementation of ServerCall which delegates to the client listener.
@SuppressWarnings("rawtypes")
final ServerCall serverCall = new ServerCall() {
@Override
@ -113,6 +115,7 @@ public class InProcessUtils {
try {
// TODO(user): Consider adapting at the Channel layer on the client
// so we avoid serialization costs.
@SuppressWarnings("unchecked")
InputStream message = serverMethod.streamResponse(payload);
clientListener.messageRead(message, message.available());
} catch (IOException ioe) {
@ -140,6 +143,7 @@ public class InProcessUtils {
};
// Get the listener from the service implementation
@SuppressWarnings({"rawtypes", "unchecked"})
final ServerCall.Listener serverListener =
serverMethod.getServerCallHandler().startCall(method.getName(),
serverCall, headers);
@ -181,6 +185,7 @@ public class InProcessUtils {
public void writeMessage(final InputStream message, int length,
@Nullable final Runnable accepted) {
serverWorkQueue.execute(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
try {

View File

@ -20,8 +20,8 @@ public class TestUtils {
* Echo the request headers from a client into response headers and trailers. Useful for
* testing end-to-end metadata propagation.
*/
public static ServerInterceptor echoRequestHeadersInterceptor(Metadata.Key... keys) {
final Set<Metadata.Key> keySet = new HashSet<Metadata.Key>(Arrays.asList(keys));
public static ServerInterceptor echoRequestHeadersInterceptor(final Metadata.Key<?>... keys) {
final Set<Metadata.Key<?>> keySet = new HashSet<Metadata.Key<?>>(Arrays.asList(keys));
return new ServerInterceptor() {
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(String method,