id stringlengths 29 30 | content stringlengths 152 2.6k |
|---|---|
codereview_new_java_data_8147 | public void processHeaders(HttpHeaders headers, StreamDecoderOutput<DeframedMess
}
}
- final Metadata metadata = MetadataUtil.copyFromHeaders(headers);
- // Note: this implementation slightly differs from upstream in that
- // we don't check if the content-type is valid before invoking this callback.
- transportStatusListener.transportReportHeaders(metadata);
}
@Override
A `ResposneHeaders` containing `grpcStatus`, trailers-only response may reach here.
Should we add a condition for that?
public void processHeaders(HttpHeaders headers, StreamDecoderOutput<DeframedMess
}
}
+ if (grpcStatus == null) {
+ // exclude trailers-only responses from triggering the callback
+ final Metadata metadata = MetadataUtil.copyFromHeaders(headers);
+ // Note: this implementation slightly differs from upstream in that
+ // we don't check if the content-type is valid before invoking this callback.
+ transportStatusListener.transportReportHeaders(metadata);
+ }
}
@Override |
codereview_new_java_data_8148 |
import io.grpc.Status;
/**
- * A listener of gRPC {@link Status}s. Any errors occurring within the armeria will be returned to gRPC business
- * logic through this listener, and for clients the final response {@link Status} is also returned.
*/
public interface TransportStatusListener {
default void transportReportHeaders(Metadata metadata) {}
This is not relevant to the change of this PR, but could you add `@FuntionalInterface` to the interface?
Could you also update the description?
import io.grpc.Status;
/**
+ * A listener of gRPC {@link Status}s. Error or header events will be returned to gRPC business
+ * logic through this listener. For clients the final response {@link Status} is also returned.
*/
+@FunctionalInterface
public interface TransportStatusListener {
default void transportReportHeaders(Metadata metadata) {} |
codereview_new_java_data_8149 | public InetAddress getAddress() {
/**
* Registers a Network address that the {@link Server} uses.
*/
- public void setAddress(InetAddress address) {
this.address = address;
}
/**
Should return `this` like other setters?
public InetAddress getAddress() {
/**
* Registers a Network address that the {@link Server} uses.
*/
+ public Port setAddress(InetAddress address) {
this.address = address;
+ return this;
}
/** |
codereview_new_java_data_8150 |
/*
- * Copyright 2020 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
```suggestion
* Copyright 2023 LINE Corporation
```
/*
+ * Copyright 2023 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance |
codereview_new_java_data_8151 | final class RequestObjectTypeSignature extends DescriptiveTypeSignature {
private final Object annotatedValueResolvers;
- RequestObjectTypeSignature(TypeSignatureType requestObject, String name, Class<?> type,
Object annotatedValueResolvers) {
- super(requestObject, name, type);
this.annotatedValueResolvers = annotatedValueResolvers;
}
```suggestion
RequestObjectTypeSignature(TypeSignatureType type, String name, Class<?> clazz,
Object annotatedValueResolvers) {
super(type, name, clazz);
```
final class RequestObjectTypeSignature extends DescriptiveTypeSignature {
private final Object annotatedValueResolvers;
+ RequestObjectTypeSignature(TypeSignatureType type, String name, Class<?> clazz,
Object annotatedValueResolvers) {
+ super(type, name, clazz);
this.annotatedValueResolvers = annotatedValueResolvers;
}
|
codereview_new_java_data_8152 | static StreamDecoderFactory brotli() {
/**
* Construct a new {@link StreamDecoder} to use to decode an {@link HttpMessage}.
*/
@Override
default StreamDecoder newDecoder(ByteBufAllocator alloc) {
```suggestion
* Construct a new {@link StreamDecoder} to use to decode an {@link HttpMessage}.
*
* @param alloc the {@link ByteBufAllocator} to allocate a new {@link ByteBuf} for the decoded
* {@link HttpMessage}.
```
static StreamDecoderFactory brotli() {
/**
* Construct a new {@link StreamDecoder} to use to decode an {@link HttpMessage}.
+ *
+ * @param alloc the {@link ByteBufAllocator} to allocate a new {@link ByteBuf} for the decoded
+ * {@link HttpMessage}.
*/
@Override
default StreamDecoder newDecoder(ByteBufAllocator alloc) { |
codereview_new_java_data_8153 |
import static java.util.Objects.requireNonNull;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
Could you check your IDE settings and rearrange the imports?
https://armeria.dev/community/developer-guide#setting-up-your-ide
import static java.util.Objects.requireNonNull;
import com.google.errorprone.annotations.concurrent.GuardedBy;
+
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer; |
codereview_new_java_data_8154 | public final class ShutdownHooks {
private static final Logger logger = LoggerFactory.getLogger(ShutdownHooks.class);
- @GuardedBy("autoCloseableOnShutdownTasks")
private static final Map<AutoCloseable, Queue<Runnable>> autoCloseableOnShutdownTasks =
new LinkedHashMap<>();
This is:
```suggestion
@GuardedBy("reentrantLock")
```
public final class ShutdownHooks {
private static final Logger logger = LoggerFactory.getLogger(ShutdownHooks.class);
+ @GuardedBy("reentrantLock")
private static final Map<AutoCloseable, Queue<Runnable>> autoCloseableOnShutdownTasks =
new LinkedHashMap<>();
|
codereview_new_java_data_8155 | private static CompletableFuture<Void> addClosingTask(
}
}
});
- }
- finally {
reentrantLock.unlock();
}
}));
```suggestion
} finally {
```
private static CompletableFuture<Void> addClosingTask(
}
}
});
+ } finally {
reentrantLock.unlock();
}
})); |
codereview_new_java_data_8156 | final class HttpHealthChecker implements AsyncCloseable {
private static final Logger logger = LoggerFactory.getLogger(HttpHealthChecker.class);
- private final ReentrantLock lock = new ReentrantLock();
-
private static final AsciiString ARMERIA_LPHC = HttpHeaderNames.of("armeria-lphc");
private final HealthCheckerContext ctx;
private final WebClient webClient;
private final String authority;
Ditto: Should we move this below the static fields?
final class HttpHealthChecker implements AsyncCloseable {
private static final Logger logger = LoggerFactory.getLogger(HttpHealthChecker.class);
private static final AsciiString ARMERIA_LPHC = HttpHeaderNames.of("armeria-lphc");
+ private final ReentrantLock lock = new ReentrantLock();
private final HealthCheckerContext ctx;
private final WebClient webClient;
private final String authority; |
codereview_new_java_data_8157 |
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.LoggerContextVO;
-final class LoggingEventWrapper implements ILoggingEvent {
private final ILoggingEvent event;
private final Map<String, String> mdcPropertyMap;
@Nullable
If Logback maintainers are not interested in https://github.com/qos-ch/logback/pull/614,
I'm OK to extend `LoggingEvent` with some TODO.
```
// TODO(ikhoon): Use `ILoggingEvent` instead of `LoggingEvent` once https://github.com/qos-ch/logback/pull/614 is merged.
```
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.LoggerContextVO;
+import ch.qos.logback.classic.spi.LoggingEvent;
+// TODO(ikhoon): Use `ILoggingEvent` instead of `LoggingEvent` once https://github.com/qos-ch/logback/pull/614 is merged.
+final class LoggingEventWrapper extends LoggingEvent {
private final ILoggingEvent event;
private final Map<String, String> mdcPropertyMap;
@Nullable |
codereview_new_java_data_8158 | public class ContainerTypeSignature extends DefaultTypeSignature {
private final List<TypeSignature> typeParameters;
ContainerTypeSignature(TypeSignatureType type, String name,
- Iterable<TypeSignature> typeParameters) {
super(type, name);
final List<TypeSignature> typeParametersCopy = ImmutableList.copyOf(typeParameters);
checkArgument(!typeParametersCopy.isEmpty(), "typeParameters is empty.");
nit: How about simply using `List`?
```suggestion
List<TypeSignature> typeParameters) {
```
public class ContainerTypeSignature extends DefaultTypeSignature {
private final List<TypeSignature> typeParameters;
ContainerTypeSignature(TypeSignatureType type, String name,
+ List<TypeSignature> typeParameters) {
super(type, name);
final List<TypeSignature> typeParametersCopy = ImmutableList.copyOf(typeParameters);
checkArgument(!typeParametersCopy.isEmpty(), "typeParameters is empty."); |
codereview_new_java_data_8159 | boolean isSentConnectionCloseHeader() {
@Override
public boolean isResponseHeadersSent(int id, int streamId) {
- return id < currentId();
}
@Override
What do you think of renaming this as `isResponseSent` since a response with an id smaller than `currentId` is guaranteed to have been fully sent?
boolean isSentConnectionCloseHeader() {
@Override
public boolean isResponseHeadersSent(int id, int streamId) {
+ return id <= lastResponseHeadersId();
}
@Override |
codereview_new_java_data_8160 | void shouldReturn414ForLongUrlForHTTP1() {
}
@Test
- void shouldThrowHeaderListSizeExceptionForLongUrlForHTTP1() {
final BlockingWebClient client = BlockingWebClient.of(server.uri(SessionProtocol.H2C));
assertThatThrownBy(() -> {
client.get("/?q" + Strings.repeat("a", 200));
```suggestion
void shouldThrowHeaderListSizeExceptionForLongUrlForHTTP2() {
```
void shouldReturn414ForLongUrlForHTTP1() {
}
@Test
+ void shouldThrowHeaderListSizeExceptionForLongUrlForHTTP2() {
final BlockingWebClient client = BlockingWebClient.of(server.uri(SessionProtocol.H2C));
assertThatThrownBy(() -> {
client.get("/?q" + Strings.repeat("a", 200)); |
codereview_new_java_data_8161 | private PooledChannel acquireNowExact(PoolKey key, SessionProtocol protocol) {
private static boolean isHealthy(PooledChannel pooledChannel) {
final Channel ch = pooledChannel.get();
- return ch.isActive() && HttpSession.get(ch).canAcquire();
}
@Nullable
`canAcquire()` usually becomes `false` early than `canSendRequest()`. So `canAcquire()` would be a stricter rule.
private PooledChannel acquireNowExact(PoolKey key, SessionProtocol protocol) {
private static boolean isHealthy(PooledChannel pooledChannel) {
final Channel ch = pooledChannel.get();
+ return ch.isActive() && HttpSession.get(ch).isAcquirable();
}
@Nullable |
codereview_new_java_data_8162 | private ChannelFuture respond(ServiceRequestContext reqCtx, ResponseHeadersBuild
return future;
}
- /**
- * Sets the keep alive header as per:
- * - https://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
- */
private void addConnectionCloseHeaders(ResponseHeadersBuilder headers) {
if (protocol == H1 || protocol == H1C) {
headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE.toString());
nit; we can remove this javadoc
private ChannelFuture respond(ServiceRequestContext reqCtx, ResponseHeadersBuild
return future;
}
private void addConnectionCloseHeaders(ResponseHeadersBuilder headers) {
if (protocol == H1 || protocol == H1C) {
headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE.toString()); |
codereview_new_java_data_8163 | protected void configure(ServerBuilder sb) throws Exception {
@Test
void shouldCompleteUnfinishedRequestWhenConnectionIsClosed() throws Exception {
- final WebClient client = WebClient.builder(server.httpUri())
- .responseTimeoutMillis(0)
- .build();
client.get("/").aggregate();
client.get("/").aggregate();
nit:
```suggestion
final WebClient client = server.webClient(builder -> builder.responseTimeoutMillis(0));
```
protected void configure(ServerBuilder sb) throws Exception {
@Test
void shouldCompleteUnfinishedRequestWhenConnectionIsClosed() throws Exception {
+ final WebClient client = server.webClient(cb -> cb.responseTimeoutMillis(0));
client.get("/").aggregate();
client.get("/").aggregate();
|
codereview_new_java_data_8164 | public ServerBuilder addHeader(CharSequence name, Object value) {
* <ul>
* <li>{@link ServiceRequestContext#additionalResponseHeaders()}</li>
* <li>The {@link ResponseHeaders} of the {@link HttpResponse}</li>
- * <li>{@link VirtualHostBuilder#addHeader(CharSequence, Object)}</li>
- * <li>{@link VirtualHostServiceBindingBuilder#addHeader(CharSequence, Object)} or
- * {@link VirtualHostAnnotatedServiceBindingBuilder#addHeader(CharSequence, Object)}</li>
* </ul>
*/
public ServerBuilder addHeaders(
nit; `addHeader` -> `addHeaders`
public ServerBuilder addHeader(CharSequence name, Object value) {
* <ul>
* <li>{@link ServiceRequestContext#additionalResponseHeaders()}</li>
* <li>The {@link ResponseHeaders} of the {@link HttpResponse}</li>
+ * <li>{@link VirtualHostBuilder#addHeaders(Iterable)}</li>
+ * <li>{@link VirtualHostServiceBindingBuilder#addHeaders(Iterable)} or
+ * {@link VirtualHostAnnotatedServiceBindingBuilder#addHeaders(Iterable)}</li>
* </ul>
*/
public ServerBuilder addHeaders( |
codereview_new_java_data_8165 | public VirtualHostBuilder setHeader(CharSequence name, Object value) {
}
/**
- * Sets the default HTTP headers for {@link HttpResponse}.
*
* <p>Note that the default headers could be overridden if the same {@link HttpHeaderNames} are defined in
* one of the followings:
```suggestion
* Sets the default HTTP headers for an {@link HttpResponse} served by this {@link VirtualHost}.
```
public VirtualHostBuilder setHeader(CharSequence name, Object value) {
}
/**
+ * Sets the default HTTP headers for an {@link HttpResponse} served by this {@link VirtualHost}.
*
* <p>Note that the default headers could be overridden if the same {@link HttpHeaderNames} are defined in
* one of the followings: |
codereview_new_java_data_8166 | public void serviceAdded(ServiceConfig cfg) throws Exception {
// Build the Specification after all the services are added to the server.
final ServerConfig config = server.config();
- final List<VirtualHost> virtualHosts = config.findVirtualHosts(DocService.this);
final List<ServiceConfig> services =
config.serviceConfigs().stream()
```suggestion
final List<VirtualHost> virtualHosts = config.findVirtualHosts(this);
```
public void serviceAdded(ServiceConfig cfg) throws Exception {
// Build the Specification after all the services are added to the server.
final ServerConfig config = server.config();
+ final List<VirtualHost> virtualHosts = config.findVirtualHosts(this);
final List<ServiceConfig> services =
config.serviceConfigs().stream() |
codereview_new_java_data_8167 | static void verifyResponseBufs() {
@Test
void shouldReturnEmptyBodyOnHead() throws Exception {
- final BlockingWebClient client = WebClient.of(server.httpUri()).blocking();
final AggregatedHttpResponse res = client.head("/hello");
assertThat(res.headers().contentLength()).isEqualTo(5);
assertThat(res.contentUtf8()).isEmpty();
nit:
```suggestion
final BlockingWebClient client = server.blockingWebClient();
```
static void verifyResponseBufs() {
@Test
void shouldReturnEmptyBodyOnHead() throws Exception {
+ final BlockingWebClient client = server.blockingWebClient();
final AggregatedHttpResponse res = client.head("/hello");
assertThat(res.headers().contentLength()).isEqualTo(5);
assertThat(res.contentUtf8()).isEmpty(); |
codereview_new_java_data_8168 | final AggregatedHttpResponse toAggregatedHttpResponse(HttpStatusException cause)
return response;
}
-
final void endLogRequestAndResponse(Throwable cause) {
logBuilder().endRequest(cause);
logBuilder().endResponse(cause);
Should we revert the extra line?
final AggregatedHttpResponse toAggregatedHttpResponse(HttpStatusException cause)
return response;
}
final void endLogRequestAndResponse(Throwable cause) {
logBuilder().endRequest(cause);
logBuilder().endResponse(cause); |
codereview_new_java_data_8169 | String uriText() {
@Param
private Protocol protocol;
- @Param({ "100", "1000"})
private int chunkCount;
@Setup
nit; What do you think of leaving this as a single value by default?
Other benchmarks like `plainText`, `empty` would run twice by default due to a parameter they don't rely on.
```suggestion
@Param("100")
```
String uriText() {
@Param
private Protocol protocol;
+ @Param("100")
private int chunkCount;
@Setup |
codereview_new_java_data_8170 |
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;
import com.linecorp.armeria.server.annotation.DecoratorFactory;
/**
- * Annotation for request timeout
*/
@DecoratorFactory(RequestTimeoutDecoratorFunction.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface RequestTimeout {
/**
- * Value of request timeout to set
*/
long value();
/**
- * Time unit of request timeout to set
*/
- TimeUnit unit();
}
- How about setting `TimeUnit.MILLISECONDS` as the default unit?
- `TimeoutMode` could be also a useful parameter. `TimeoutMode.SET_FROM_START` may be used for the default mode.
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;
+import com.linecorp.armeria.common.util.TimeoutMode;
import com.linecorp.armeria.server.annotation.DecoratorFactory;
/**
+ * Annotation for request timeout.
*/
@DecoratorFactory(RequestTimeoutDecoratorFunction.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface RequestTimeout {
/**
+ * Value of request timeout to set.
*/
long value();
/**
+ * Time unit of request timeout to set.
*/
+ TimeUnit unit() default TimeUnit.MILLISECONDS;
+
+ /**
+ * Timeout mode of request timeout to set.
+ */
+ TimeoutMode timeoutMode() default TimeoutMode.SET_FROM_START;
} |
codereview_new_java_data_8171 | public final class RequestTimeoutDecoratorFunction implements DecoratorFactoryFu
return delegate -> new SimpleDecoratingHttpService(delegate) {
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
- ServiceRequestContext.current()
- .setRequestTimeoutMillis(TimeoutMode.SET_FROM_START, timeoutMillis);
return delegate.serve(ctx, req);
}
};
nit:
```suggestion
ctx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_START, timeoutMillis);
```
public final class RequestTimeoutDecoratorFunction implements DecoratorFactoryFu
return delegate -> new SimpleDecoratingHttpService(delegate) {
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
+ ctx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_START, timeoutMillis);
return delegate.serve(ctx, req);
}
}; |
codereview_new_java_data_8172 | public String timeoutSeconds(ServiceRequestContext ctx, HttpRequest req) {
AnnotatedServiceTest.validateContextAndRequest(ctx, req);
return Long.toString(ctx.requestTimeoutMillis());
}
-
- @Get("/subscriberIsInitialized")
- public String subscriberIsInitialized(ServiceRequestContext ctx, HttpRequest req) {
- AnnotatedServiceTest.validateContextAndRequest(ctx, req);
- final boolean isInitialized = ((DefaultServiceRequestContext) ctx)
- .requestCancellationScheduler().isInitialized();
- return Boolean.toString(isInitialized);
- }
}
@Test
void testRequestTimeoutSet() {
- final BlockingWebClient client = BlockingWebClient.of(server.httpUri());
AggregatedHttpResponse response;
```suggestion
final BlockingWebClient client = server.blockingWebClient();
```
public String timeoutSeconds(ServiceRequestContext ctx, HttpRequest req) {
AnnotatedServiceTest.validateContextAndRequest(ctx, req);
return Long.toString(ctx.requestTimeoutMillis());
}
}
@Test
void testRequestTimeoutSet() {
+ final BlockingWebClient client = server.blockingWebClient();
AggregatedHttpResponse response;
|
codereview_new_java_data_8173 |
public final class RequestTimeoutDecoratorFunction implements DecoratorFactoryFunction<RequestTimeout> {
/**
- * Creates a new decorator with the specified {@code parameter}.
*/
@Override
public Function<? super HttpService, ? extends HttpService> newDecorator(RequestTimeout parameter) {
```suggestion
* Creates a new decorator with the specified {@link RequestTimeout}.
```
public final class RequestTimeoutDecoratorFunction implements DecoratorFactoryFunction<RequestTimeout> {
/**
+ * Creates a new decorator with the specified {@link RequestTimeout}.
*/
@Override
public Function<? super HttpService, ? extends HttpService> newDecorator(RequestTimeout parameter) { |
codereview_new_java_data_8174 | public void subscribe(Subscriber<? super T> subscriber, EventExecutor executor,
SubscriptionOption... options) {
requireNonNull(subscriber, "subscriber");
requireNonNull(executor, "executor");
- executor.execute(() -> {
- subscriber.onSubscribe(NoopSubscription.get());
- subscriber.onComplete();
- whenComplete().complete(null);
- });
}
@Override
Question) Is there no need to complete this future from the provided eventloop (`executor`)?
Ditto for `cancel`, `abort` as well.
public void subscribe(Subscriber<? super T> subscriber, EventExecutor executor,
SubscriptionOption... options) {
requireNonNull(subscriber, "subscriber");
requireNonNull(executor, "executor");
+ if (executor.inEventLoop()) {
+ subscribe0(subscriber);
+ } else {
+ executor.execute(() -> subscribe0(subscriber));
+ }
+ }
+
+ private void subscribe0(Subscriber<? super T> subscriber) {
+ subscriber.onSubscribe(NoopSubscription.get());
+ subscriber.onComplete();
+ whenComplete().complete(null);
}
@Override |
codereview_new_java_data_8175 |
*/
package com.linecorp.armeria.internal.server;
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.common.HttpResponse;
/**
- * A special {@link RuntimeException} that aborts an {@link HttpRequest} after the corresponding
* {@link HttpResponse} is completed.
*/
-public final class ResponseCompleteException extends RuntimeException {
private static final long serialVersionUID = 6090278381004263949L;
Would be better to extend either `CancelledSubscriptionException` or `AbortedStreamException`?
*/
package com.linecorp.armeria.internal.server;
+import com.linecorp.armeria.common.CancellationException;
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.common.HttpResponse;
/**
+ * A special {@link CancellationException} that aborts an {@link HttpRequest} after the corresponding
* {@link HttpResponse} is completed.
*/
+public final class ResponseCompleteException extends CancellationException {
private static final long serialVersionUID = 6090278381004263949L;
|
codereview_new_java_data_8176 | public void subscribe(Subscriber<? super T> subscriber, EventExecutor executor,
SubscriptionOption... options) {
requireNonNull(subscriber, "subscriber");
requireNonNull(executor, "executor");
- executor.execute(() -> {
- subscriber.onSubscribe(NoopSubscription.get());
- subscriber.onComplete();
- whenComplete().complete(null);
- });
}
@Override
Do we need to reschedule this even when it is in the event loop?
public void subscribe(Subscriber<? super T> subscriber, EventExecutor executor,
SubscriptionOption... options) {
requireNonNull(subscriber, "subscriber");
requireNonNull(executor, "executor");
+ if (executor.inEventLoop()) {
+ subscribe0(subscriber);
+ } else {
+ executor.execute(() -> subscribe0(subscriber));
+ }
+ }
+
+ private void subscribe0(Subscriber<? super T> subscriber) {
+ subscriber.onSubscribe(NoopSubscription.get());
+ subscriber.onComplete();
+ whenComplete().complete(null);
}
@Override |
codereview_new_java_data_8177 | private <I, O> void startCall(ServerMethodDefinition<I, O> methodDef, ServiceReq
.startCall(call, MetadataUtil.copyFromHeaders(req.headers()));
} catch (Throwable t) {
call.setListener((Listener<I>) EMPTY_LISTENER);
- final Metadata metadata = new Metadata();
- call.close(GrpcStatus.fromThrowable(statusFunction, ctx, t, metadata), metadata);
return;
}
if (listener == null) {
I'm wondering if we want to also pass the throwable so that the cause is exposed better.
What do you think other maintainers?
```suggestion
call.close(t);
```
private <I, O> void startCall(ServerMethodDefinition<I, O> methodDef, ServiceReq
.startCall(call, MetadataUtil.copyFromHeaders(req.headers()));
} catch (Throwable t) {
call.setListener((Listener<I>) EMPTY_LISTENER);
+ call.close(t);
return;
}
if (listener == null) { |
codereview_new_java_data_8178 | private static MediaType addKnownType(MediaType mediaType) {
/**
* The GraphQL response content type is changed from {@link #GRAPHQL_JSON} to {@link #GRAPHQL_RESPONSE_JSON}
* in this PR. <a href="https://github.com/graphql/graphql-over-http/pull/215">Change media type</a>
*/
public static final MediaType GRAPHQL_JSON = createConstant(APPLICATION_TYPE, "graphql+json");
/**
```suggestion
@Deprecated
public static final MediaType GRAPHQL_JSON = createConstant(APPLICATION_TYPE, "graphql+json");
```
private static MediaType addKnownType(MediaType mediaType) {
/**
* The GraphQL response content type is changed from {@link #GRAPHQL_JSON} to {@link #GRAPHQL_RESPONSE_JSON}
* in this PR. <a href="https://github.com/graphql/graphql-over-http/pull/215">Change media type</a>
+ *
+ * @deprecated Use {@link #GRAPHQL_RESPONSE_JSON} if the client can recognize the media type.
*/
+ @Deprecated
public static final MediaType GRAPHQL_JSON = createConstant(APPLICATION_TYPE, "graphql+json");
/** |
codereview_new_java_data_8179 | public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) throws Ex
final HttpRequestDuplicator reqDuplicator = req.toDuplicator(ctx.eventLoop().withoutContext(), 0);
execute0(ctx, redirectCtx, reqDuplicator, true);
} else {
- req.aggregate(AggregationOptions.builder()
- .usePooledObjects(ctx.alloc())
- .executor(ctx.eventLoop())
- .build())
.handle((agg, cause) -> {
if (cause != null) {
handleException(ctx, null, responseFuture, cause, true);
This pattern seems frequently used. How about adding a factory method for it?
```suggestion
req.aggregate(AggregationOptions.usePooledObjects(ctx.alloc(),
ctx.eventLoop())
```
public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) throws Ex
final HttpRequestDuplicator reqDuplicator = req.toDuplicator(ctx.eventLoop().withoutContext(), 0);
execute0(ctx, redirectCtx, reqDuplicator, true);
} else {
+ req.aggregate(AggregationOptions.usePooledObjects(ctx.alloc(), ctx.eventLoop()))
.handle((agg, cause) -> {
if (cause != null) {
handleException(ctx, null, responseFuture, cause, true); |
codereview_new_java_data_8180 | default HttpRequest toHttpRequest() {
*/
default HttpRequest toHttpRequest(RequestHeaders headers) {
requireNonNull(headers, "headers");
- return HttpRequest.of(maybeModifyContentLength(headers, content()), content(), trailers());
}
}
Doesn't have to be done in this PR, just a note:
I find it surprising that `HttpRequest.of` modifies the content based on header length, I'm wondering if the behavior should be consistent with `AggregatedHttpRequest.of`
default HttpRequest toHttpRequest() {
*/
default HttpRequest toHttpRequest(RequestHeaders headers) {
requireNonNull(headers, "headers");
+ return HttpRequest.of(headers, content(), trailers());
}
} |
codereview_new_java_data_8181 | private static FieldInfo newFieldInfo(FieldDescriptor fieldDescriptor, Set<Descr
final TypeSignature typeSignature = newFieldTypeInfo(fieldDescriptor);
final Object typeDescriptor = typeSignature.namedTypeDescriptor();
final FieldInfoBuilder builder;
- if (typeDescriptor instanceof Descriptor && visiting.add((Descriptor) typeDescriptor) &&
- !((Descriptor) typeDescriptor).getFields().isEmpty()) {
builder = FieldInfo.builder(fieldDescriptor.getName(), typeSignature,
newFieldInfos((Descriptor) typeDescriptor, visiting));
} else {
The following validation is pretty annoying and I'm not sure it is genuinely useful validation.
https://github.com/line/armeria/blob/755c28292c734e954bd69aebcfaeabcf7b024c16/core/src/main/java/com/linecorp/armeria/server/docs/FieldInfoBuilder.java#L56-L57
I was wondering if we could solve the problem by just removing the validation.
private static FieldInfo newFieldInfo(FieldDescriptor fieldDescriptor, Set<Descr
final TypeSignature typeSignature = newFieldTypeInfo(fieldDescriptor);
final Object typeDescriptor = typeSignature.namedTypeDescriptor();
final FieldInfoBuilder builder;
+ if (typeDescriptor instanceof Descriptor && visiting.add((Descriptor) typeDescriptor)) {
builder = FieldInfo.builder(fieldDescriptor.getName(), typeSignature,
newFieldInfos((Descriptor) typeDescriptor, visiting));
} else { |
codereview_new_java_data_8182 | private GraphqlErrorsHandlers() {}
*/
private static HttpResponse toHttpResponse(HttpStatus httpStatus, ExecutionResult executionResult,
MediaType produceType) {
- // TODO: When WebSocket is implemented, it should be removed.
- if (executionResult.getData() instanceof Publisher) {
- logger.warn("executionResult.getData() returns a {} that is not supported yet.",
- executionResult.getData().toString());
- final ExecutionResult error =
- newExecutionResult(new UnsupportedOperationException("WebSocket is not implemented"));
- return HttpResponse.ofJson(HttpStatus.NOT_IMPLEMENTED, produceType, error.toSpecification());
- }
return HttpResponse.ofJson(httpStatus, produceType, executionResult.toSpecification());
}
Now we can remove this. π
```suggestion
```
private GraphqlErrorsHandlers() {}
*/
private static HttpResponse toHttpResponse(HttpStatus httpStatus, ExecutionResult executionResult,
MediaType produceType) {
return HttpResponse.ofJson(httpStatus, produceType, executionResult.toSpecification());
}
|
codereview_new_java_data_8183 | public GraphqlServiceBuilder useBlockingTaskExecutor(boolean useBlockingTaskExec
* Sets the {@link GraphqlErrorsHandler}.
*/
public GraphqlServiceBuilder errorsHandler(GraphqlErrorsHandler errorsHandler) {
- this.errorsHandler = errorsHandler;
return this;
}
```suggestion
this.errorsHandler = requireNonNull(errorsHandler, "errorsHandler");
```
public GraphqlServiceBuilder useBlockingTaskExecutor(boolean useBlockingTaskExec
* Sets the {@link GraphqlErrorsHandler}.
*/
public GraphqlServiceBuilder errorsHandler(GraphqlErrorsHandler errorsHandler) {
+ this.errorsHandler = requireNonNull(errorsHandler, "errorsHandler");
return this;
}
|
codereview_new_java_data_8184 |
import graphql.ExecutionResult;
/**
- * A handler that maps GraphQL errors to an {@link HttpResponse}.
*/
@FunctionalInterface
public interface GraphqlErrorsHandler {
```suggestion
* A handler that maps GraphQL errors or a {@link Throwable} to an {@link HttpResponse}.
```
import graphql.ExecutionResult;
/**
+ * A handler that maps GraphQL errors or a {@link Throwable} to an {@link HttpResponse}.
*/
@FunctionalInterface
public interface GraphqlErrorsHandler { |
codereview_new_java_data_8185 |
import graphql.GraphqlErrorException;
import graphql.schema.DataFetcher;
-public class GraphqlErrorsHandlerTest {
@RegisterExtension
static ServerExtension server = new ServerExtension() {
```suggestion
class GraphqlErrorsHandlerTest {
```
We don't need `public` modifier for the test. π
import graphql.GraphqlErrorException;
import graphql.schema.DataFetcher;
+class GraphqlErrorsHandlerTest {
@RegisterExtension
static ServerExtension server = new ServerExtension() { |
codereview_new_java_data_8186 | static ExecutionResult newExecutionResult(Throwable cause) {
}
/**
- * Return {@link HttpStatus} based List of {@link GraphQLError}.
*/
private static HttpStatus graphqlErrorsToHttpStatus(List<GraphQLError> errors) {
if (errors.isEmpty()) {
```suggestion
* Return an {@link HttpStatus} based on the specified list of {@link GraphQLError}s.
```
Or we can remove this Javadoc because it's a private method. π
static ExecutionResult newExecutionResult(Throwable cause) {
}
/**
+ * Return an {@link HttpStatus} based on the specified list of {@link GraphQLError}s.
*/
private static HttpStatus graphqlErrorsToHttpStatus(List<GraphQLError> errors) {
if (errors.isEmpty()) { |
codereview_new_java_data_8187 |
import static java.util.Objects.requireNonNull;
import com.linecorp.armeria.common.HttpResponse;
-import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.MediaType;
import com.linecorp.armeria.common.annotation.Nullable;
import com.linecorp.armeria.common.annotation.UnstableApi;
import com.linecorp.armeria.server.ServiceRequestContext;
import graphql.ExecutionInput;
import graphql.ExecutionResult;
-import graphql.GraphQLError;
/**
- * A handler that maps GraphQL errors or a {@link Throwable} to an {@link HttpResponse}.
*/
@UnstableApi
@FunctionalInterface
public interface GraphqlErrorsHandler {
/**
- * Return an {@link HttpStatus} based on the specified list of {@link GraphQLError}s.
*/
static GraphqlErrorsHandler of() {
return GraphqlErrorsHandlers.defaultErrorsHandler;
```suggestion
* Return the default {@link GraphqlErrorsHandler}.
```
import static java.util.Objects.requireNonNull;
import com.linecorp.armeria.common.HttpResponse;
import com.linecorp.armeria.common.MediaType;
import com.linecorp.armeria.common.annotation.Nullable;
import com.linecorp.armeria.common.annotation.UnstableApi;
import com.linecorp.armeria.server.ServiceRequestContext;
import graphql.ExecutionInput;
import graphql.ExecutionResult;
/**
+ * A handler that maps {@link ExecutionResult#getErrors()} or the specified {@link Throwable}
+ * to an {@link HttpResponse}.
*/
@UnstableApi
@FunctionalInterface
public interface GraphqlErrorsHandler {
/**
+ * Return the default {@link GraphqlErrorsHandler}.
*/
static GraphqlErrorsHandler of() {
return GraphqlErrorsHandlers.defaultErrorsHandler; |
codereview_new_java_data_8188 | public GraphqlServiceBuilder useBlockingTaskExecutor(boolean useBlockingTaskExec
/**
* Sets the {@link GraphqlErrorsHandler}.
*/
public GraphqlServiceBuilder errorsHandler(GraphqlErrorsHandler errorsHandler) {
this.errorsHandler = requireNonNull(errorsHandler, "errorsHandler");
```suggestion
* Sets the {@link GraphqlErrorsHandler}.
* If not specified, {@link GraphqlErrorsHandler#of()} is used by default.
```
public GraphqlServiceBuilder useBlockingTaskExecutor(boolean useBlockingTaskExec
/**
* Sets the {@link GraphqlErrorsHandler}.
+ * If not specified, {@link GraphqlErrorsHandler#of()} is used by default.
*/
public GraphqlServiceBuilder errorsHandler(GraphqlErrorsHandler errorsHandler) {
this.errorsHandler = requireNonNull(errorsHandler, "errorsHandler"); |
codereview_new_java_data_8189 |
public interface GraphqlErrorHandler {
/**
- * Return the {@link DefaultGraphqlErrorHandler}.
*/
static GraphqlErrorHandler of() {
return DefaultGraphqlErrorHandler.INSTANCE;
```suggestion
* Return the default {@link GraphqlErrorHandler}.
```
... because `DefaultGraphqlErrorHandler` is a package-private class so we cannot expose it to the Javadoc.
public interface GraphqlErrorHandler {
/**
+ * Return the default {@link GraphqlErrorHandler}.
*/
static GraphqlErrorHandler of() {
return DefaultGraphqlErrorHandler.INSTANCE; |
codereview_new_java_data_8190 | public GraphqlServiceBuilder useBlockingTaskExecutor(boolean useBlockingTaskExec
* Sets the {@link GraphqlErrorHandler}.
* If not specified, {@link GraphqlErrorHandler#of()} is used by default.
*/
- public GraphqlServiceBuilder errorsHandler(GraphqlErrorHandler errorsHandler) {
this.errorsHandler = requireNonNull(errorsHandler, "errorsHandler");
return this;
}
```suggestion
public GraphqlServiceBuilder errorHandler(GraphqlErrorHandler errorHandler) {
```
public GraphqlServiceBuilder useBlockingTaskExecutor(boolean useBlockingTaskExec
* Sets the {@link GraphqlErrorHandler}.
* If not specified, {@link GraphqlErrorHandler#of()} is used by default.
*/
+ public GraphqlServiceBuilder errorHandler(GraphqlErrorHandler errorHandler) {
this.errorsHandler = requireNonNull(errorsHandler, "errorsHandler");
return this;
} |
codereview_new_java_data_8191 | static ResultType toResultType(Type type) {
}
final Class<?> keyType = (Class<?>) typeArguments[0];
if (!String.class.isAssignableFrom(keyType)) {
- throw new IllegalStateException(
- keyType + " cannot be used for the key type of Map. " +
- "(expected: Map<String, ?>)");
}
if (!(typeArguments[1] instanceof Class<?>)) {
return ResultType.UNKNOWN;
Shouldn't we return `return ResultType.UNKNOWN;` instead of raising an exception?
static ResultType toResultType(Type type) {
}
final Class<?> keyType = (Class<?>) typeArguments[0];
if (!String.class.isAssignableFrom(keyType)) {
+ return ResultType.UNKNOWN;
}
if (!(typeArguments[1] instanceof Class<?>)) {
return ResultType.UNKNOWN; |
codereview_new_java_data_8192 | public final class ThriftProtocolFactories {
final Constructor<TBinaryProtocol.Factory> ignored =
TBinaryProtocol.Factory.class.getConstructor(boolean.class, boolean.class,
long.class, long.class);
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
isThrift091 = true;
}
IS_THRIFT_091 = isThrift091;
let's leave a info log instead of calling `printStackTrace`
public final class ThriftProtocolFactories {
final Constructor<TBinaryProtocol.Factory> ignored =
TBinaryProtocol.Factory.class.getConstructor(boolean.class, boolean.class,
long.class, long.class);
+ } catch (NoSuchMethodException ignored) {
isThrift091 = true;
}
IS_THRIFT_091 = isThrift091; |
codereview_new_java_data_8193 |
/**
* A generic handler containing callback methods which are invoked by
* {@link CircuitBreakerClient}. It may be useful to create a custom
- * implementation in conjunction with {@link CircuitBreakerHandlerFactory}
* if one wishes to use a custom CircuitBreaker with {@link CircuitBreakerClient}.
*/
@UnstableApi
-public interface CircuitBreakerClientHandler<CB, I extends Request> {
/**
* Invoked by {@link CircuitBreakerClient} right before executing a request.
It seems that `CB` could be removed.
/**
* A generic handler containing callback methods which are invoked by
* {@link CircuitBreakerClient}. It may be useful to create a custom
+ * implementation in conjunction with {@link CircuitBreakerClientHandlerFactory}
* if one wishes to use a custom CircuitBreaker with {@link CircuitBreakerClient}.
*/
@UnstableApi
+public interface CircuitBreakerClientHandler<I extends Request> {
/**
* Invoked by {@link CircuitBreakerClient} right before executing a request. |
codereview_new_java_data_8194 |
import com.linecorp.armeria.common.annotation.UnstableApi;
/**
- * An abstract builder class for building a CircuitBreaker mapping
* based on a combination of host, method and path.
*/
@UnstableApi
```suggestion
* An abstract builder class for building a {@link CircuitBreakerMapping}
```
import com.linecorp.armeria.common.annotation.UnstableApi;
/**
+ * An abstract builder class for building a {@link CircuitBreakerMapping}
* based on a combination of host, method and path.
*/
@UnstableApi |
codereview_new_java_data_8195 |
* Returns a newly-created {@link CircuitBreakerRpcClient} based on the properties of this builder.
*/
public CircuitBreakerRpcClient build(RpcClient delegate) {
- return build(delegate, CircuitBreakerClientHandler.of(CircuitBreakerMapping.ofDefault()));
- }
-
- /**
- * Returns a newly-created {@link CircuitBreakerRpcClient} based on the properties of this builder.
- */
- public CircuitBreakerRpcClient build(
- RpcClient delegate,
- CircuitBreakerClientHandler<RpcRequest> handler) {
- return new CircuitBreakerRpcClient(delegate, ruleWithContent(), handler);
}
/**
`AbstractCircuitBreakerClientBuilder` also has `CircuitBreakerClientHandler.of(CircuitBreakerMapping.ofDefault())`.
How about adding `CircuitBreakerClientHandler.of()` and using it?
* Returns a newly-created {@link CircuitBreakerRpcClient} based on the properties of this builder.
*/
public CircuitBreakerRpcClient build(RpcClient delegate) {
+ return new CircuitBreakerRpcClient(delegate, ruleWithContent(), handler());
}
/** |
codereview_new_java_data_8196 | static <I extends Request> CircuitBreakerClientHandler<I> of(CircuitBreakerMappi
}
/**
- * Invoked by {@link CircuitBreakerClient} right before executing a request.
* In a typical implementation, users may extract the appropriate circuit breaker
* implementation using the provided {@link ClientRequestContext} and {@link Request}.
* Afterwards, one of the following can occur:
nit: Will `sending a request` be more appropriate?
static <I extends Request> CircuitBreakerClientHandler<I> of(CircuitBreakerMappi
}
/**
+ * Invoked by {@link CircuitBreakerClient} right before sending a request.
* In a typical implementation, users may extract the appropriate circuit breaker
* implementation using the provided {@link ClientRequestContext} and {@link Request}.
* Afterwards, one of the following can occur: |
codereview_new_java_data_8197 |
/**
* Returns a circuit breaker implementation from remote invocation parameters.
*/
@FunctionalInterface
@UnstableApi
How about adding the description of the type parameter `T`?
/**
* Returns a circuit breaker implementation from remote invocation parameters.
+ *
+ * @param <T> the type of circuit breaker that will be generated
*/
@FunctionalInterface
@UnstableApi |
codereview_new_java_data_8198 | public CircuitBreakerCallback tryRequest(ClientRequestContext ctx, I req) {
try {
circuitBreaker = requireNonNull(mapping.get(ctx, req), "circuitBreaker");
} catch (Throwable t) {
- logger.warn("Failed to get a circuit breaker from mapping", t);
return null;
}
if (!circuitBreaker.tryRequest()) {
nit:
```suggestion
logger.warn("Failed to get a circuit breaker from mapping: {}", mapping, t);
```
public CircuitBreakerCallback tryRequest(ClientRequestContext ctx, I req) {
try {
circuitBreaker = requireNonNull(mapping.get(ctx, req), "circuitBreaker");
} catch (Throwable t) {
+ logger.warn("Failed to get a circuit breaker from mapping: {}", mapping, t);
return null;
}
if (!circuitBreaker.tryRequest()) { |
codereview_new_java_data_8199 |
import com.linecorp.armeria.common.annotation.UnstableApi;
/**
- * A collection of callbacks that are invoked for each request by {@link CircuitBreakerClient}.
* Users may implement this class in conjunction with {@link CircuitBreakerClientHandler} to
* use arbitrary circuit breaker implementations with {@link CircuitBreakerClient}.
*
```suggestion
* A callback that is invoked for each request by {@link CircuitBreakerClient}.
```
import com.linecorp.armeria.common.annotation.UnstableApi;
/**
+ * A callback that is invoked for each request by {@link CircuitBreakerClient}.
* Users may implement this class in conjunction with {@link CircuitBreakerClientHandler} to
* use arbitrary circuit breaker implementations with {@link CircuitBreakerClient}.
* |
codereview_new_java_data_8200 | public String toString() {
return toStringHelper()
.add("questions", questions)
.add("logPrefix", logPrefix)
.toString();
}
}
Add `attemptsSoFar` as well? It would be useful for debugging.
public String toString() {
return toStringHelper()
.add("questions", questions)
.add("logPrefix", logPrefix)
+ .add("attemptsSoFar", attemptsSoFar)
.toString();
}
} |
codereview_new_java_data_8201 | void healthCheckedEndpointGroup_custom() {
}
// TODO(ikhoon): Revert once CI builds pass
- @RepeatedTest(1000)
void select_timeout() {
final int expectedTimeout = 3000;
try (MockEndpointGroup endpointGroup = new MockEndpointGroup(expectedTimeout)) {
```suggestion
@RepeatedTest(100)
```
void healthCheckedEndpointGroup_custom() {
}
// TODO(ikhoon): Revert once CI builds pass
+ @RepeatedTest(100)
void select_timeout() {
final int expectedTimeout = 3000;
try (MockEndpointGroup endpointGroup = new MockEndpointGroup(expectedTimeout)) { |
codereview_new_java_data_8202 |
final class ByteStreamMessageOutputStream implements ByteStreamMessage {
- private final Consumer<OutputStream> outputStreamWriter;
- private final Executor executor;
-
private final StreamMessageAndWriter<HttpData> streamWriter = new DefaultStreamMessage<>();
private final ByteStreamMessage delegate = ByteStreamMessage.of(streamWriter);
private final OutputStream outputStream = new StreamWriterOutputStream(streamWriter);
ByteStreamMessageOutputStream(Consumer<OutputStream> outputStreamWriter, Executor executor) {
this.outputStreamWriter = outputStreamWriter;
this.executor = executor;
Should we sort the fields according to the initialization order?
```suggestion
private final StreamMessageAndWriter<HttpData> streamWriter = new DefaultStreamMessage<>();
private final ByteStreamMessage delegate = ByteStreamMessage.of(streamWriter);
private final OutputStream outputStream = new StreamWriterOutputStream(streamWriter);
private final Consumer<OutputStream> outputStreamWriter;
private final Executor executor;
```
final class ByteStreamMessageOutputStream implements ByteStreamMessage {
private final StreamMessageAndWriter<HttpData> streamWriter = new DefaultStreamMessage<>();
private final ByteStreamMessage delegate = ByteStreamMessage.of(streamWriter);
private final OutputStream outputStream = new StreamWriterOutputStream(streamWriter);
+ private final Consumer<OutputStream> outputStreamWriter;
+ private final Executor executor;
+
ByteStreamMessageOutputStream(Consumer<OutputStream> outputStreamWriter, Executor executor) {
this.outputStreamWriter = outputStreamWriter;
this.executor = executor; |
codereview_new_java_data_8203 | void refresh() {
return;
}
- final String hostname = address.getHostName();
if (refreshing) {
return;
}
refreshing = true;
// 'sendQueries()' always successfully completes.
sendQueries(questions, hostname, originalCreationTimeNanos).thenAccept(entry -> {
if (executor().inEventLoop()) {
nit: let's move this down to the line 337
void refresh() {
return;
}
if (refreshing) {
return;
}
refreshing = true;
+ final String hostname = address.getHostName();
// 'sendQueries()' always successfully completes.
sendQueries(questions, hostname, originalCreationTimeNanos).thenAccept(entry -> {
if (executor().inEventLoop()) { |
codereview_new_java_data_8204 | void onRemoval(DnsQuestion question, @Nullable List<DnsRecord> records,
@Nullable UnknownHostException cause);
/**
- * Invoked when an eviction occurred for the {@link DnsRecord}s. The eviction may occur due to exceeding
- * a maximum size or timed expiration. The cause may vary depending on the
- * {@link DnsCacheBuilder#cacheSpec(String)} of the {@link DnsCache}.
*
* @param question the DNS question.
* @param records the result of a successful DNS resolution. {@code null} if failed.
```suggestion
* Invoked when an eviction occurred for the {@link DnsRecord}s. The eviction occurs due to exceeding
* the maximum size.
```
void onRemoval(DnsQuestion question, @Nullable List<DnsRecord> records,
@Nullable UnknownHostException cause);
/**
+ * Invoked when an eviction occurred for the {@link DnsRecord}s. The eviction occurs due to exceeding
+ * the maximum size.
*
* @param question the DNS question.
* @param records the result of a successful DNS resolution. {@code null} if failed. |
codereview_new_java_data_8205 | private HttpResponse convertResponseInternal(ServiceRequestContext ctx,
private ResponseHeaders buildResponseHeaders(ServiceRequestContext ctx, HttpHeaders customHeaders) {
final ResponseHeadersBuilder builder;
- // Prefer ResponseHeaders#toBuilder because builder#add is an expensive operation.
if (customHeaders instanceof ResponseHeaders) {
builder = ((ResponseHeaders) customHeaders).toBuilder();
} else {
```suggestion
// Prefer ResponseHeaders#toBuilder because builder#add(Iterable) is an expensive operation.
```
private HttpResponse convertResponseInternal(ServiceRequestContext ctx,
private ResponseHeaders buildResponseHeaders(ServiceRequestContext ctx, HttpHeaders customHeaders) {
final ResponseHeadersBuilder builder;
+ // Prefer ResponseHeaders#toBuilder because builder#add(Iterable) is an expensive operation.
if (customHeaders instanceof ResponseHeaders) {
builder = ((ResponseHeaders) customHeaders).toBuilder();
} else { |
codereview_new_java_data_8206 |
import com.linecorp.armeria.server.Server;
/**
- * An {@link SmartLifecycle} which retries to start the {@link Server} up to {@code maxAttempts}.
* This is useful for testing that needs to bind a server to a random port number obtained in advance.
*/
final class RetryableArmeriaServerGracefulShutdownLifecycle implements SmartLifecycle {
```suggestion
* A {@link SmartLifecycle} which retries to start the {@link Server} up to {@code maxAttempts}.
```
import com.linecorp.armeria.server.Server;
/**
+ * A {@link SmartLifecycle} which retries to start the {@link Server} up to {@code maxAttempts}.
* This is useful for testing that needs to bind a server to a random port number obtained in advance.
*/
final class RetryableArmeriaServerGracefulShutdownLifecycle implements SmartLifecycle { |
codereview_new_java_data_8207 |
import io.netty.util.concurrent.EventExecutor;
-abstract class CancellableStreamMessage<T> extends AbstractStreamMessage<T> {
static final Logger logger = LoggerFactory.getLogger(CancellableStreamMessage.class);
I didn't review this class carefully because the implementation of this class is derived from the old `AbstractStreamMessage`. Please, let me know if there are any changes you made. π
import io.netty.util.concurrent.EventExecutor;
+abstract class CancellableStreamMessage<T> extends AggregationSupport implements StreamMessage<T> {
static final Logger logger = LoggerFactory.getLogger(CancellableStreamMessage.class);
|
codereview_new_java_data_8208 | static HttpResponseBuilder builder() {
/**
* Aggregates this response with the specified {@link AggregationOptions}. The returned
* {@link CompletableFuture} will be notified when the content and the trailers of the response are
- * received fully.
* <pre>{@code
* AggregationOptions options =
* AggregationOptions.builder()
```suggestion
* fully received.
```
static HttpResponseBuilder builder() {
/**
* Aggregates this response with the specified {@link AggregationOptions}. The returned
* {@link CompletableFuture} will be notified when the content and the trailers of the response are
+ * fully received.
* <pre>{@code
* AggregationOptions options =
* AggregationOptions.builder() |
codereview_new_java_data_8209 | static AggregationOptionsBuilder builder() {
}
/**
- * Returns the {@link EventExecutor} that executes the aggregation on.
*/
EventExecutor executor();
```suggestion
* Returns the {@link EventExecutor} that executes the aggregation.
```
static AggregationOptionsBuilder builder() {
}
/**
+ * Returns the {@link EventExecutor} that executes the aggregation.
*/
EventExecutor executor();
|
codereview_new_java_data_8210 | public boolean isJson() {
}
/**
- * Returns {@code true} when the subtype is in [{@link MediaType#PROTOBUF}, {@link MediaType#X_PROTOBUF}, {@link MediaType#X_GOOGLE_PROTOBUF}].
* Otherwise {@code false}.
*
* <pre>{@code
We prefer to list elements using `and` or `or`.
```suggestion
* Returns {@code true} when the subtype is one of {@link MediaType#PROTOBUF}, {@link MediaType#X_PROTOBUF}, and {@link MediaType#X_GOOGLE_PROTOBUF}.
```
public boolean isJson() {
}
/**
+ * Returns {@code true} when the subtype is one of {@link MediaType#PROTOBUF}, {@link MediaType#X_PROTOBUF} and {@link MediaType#X_GOOGLE_PROTOBUF}.
* Otherwise {@code false}.
*
* <pre>{@code |
codereview_new_java_data_8211 | public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exc
responseFuture.completeExceptionally(t);
} else {
frameAndServe(unwrap(), ctx, grpcHeaders.build(), clientRequest.content(),
- responseFuture, null, responseContentType);
}
}
return null;
Incorrect indentation - can you check that your IDE is correctly formatted?
https://armeria.dev/community/developer-guide#setting-up-your-ide
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exc
responseFuture.completeExceptionally(t);
} else {
frameAndServe(unwrap(), ctx, grpcHeaders.build(), clientRequest.content(),
+ responseFuture, null, responseContentType);
}
}
return null; |
codereview_new_java_data_8212 | Queue<HealthCheckContextGroup> contextGroupChain() {
@VisibleForTesting
List<Endpoint> allHealthyEndpoints() {
synchronized (contextGroupChain) {
- if (contextGroupChain.isEmpty()) {
return ImmutableList.of();
}
final List<Endpoint> allHealthyEndpoints = new ArrayList<>();
- final HealthCheckContextGroup newGroup = contextGroupChain.getLast();
for (Endpoint candidate : newGroup.candidates()) {
if (healthyEndpoints.contains(candidate)) {
allHealthyEndpoints.add(candidate);
I thought using `pollLast` instead of `getLast` and returning empty on null is more natural, to only check contended `contextGroupChain` once (likely no difference in practice)
Queue<HealthCheckContextGroup> contextGroupChain() {
@VisibleForTesting
List<Endpoint> allHealthyEndpoints() {
synchronized (contextGroupChain) {
+ final HealthCheckContextGroup newGroup = contextGroupChain.pollLast();
+ if (newGroup == null) {
return ImmutableList.of();
}
final List<Endpoint> allHealthyEndpoints = new ArrayList<>();
for (Endpoint candidate : newGroup.candidates()) {
if (healthyEndpoints.contains(candidate)) {
allHealthyEndpoints.add(candidate); |
codereview_new_java_data_8213 | static void deframeAndRespond(ServiceRequestContext ctx,
try {
requireNonNull(grpcStatusCode, "grpc-status header must exist");
} catch (NullPointerException e) {
res.completeExceptionally(e);
return;
}
Let's close a pooled object (a reference counting object of Netty) before returning it. The ownership of the object is passed to this method. We should remove it if we don't ship the object to another place. https://netty.io/wiki/reference-counted-objects.html
```java
PooledObjects.close(grpcResponse.content());
```
static void deframeAndRespond(ServiceRequestContext ctx,
try {
requireNonNull(grpcStatusCode, "grpc-status header must exist");
} catch (NullPointerException e) {
+ PooledObjects.close(grpcResponse.content());
res.completeExceptionally(e);
return;
} |
codereview_new_java_data_8214 | static void deframeAndRespond(ServiceRequestContext ctx,
if (grpcStatusCode == null) {
PooledObjects.close(grpcResponse.content());
res.completeExceptionally(new NullPointerException("grpcStatusCode must not be null"));
- logger.warn("A gRPC response must have the {} header.", GrpcHeaderNames.GRPC_STATUS);
return;
}
Status grpcStatus = Status.fromCodeValue(Integer.parseInt(grpcStatusCode));
Should we add more context to the log message? It seems difficult to know which response omits `GrpcHeaderNames.GRPC_STATUS`.
```suggestion
logger.warn("{} A gRPC response must have the {} header. response: {}",
ctx, GrpcHeaderNames.GRPC_STATUS, grpcResponse);
```
static void deframeAndRespond(ServiceRequestContext ctx,
if (grpcStatusCode == null) {
PooledObjects.close(grpcResponse.content());
res.completeExceptionally(new NullPointerException("grpcStatusCode must not be null"));
+ logger.warn("{} A gRPC response must have the {} header. response: {}",
+ ctx, GrpcHeaderNames.GRPC_STATUS, grpcResponse);
return;
}
Status grpcStatus = Status.fromCodeValue(Integer.parseInt(grpcStatusCode)); |
codereview_new_java_data_8215 | void testUnwrap() {
@Test
void testUnwrapAll() {
final Foo foo = new Foo();
final Bar<Foo> bar = new Bar<>(foo);
- final Qux<Bar<Foo>> qux = new Qux<>(bar);
- final Foo root = qux.root();
- assertThat(root).isSameAs(foo);
}
private static final class Foo implements Unwrappable {}
Naming candidates I could think of are
1. `Unwrappable#root`
2. `Unwrappable#unwrapAll`
3. `Unwrappable#asRoot`
void testUnwrap() {
@Test
void testUnwrapAll() {
final Foo foo = new Foo();
+ assertThat(foo.root()).isSameAs(foo);
+
final Bar<Foo> bar = new Bar<>(foo);
+ assertThat(bar.root()).isSameAs(foo);
+ final Qux<Bar<Foo>> qux = new Qux<>(bar);
+ assertThat(qux.root()).isSameAs(foo);
}
private static final class Foo implements Unwrappable {} |
codereview_new_java_data_8216 | default Unwrappable unwrap() {
* }
* }
*
- * final Foo foo = new Foo();
- * foo.unwrapAll() == foo;
*
- * final Bar<Foo> bar = new Bar<>(foo);
- * bar.unwrapAll() == foo;
*
- * final Qux<Bar<Foo>> qux = new Qux<>(bar);
- * qux.unwrapAll() == foo;
* }</pre>
*/
default Unwrappable unwrapAll() {
- return this;
}
}
```suggestion
* assert foo.unwrapAll() == foo;
```
default Unwrappable unwrap() {
* }
* }
*
+ * Foo foo = new Foo();
+ * assert foo.unwrapAll() == foo;
*
+ * Bar<Foo> bar = new Bar<>(foo);
+ * assert bar.unwrapAll() == foo;
*
+ * Qux<Bar<Foo>> qux = new Qux<>(bar);
+ * assert qux.unwrap() == bar;
+ * assert qux.unwrapAll() == foo;
* }</pre>
*/
default Unwrappable unwrapAll() {
+ return unwrap();
}
} |
codereview_new_java_data_8217 | default Unwrappable unwrap() {
* }
* }
*
- * final Foo foo = new Foo();
- * foo.unwrapAll() == foo;
*
- * final Bar<Foo> bar = new Bar<>(foo);
- * bar.unwrapAll() == foo;
*
- * final Qux<Bar<Foo>> qux = new Qux<>(bar);
- * qux.unwrapAll() == foo;
* }</pre>
*/
default Unwrappable unwrapAll() {
- return this;
}
}
```suggestion
* Bar<Foo> bar = new Bar<>(foo);
* assert bar.unwrapAll() == foo;
```
default Unwrappable unwrap() {
* }
* }
*
+ * Foo foo = new Foo();
+ * assert foo.unwrapAll() == foo;
*
+ * Bar<Foo> bar = new Bar<>(foo);
+ * assert bar.unwrapAll() == foo;
*
+ * Qux<Bar<Foo>> qux = new Qux<>(bar);
+ * assert qux.unwrap() == bar;
+ * assert qux.unwrapAll() == foo;
* }</pre>
*/
default Unwrappable unwrapAll() {
+ return unwrap();
}
} |
codereview_new_java_data_8218 | default Unwrappable unwrap() {
* }
* }
*
- * final Foo foo = new Foo();
- * foo.unwrapAll() == foo;
*
- * final Bar<Foo> bar = new Bar<>(foo);
- * bar.unwrapAll() == foo;
*
- * final Qux<Bar<Foo>> qux = new Qux<>(bar);
- * qux.unwrapAll() == foo;
* }</pre>
*/
default Unwrappable unwrapAll() {
- return this;
}
}
How about also adding `unwrap()`?
```suggestion
* Qux<Bar<Foo>> qux = new Qux<>(bar);
* assert qux.unwrap() == bar;
* assert qux.unwrapAll() == foo;
```
default Unwrappable unwrap() {
* }
* }
*
+ * Foo foo = new Foo();
+ * assert foo.unwrapAll() == foo;
*
+ * Bar<Foo> bar = new Bar<>(foo);
+ * assert bar.unwrapAll() == foo;
*
+ * Qux<Bar<Foo>> qux = new Qux<>(bar);
+ * assert qux.unwrap() == bar;
+ * assert qux.unwrapAll() == foo;
* }</pre>
*/
default Unwrappable unwrapAll() {
+ return unwrap();
}
} |
codereview_new_java_data_8219 | default Unwrappable unwrap() {
* }</pre>
*/
default Unwrappable unwrapAll() {
- return unwrap();
}
}
Should we improve the default implementation to unwrap until the returned value is the same as the old value?
For example:
```java
Unwrappable unwrapped = this;
while (true) {
final Unwrappable inner = unwrapped.unwrap();
if (inner == unwrapped) {
return inner;
}
unwrapped = inner;
}
```
default Unwrappable unwrap() {
* }</pre>
*/
default Unwrappable unwrapAll() {
+ Unwrappable unwrapped = this;
+ while (true) {
+ final Unwrappable inner = unwrapped.unwrap();
+ if (inner == unwrapped) {
+ return inner;
+ }
+ unwrapped = inner;
+ }
}
} |
codereview_new_java_data_8220 | public interface DelegatingResponseConverterFunctionProvider {
* Returns a {@link ResponseConverterFunction} instance if the function can convert
* the {@code responseType}, otherwise return {@code null}.
* The {@link ResponseConverterFunction} passed in is a delegate function which will be used to convert
- * the {@code responseType}
*
* @param responseType the return {@link Type} of the annotated HTTP service method
* @param responseConverter the delegate {@link ResponseConverterFunction} which converts an object
```suggestion
* the {@code responseType}.
```
public interface DelegatingResponseConverterFunctionProvider {
* Returns a {@link ResponseConverterFunction} instance if the function can convert
* the {@code responseType}, otherwise return {@code null}.
* The {@link ResponseConverterFunction} passed in is a delegate function which will be used to convert
+ * the {@code responseType}.
*
* @param responseType the return {@link Type} of the annotated HTTP service method
* @param responseConverter the delegate {@link ResponseConverterFunction} which converts an object |
codereview_new_java_data_8221 |
import com.linecorp.armeria.server.annotation.ResponseConverterFunction;
/**
- * For use with ResponseConverterFunctionSelectorTest.
*/
public class TestDelegatingSpiConverterProvider implements DelegatingResponseConverterFunctionProvider {
```suggestion
* For use with ResponseConverterFunctionUtilTest.
```
import com.linecorp.armeria.server.annotation.ResponseConverterFunction;
/**
+ * For use with ResponseConverterFunctionUtilTest.
*/
public class TestDelegatingSpiConverterProvider implements DelegatingResponseConverterFunctionProvider {
|
codereview_new_java_data_8223 |
/**
* A {@link ResponseConverterFunction} provider interface which creates a new
* {@link ResponseConverterFunction} for converting an object of the given type and functions.
*/
@UnstableApi
@FunctionalInterface
Could you add this to the Javadoc of this interface?
` * @see DelegatingResponseConverterFunctionProvider`
/**
* A {@link ResponseConverterFunction} provider interface which creates a new
* {@link ResponseConverterFunction} for converting an object of the given type and functions.
+ *
+ * @see DelegatingResponseConverterFunctionProvider
*/
@UnstableApi
@FunctionalInterface |
codereview_new_java_data_8224 | public interface NamedTypeInfoProvider {
* {@code org.apache.thrift.TException} for {@code ThriftDocServicePlugin}</li>
* </ul>
*
- * @return a new {@link StructInfo}. {@code null} if this {@link NamedTypeInfoProvider} cannot convert the
- * {@code typeDescriptor} to the {@link NamedTypeInfo}.
*/
@Nullable
NamedTypeInfo newNamedTypeInfo(Object typeDescriptor);
```suggestion
* @return a new {@link NamedTypeInfo}. {@code null} if this {@link NamedTypeInfoProvider} cannot convert the
```
public interface NamedTypeInfoProvider {
* {@code org.apache.thrift.TException} for {@code ThriftDocServicePlugin}</li>
* </ul>
*
+ * @return a new {@link NamedTypeInfo}. {@code null} if this {@link NamedTypeInfoProvider} cannot convert
+ * the {@code typeDescriptor} to the {@link NamedTypeInfo}.
*/
@Nullable
NamedTypeInfo newNamedTypeInfo(Object typeDescriptor); |
codereview_new_java_data_8225 | public DocServiceBuilder injectedScriptSupplier(
}
/**
- * Adds the specified {@link NamedTypeInfoProvider}s used to create a {@link NamedTypeInfo} from
* a type descriptor.
*/
public DocServiceBuilder namedTypeInfoProvider(NamedTypeInfoProvider namedTypeInfoProvider) {
Since it's singular
```suggestion
* Adds the specified {@link NamedTypeInfoProvider} used to create a {@link NamedTypeInfo} from
```
public DocServiceBuilder injectedScriptSupplier(
}
/**
+ * Adds the specified {@link NamedTypeInfoProvider} used to create a {@link NamedTypeInfo} from
* a type descriptor.
*/
public DocServiceBuilder namedTypeInfoProvider(NamedTypeInfoProvider namedTypeInfoProvider) { |
codereview_new_java_data_8226 | private static <T> T extractFromGetter(JavaType classType, JavaType fieldType, S
return null;
}
- private StructInfo newReflectiveStructInfo(Class<?> clazz) {
return (StructInfo) ReflectiveNamedTypeInfoProvider.INSTANCE.newNamedTypeInfo(clazz);
}
}
Let's add `assert value != null;`
private static <T> T extractFromGetter(JavaType classType, JavaType fieldType, S
return null;
}
+ private static StructInfo newReflectiveStructInfo(Class<?> clazz) {
return (StructInfo) ReflectiveNamedTypeInfoProvider.INSTANCE.newNamedTypeInfo(clazz);
}
} |
codereview_new_java_data_8227 | public String name() {
/**
* Returns the alias of the {@link #name()}.
*/
@Nullable
@JsonInclude(Include.NON_NULL)
Can it be anything other than class name?
public String name() {
/**
* Returns the alias of the {@link #name()}.
+ * An alias could be set when a {@link StructInfo} has two different names.
+ *
+ * <p>For example, if a {@link StructInfo} is extracted from a {@code com.google.protobuf.Message},
+ * the {@link StructInfo#name()} is set to the full name defined in the proto file and the
+ * {@link StructInfo#alias()} is set to the {@linkplain Class#getName() name} of the generated
+ * {@link Class}.
*/
@Nullable
@JsonInclude(Include.NON_NULL) |
codereview_new_java_data_8228 |
/**
* A {@link NamedTypeInfoProvider} to create a {@link NamedTypeInfo} from a Thrift type such as {@link TBase}
- * , {@link TEnum} or {@link TException}.
*/
public final class ThriftNamedTypeInfoProvider implements NamedTypeInfoProvider {
Let's move `,` to the above line. π
/**
* A {@link NamedTypeInfoProvider} to create a {@link NamedTypeInfo} from a Thrift type such as {@link TBase}
+ * {@link TEnum} or {@link TException}.
*/
public final class ThriftNamedTypeInfoProvider implements NamedTypeInfoProvider {
|
codereview_new_java_data_8229 | public ServiceSpecification generateSpecification(Set<ServiceConfig> serviceConf
NamedTypeInfoProvider namedTypeInfoProvider) {
requireNonNull(serviceConfigs, "serviceConfigs");
requireNonNull(filter, "filter");
final Map<Class<?>, EntryBuilder> map = new LinkedHashMap<>();
```suggestion
requireNonNull(namedTypeInfoProvider, "namedTypeInfoProvider");
```
It can be checked non-null.
public ServiceSpecification generateSpecification(Set<ServiceConfig> serviceConf
NamedTypeInfoProvider namedTypeInfoProvider) {
requireNonNull(serviceConfigs, "serviceConfigs");
requireNonNull(filter, "filter");
+ requireNonNull(namedTypeInfoProvider, "namedTypeInfoProvider");
final Map<Class<?>, EntryBuilder> map = new LinkedHashMap<>();
|
codereview_new_java_data_8230 | public DocServiceBuilder injectedScriptSupplier(
return this;
}
/**
* Adds the specified {@link NamedTypeInfoProvider} used to create a {@link NamedTypeInfo} from
* a type descriptor.
How about supporting list of the `namedTypeInfoProvider` using `orElse`? π
I think it can be handled by various provider.
```
public DocServiceBuilder namedTypeInfoProvider(List<NamedTypeInfoProvider> namedTypeInfoProvider)
```
public DocServiceBuilder injectedScriptSupplier(
return this;
}
+ /**
+ * Adds the specified {@link NamedTypeInfoProvider}s used to create a {@link NamedTypeInfo} from
+ * a type descriptor.
+ */
+ public DocServiceBuilder namedTypeInfoProvider(
+ Iterable<? extends NamedTypeInfoProvider> namedTypeInfoProviders) {
+ requireNonNull(namedTypeInfoProviders, "namedTypeInfoProviders");
+ for (NamedTypeInfoProvider typeInfoProvider : namedTypeInfoProviders) {
+ namedTypeInfoProvider(typeInfoProvider);
+ }
+ return this;
+ }
+
/**
* Adds the specified {@link NamedTypeInfoProvider} used to create a {@link NamedTypeInfo} from
* a type descriptor. |
codereview_new_java_data_8231 | public NamedTypeInfo newNamedTypeInfo(Object typeDescriptor) {
}
final Class<?> clazz = (Class<?>) typeDescriptor;
- if (clazz.isEnum()) {
@SuppressWarnings("unchecked")
final Class<? extends Enum<? extends TEnum>> enumType =
(Class<? extends Enum<? extends TEnum>>) clazz;
I think `clazz.isEnum()` can also be true for non-thrift objects.
If a user is
1. Loading `ThriftNamedTypeInfoProvider` via SPI
2. A different implementation (say `GrpcDocService`) tries to find a `namedTypeInfo` for an enum, a `ClassCastException` will occur in the next line.
```suggestion
if (TEnum.class.isAssignableFrom(clazz)) {
```
public NamedTypeInfo newNamedTypeInfo(Object typeDescriptor) {
}
final Class<?> clazz = (Class<?>) typeDescriptor;
+ if (TEnum.class.isAssignableFrom(clazz)) {
@SuppressWarnings("unchecked")
final Class<? extends Enum<? extends TEnum>> enumType =
(Class<? extends Enum<? extends TEnum>>) clazz; |
codereview_new_java_data_8232 |
import com.linecorp.armeria.client.endpoint.EndpointGroup;
import com.linecorp.armeria.common.logging.RequestLog;
import com.linecorp.armeria.internal.common.CancellationScheduler;
/**
* This class exposes extension methods for {@link ClientRequestContext}
* which are used internally by Armeria but aren't intended for public usage.
- * Advanced users who have implemented their own concrete
- * {@link ClientRequestContext} may extend this interface. It is highly
- * recommended to consult with the maintainers before using this class.
*/
-public interface ClientRequestContextExtension extends ClientRequestContext {
/**
* Returns the {@link CancellationScheduler} used to schedule a response timeout.
Should we make `ClientRequestContextExtension` extend `RequestContextExtension`
so that we can use `RequestContextExtension` methods from `ClientRequestContextExtension`?
import com.linecorp.armeria.client.endpoint.EndpointGroup;
import com.linecorp.armeria.common.logging.RequestLog;
import com.linecorp.armeria.internal.common.CancellationScheduler;
+import com.linecorp.armeria.internal.common.RequestContextExtension;
/**
* This class exposes extension methods for {@link ClientRequestContext}
* which are used internally by Armeria but aren't intended for public usage.
*/
+public interface ClientRequestContextExtension extends ClientRequestContext, RequestContextExtension {
/**
* Returns the {@link CancellationScheduler} used to schedule a response timeout. |
codereview_new_java_data_8233 | protected RequestContextWrapper(T delegate) {
/**
* Returns the delegate context.
*/
protected final T delegate() {
return unwrap();
}
How about deprecating this method?
protected RequestContextWrapper(T delegate) {
/**
* Returns the delegate context.
*/
+ @Deprecated
protected final T delegate() {
return unwrap();
} |
codereview_new_java_data_8234 | private static EnumInfo newEnumInfo(Class<?> enumClass) {
final Field[] declaredFields = enumClass.getDeclaredFields();
final List<EnumValueInfo> values =
Stream.of(declaredFields)
- .filter(Field::isEnumConstant)
.map(f -> {
final Description valueDescription = AnnotationUtil.findFirst(f, Description.class);
if (valueDescription != null) {
nit: indentation
```suggestion
Stream.of(declaredFields)
.filter(Field::isEnumConstant)
```
private static EnumInfo newEnumInfo(Class<?> enumClass) {
final Field[] declaredFields = enumClass.getDeclaredFields();
final List<EnumValueInfo> values =
Stream.of(declaredFields)
+ .filter(Field::isEnumConstant)
.map(f -> {
final Description valueDescription = AnnotationUtil.findFirst(f, Description.class);
if (valueDescription != null) { |
codereview_new_java_data_8236 | public final class FieldInfoBuilder {
FieldInfoBuilder(String name, TypeSignature typeSignature) {
this.name = requireNonNull(name, "name");
this.typeSignature = requireNonNull(typeSignature, "typeSignature");
- this.childFieldInfos = ImmutableList.of();
}
FieldInfoBuilder(String name, TypeSignature typeSignature, FieldInfo... childFieldInfos) {
```suggestion
childFieldInfos = ImmutableList.of();
```
public final class FieldInfoBuilder {
FieldInfoBuilder(String name, TypeSignature typeSignature) {
this.name = requireNonNull(name, "name");
this.typeSignature = requireNonNull(typeSignature, "typeSignature");
+ childFieldInfos = ImmutableList.of();
}
FieldInfoBuilder(String name, TypeSignature typeSignature, FieldInfo... childFieldInfos) { |
codereview_new_java_data_8237 | public static FieldInfo of(String name, TypeSignature typeSignature) {
}
/**
- * Creates a new {@link FieldInfo} with the specified {@code name}, {@link TypeSignature} and DocString.
* The {@link FieldLocation} and {@link FieldRequirement} of the {@link FieldInfo} will be
* {@code UNSPECIFIED}.
*/
```suggestion
* Creates a new {@link FieldInfo} with the specified {@code name}, {@link TypeSignature} and description.
```
public static FieldInfo of(String name, TypeSignature typeSignature) {
}
/**
+ * Creates a new {@link FieldInfo} with the specified {@code name}, {@link TypeSignature} and description.
* The {@link FieldLocation} and {@link FieldRequirement} of the {@link FieldInfo} will be
* {@code UNSPECIFIED}.
*/ |
codereview_new_java_data_8238 | public List<FieldInfo> fields() {
* Returns the description information of the struct.
*/
@JsonProperty
@JsonInclude(Include.NON_NULL)
@Nullable
public DescriptionInfo descriptionInfo() {
```suggestion
@JsonProperty
@Override
```
public List<FieldInfo> fields() {
* Returns the description information of the struct.
*/
@JsonProperty
+ @Override
@JsonInclude(Include.NON_NULL)
@Nullable
public DescriptionInfo descriptionInfo() { |
codereview_new_java_data_8239 | void jsonSpecification() throws InterruptedException {
addPeriodMethodInfo(methodInfos);
addMarkdownDescriptionMethodInfo(methodInfos);
addMermaidDescriptionMethodInfo(methodInfos);
- final Map<Class<?>, DescriptionInfo> serviceDescription = ImmutableMap.of(MyService.class,
- DescriptionInfo.of(
- "My service class"));
final JsonNode expectedJson = mapper.valueToTree(AnnotatedDocServicePlugin.generate(
serviceDescription, methodInfos));
```suggestion
final Map<Class<?>, DescriptionInfo> serviceDescription = ImmutableMap.of(
MyService.class, DescriptionInfo.of("My service class"));
```
void jsonSpecification() throws InterruptedException {
addPeriodMethodInfo(methodInfos);
addMarkdownDescriptionMethodInfo(methodInfos);
addMermaidDescriptionMethodInfo(methodInfos);
+ final Map<Class<?>, DescriptionInfo> serviceDescription = ImmutableMap.of(
+ MyService.class, DescriptionInfo.of("My service class"));
final JsonNode expectedJson = mapper.valueToTree(AnnotatedDocServicePlugin.generate(
serviceDescription, methodInfos)); |
codereview_new_java_data_8240 | private static EnumInfo newEnumInfo(Class<?> enumClass) {
return new EnumValueInfo(f.getName(), null);
})
- .collect(Collectors.toList());
if (description != null) {
return new EnumInfo(name, values, DescriptionInfo.of(description.value(), description.markup()));
To avoid an addtional copy when creating `EnumInfo`.
```suggestion
.collect(toImmutableList());
```
private static EnumInfo newEnumInfo(Class<?> enumClass) {
return new EnumValueInfo(f.getName(), null);
})
+ .collect(toImmutableList());
if (description != null) {
return new EnumInfo(name, values, DescriptionInfo.of(description.value(), description.markup())); |
codereview_new_java_data_8241 | public Markup markup() {
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
- .omitNullValues()
.add("docString", docString)
.add("markup", markup)
.toString();
Not required because all values are not null.
```suggestion
```
public Markup markup() {
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("docString", docString)
.add("markup", markup)
.toString(); |
codereview_new_java_data_8242 | public HttpMethod httpMethod() {
}
/**
- * Returns the description information object of the function.
*/
@JsonProperty
@JsonInclude(Include.NON_NULL)
How about removing `object` from the Javadoc? `object` seems not to deliver any useful information.
```suggestion
* Returns the description information of the function.
```
public HttpMethod httpMethod() {
}
/**
+ * Returns the description information of the function.
*/
@JsonProperty
@JsonInclude(Include.NON_NULL) |
codereview_new_java_data_8243 | public List<FieldInfo> fields() {
}
/**
- * Returns the description information of the struct.
*/
@JsonProperty
@Override
```suggestion
* Returns the description information of this struct.
```
public List<FieldInfo> fields() {
}
/**
+ * Returns the description information of this struct.
*/
@JsonProperty
@Override |
codereview_new_java_data_8244 | public HttpResponse period(@Param Period period) {
@Description(value = "## Description method with markdown", markup = Markup.MARKDOWN)
@Get("/markdown")
public String description(@Param @Description(value = "DESCRIPTION `PARAM`", markup = Markup.MARKDOWN)
- DescriptionEnum descriptionEnum) {
return descriptionEnum.name();
}
nit: Indent?
```suggestion
public String description(@Param @Description(value = "DESCRIPTION `PARAM`", markup = Markup.MARKDOWN)
DescriptionEnum descriptionEnum) {
```
public HttpResponse period(@Param Period period) {
@Description(value = "## Description method with markdown", markup = Markup.MARKDOWN)
@Get("/markdown")
public String description(@Param @Description(value = "DESCRIPTION `PARAM`", markup = Markup.MARKDOWN)
+ DescriptionEnum descriptionEnum) {
return descriptionEnum.name();
}
|
codereview_new_java_data_8245 | public List<EnumValueInfo> values() {
}
/**
- * Returns description information of the enum.
*/
@Override
public DescriptionInfo descriptionInfo() {
```suggestion
* Returns the description information of the enum.
```
public List<EnumValueInfo> values() {
}
/**
+ * Returns the description information of the enum.
*/
@Override
public DescriptionInfo descriptionInfo() { |
codereview_new_java_data_8246 |
String value() default DefaultValues.UNSPECIFIED;
/**
- * The supported markup type in doc service.
*/
Markup markup() default Markup.NONE;
}
```suggestion
* The supported markup type in {@link DocService}.
```
String value() default DefaultValues.UNSPECIFIED;
/**
+ * The supported markup type in {@link DocService}.
*/
Markup markup() default Markup.NONE;
} |
codereview_new_java_data_8247 |
@UnstableApi
public enum Markup {
/**
- * The field is not support markup types.
*/
NONE,
/**
- * The field is support the markdown.
*/
MARKDOWN,
/**
- * The field is support the mermaid.
*/
MERMAID
}
The sentences seem not to be grammatically complete. How about just linking to reference sites.
```suggestion
* No markup.
*/
NONE,
/**
* <a href="https://en.wikipedia.org/wiki/Markdown">Markdown</a>.
*/
MARKDOWN,
/**
* <a href="https://mermaid-js.github.io/mermaid/#/">Mermaid</a>.
```
@UnstableApi
public enum Markup {
/**
+ * No markup.
*/
NONE,
/**
+ * <a href="https://en.wikipedia.org/wiki/Markdown">Markdown</a>.
*/
MARKDOWN,
/**
+ * <a href="https://mermaid-js.github.io/mermaid/#/">Mermaid</a>.
*/
MERMAID
} |
codereview_new_java_data_8248 | public static DescriptionInfo of(String docString) {
* @param docString the documentation string
* @param markup the supported markup string
*/
- DescriptionInfo(String docString, Markup markup) {
this.docString = requireNonNull(docString, "docString");
this.markup = requireNonNull(markup, "markup");
}
```suggestion
private DescriptionInfo(String docString, Markup markup) {
```
public static DescriptionInfo of(String docString) {
* @param docString the documentation string
* @param markup the supported markup string
*/
+ private DescriptionInfo(String docString, Markup markup) {
this.docString = requireNonNull(docString, "docString");
this.markup = requireNonNull(markup, "markup");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.