Skip to content

Commit

Permalink
core: preserve KnownLength when wrapping InputStream (grpc#6852)
Browse files Browse the repository at this point in the history
useInputStreamMessages ensures that the InputStream supports marking by wrapping the stream in a BufferedInputStream if markSupported() returns false. This change uses a new subclass of BufferedInputStream that also implements KnownLength, when the original stream also implements KnownLength.
  • Loading branch information
herbyderby authored and dfawley committed Jan 15, 2021
1 parent d8f630f commit 6f41885
Showing 1 changed file with 23 additions and 13 deletions.
36 changes: 23 additions & 13 deletions api/src/main/java/io/grpc/ServerInterceptors.java
Expand Up @@ -139,24 +139,34 @@ public static ServerServiceDefinition useInputStreamMessages(
final ServerServiceDefinition serviceDef) {
final MethodDescriptor.Marshaller<InputStream> marshaller =
new MethodDescriptor.Marshaller<InputStream>() {
@Override
public InputStream stream(final InputStream value) {
return value;
}
@Override
public InputStream stream(final InputStream value) {
return value;
}

@Override
public InputStream parse(final InputStream stream) {
if (stream.markSupported()) {
return stream;
} else {
return new BufferedInputStream(stream);
}
}
};
@Override
public InputStream parse(final InputStream stream) {
if (stream.markSupported()) {
return stream;
} else if (stream instanceof KnownLength) {
return new KnownLengthBufferedInputStream(stream);
} else {
return new BufferedInputStream(stream);
}
}
};

return useMarshalledMessages(serviceDef, marshaller);
}

/** {@link BufferedInputStream} that also implements {@link KnownLength}. */
private static final class KnownLengthBufferedInputStream extends BufferedInputStream
implements KnownLength {
KnownLengthBufferedInputStream(InputStream in) {
super(in);
}
}

/**
* Create a new {@code ServerServiceDefinition} whose {@link MethodDescriptor} serializes to
* and from T for all methods. The {@code ServerCallHandler} created will automatically
Expand Down

0 comments on commit 6f41885

Please sign in to comment.