id
stringlengths 29
30
| content
stringlengths 152
2.6k
|
|---|---|
codereview_new_java_data_6585
|
public class SsoAccessToken implements SdkToken {
private final Instant expiresAt;
private SsoAccessToken(BuilderImpl builder) {
- Validate.paramNotNull(builder.accessToken, "accessToken");
- Validate.paramNotNull(builder.expiresAt, "expiresAt");
- this.accessToken = builder.accessToken;
- this.expiresAt = builder.expiresAt;
}
public static Builder builder() {
Nit: can be shortened to `this.accessToken = Validate.paramNotNull(builder.accessToken, "accessToken");`
public class SsoAccessToken implements SdkToken {
private final Instant expiresAt;
private SsoAccessToken(BuilderImpl builder) {
+ this.accessToken = Validate.paramNotNull(builder.accessToken, "accessToken");
+ this.expiresAt = Validate.paramNotNull(builder.expiresAt, "expiresAt");
}
public static Builder builder() {
|
codereview_new_java_data_6586
|
public Builder profile(Profile profile) {
/**
* *
- * @param profileFile : ProfileFile that has the profile which is used to create the credential provider.
- * This is required to fetch the titles like sso-session defined in profile property*
- * *
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder profileFile(ProfileFile profileFile) {
Nit: formatting seems a bit off.
There's also an extra `*` in the second line for every method
public Builder profile(Profile profile) {
/**
* *
+ * @param profileFile The ProfileFile that has the profile which is used to create the credential provider. This is *
+ * required to fetch the titles like sso-session defined in profile property* *
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder profileFile(ProfileFile profileFile) {
|
codereview_new_java_data_6587
|
package software.amazon.awssdk.services.cloudfront.internal.auth;
import java.util.Arrays;
public enum PemObjectType {
PRIVATE_KEY_PKCS1("-----BEGIN RSA PRIVATE KEY-----"),
PRIVATE_KEY_PKCS8("-----BEGIN PRIVATE KEY-----"),
Internal Sdk annotation missing
package software.amazon.awssdk.services.cloudfront.internal.auth;
import java.util.Arrays;
+import software.amazon.awssdk.annotations.SdkInternalApi;
+@SdkInternalApi
public enum PemObjectType {
PRIVATE_KEY_PKCS1("-----BEGIN RSA PRIVATE KEY-----"),
PRIVATE_KEY_PKCS8("-----BEGIN PRIVATE KEY-----"),
|
codereview_new_java_data_6588
|
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
@SdkPublicApi
public interface CookiesForCannedPolicy extends SignedCookie,
ToCopyableBuilder<CookiesForCannedPolicy.Builder, CookiesForCannedPolicy> {
String EXPIRES_KEY = "CloudFront-Expires";
/**
- * Returns the expires key
- */
- String expiresKey();
-
- /**
- * Returns the expires value
*/
- String expiresValue();
@NotThreadSafe
interface Builder extends CopyableBuilder<CookiesForCannedPolicy.Builder, CookiesForCannedPolicy> {
What are these? How should they be used?
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
+/**
+ * Base interface class for CloudFront cookies with canned policies
+ */
@SdkPublicApi
public interface CookiesForCannedPolicy extends SignedCookie,
ToCopyableBuilder<CookiesForCannedPolicy.Builder, CookiesForCannedPolicy> {
String EXPIRES_KEY = "CloudFront-Expires";
/**
+ * Returns the cookie expires header value
*/
+ String expiresHeaderValue();
@NotThreadSafe
interface Builder extends CopyableBuilder<CookiesForCannedPolicy.Builder, CookiesForCannedPolicy> {
|
codereview_new_java_data_6589
|
import software.amazon.awssdk.utils.Validate;
/**
- * The class is used for Response Handling and Parsing the metadata fetched by the get call in the {@link Ec2MetadataClient}
* interface.
* The class provides convenience methods to the users to parse the metadata as a String, List and Document.
*/
Nit: Can we change this to lower case `response handling` and `parsing`?
import software.amazon.awssdk.utils.Validate;
/**
+ * The class is used for response handling and parsing the metadata fetched by the get call in the {@link Ec2MetadataClient}
* interface.
* The class provides convenience methods to the users to parse the metadata as a String, List and Document.
*/
|
codereview_new_java_data_6590
|
static Ec2MetadataAsyncClient.Builder builder() {
}
/**
- * The builder definition for a {@link Ec2MetadataClient}.
*/
interface Builder {
Can we describe in the javadocs if the parameter is optional and if so what the default value is??
Maybe something along the lines of
_Define the [something]. By default, [...]_ or
_Define an optional [something]. By default, [...]_
static Ec2MetadataAsyncClient.Builder builder() {
}
/**
+ * The builder definition for a {@link Ec2MetadataClient}. All parameters are optional and have default values if not
+ * specified. Therefore, an instance can be simply created with {@code Ec2MetadataAsyncClient.builder().build()} or {@code
+ * Ec2MetadataAsyncClient.create()}, both having the same result.
*/
interface Builder {
|
codereview_new_java_data_6591
|
private Ec2MetadataEndpointProvider(Builder builder) {
/**
* Resolve the endpoint to be used for the {@link DefaultEc2MetadataClient} client. Users may manually provide an endpoint
- * through the {@code AWS_EC2_METADATA_SERVICE_ENDPOINT} environment variable or th {@code ec2_metadata_service_endpoint}
* key in
* their aws config file.
* If an endpoint is specified is this manner, use it. If no value are provide, the defaults to:
Nit: propagating `th` instead of `the`
private Ec2MetadataEndpointProvider(Builder builder) {
/**
* Resolve the endpoint to be used for the {@link DefaultEc2MetadataClient} client. Users may manually provide an endpoint
+ * through the {@code AWS_EC2_METADATA_SERVICE_ENDPOINT} environment variable or the {@code ec2_metadata_service_endpoint}
* key in
* their aws config file.
* If an endpoint is specified is this manner, use it. If no value are provide, the defaults to:
|
codereview_new_java_data_6592
|
import software.amazon.awssdk.utils.Validate;
/**
- * The class is used for Response Handling and Parsing the metadata fetched by the get call in the {@link Ec2MetadataClient}
* interface.
* The class provides convenience methods to the users to parse the metadata as a String, List and Document.
*/
Nit: change to lower case for "response handling" and "parsing"
import software.amazon.awssdk.utils.Validate;
/**
+ * The class is used for response handling and parsing the metadata fetched by the get call in the {@link Ec2MetadataClient}
* interface.
* The class provides convenience methods to the users to parse the metadata as a String, List and Document.
*/
|
codereview_new_java_data_6593
|
@SdkPublicApi
public enum EndpointMode {
- IPV4("http://169.254.169.254"),
- IPV6("http://[fd00:ec2::254]");
-
- public final String serviceEndpoint;
-
- EndpointMode(String serviceEndpoint) {
- this.serviceEndpoint = serviceEndpoint;
- }
-
- // public String getServiceEndpoint() {
- // return this.serviceEndpoint;
- // }
/**
* Returns the appropriate EndpointMode Value after parsing the parameter.
I'd prefer not to hard code endpoints here because it makes it harder to deprecate existing endpoints and introduce new ones. The default endpoints are internal implementation imo.
@SdkPublicApi
public enum EndpointMode {
+ IPV4,
+ IPV6;
/**
* Returns the appropriate EndpointMode Value after parsing the parameter.
|
codereview_new_java_data_6594
|
public CompletableFuture<Void> execute(AsyncExecuteRequest asyncRequest) {
paramNotNull(asyncRequest.requestContentPublisher(), "RequestContentPublisher");
paramNotNull(asyncRequest.responseHandler(), "ResponseHandler");
- MetricCollector metricCollector = asyncRequest.metricCollector().orElseGet(NoOpMetricCollector::create);
- metricCollector.reportMetric(HTTP_CLIENT_NAME, clientName());
/*
* See the note on getOrCreateConnectionPool()
Should we not call report metrics if `asyncRequest.metricCollector()` is not present or it's an instance of NoOpMetricCollector (the default SDK metric collector) to avoid potential performance degradation? We skip metrics collection in netty and apache http client fwiw
https://github.com/aws/aws-sdk-java-v2/blob/master/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/NettyRequestMetrics.java#L46-L49
public CompletableFuture<Void> execute(AsyncExecuteRequest asyncRequest) {
paramNotNull(asyncRequest.requestContentPublisher(), "RequestContentPublisher");
paramNotNull(asyncRequest.responseHandler(), "ResponseHandler");
+ if (asyncRequest.metricCollector().isPresent()) {
+ MetricCollector metricCollector = asyncRequest.metricCollector().get();
+
+ if (metricCollector != null && !(metricCollector instanceof NoOpMetricCollector)) {
+ metricCollector.reportMetric(HTTP_CLIENT_NAME, clientName());
+ }
+ }
/*
* See the note on getOrCreateConnectionPool()
|
codereview_new_java_data_6595
|
private CrtRequestContext(Builder builder) {
this.request = builder.request;
this.readBufferSize = builder.readBufferSize;
this.crtConnPool = builder.crtConnPool;
-
- if (this.request.metricCollector().isPresent()) {
- this.metricCollector = this.request.metricCollector().get();
- } else {
- this.metricCollector = null;
- }
}
public static Builder builder() {
nit, can be simplified as `this.metricCollector = request.metricCollector().orElse(null)`;
private CrtRequestContext(Builder builder) {
this.request = builder.request;
this.readBufferSize = builder.readBufferSize;
this.crtConnPool = builder.crtConnPool;
+ this.metricCollector = request.metricCollector().orElse(null);
}
public static Builder builder() {
|
codereview_new_java_data_6596
|
* small parts from a single object. The Transfer Manager is built on top of the Java bindings of the AWS Common Runtime S3 client
* and leverages Amazon S3 multipart upload and byte-range fetches for parallel transfers.
*
- * <h1>Instantiate a Transfer Manager</h1>
- * <b>Create a transfer manager with SDK default settings</b>
* {@snippet class = software.amazon.awssdk.transfer.s3.samples.S3TransferManagerSamples region = defaultTM}
- * <b>Create a transfer manager with custom settings</b>
* {@snippet class = software.amazon.awssdk.transfer.s3.samples.S3TransferManagerSamples region = customTM}
* <h1>Common Usage Patterns</h1>
* <b>Upload a file to S3</b>
Nit: Create a transfer manager instance
* small parts from a single object. The Transfer Manager is built on top of the Java bindings of the AWS Common Runtime S3 client
* and leverages Amazon S3 multipart upload and byte-range fetches for parallel transfers.
*
+ * <h1>Instantiate Transfer Manager</h1>
+ * <b>Create a transfer manager instance with SDK default settings</b>
* {@snippet class = software.amazon.awssdk.transfer.s3.samples.S3TransferManagerSamples region = defaultTM}
+ * <b>Create a transfer manager instance with custom settings</b>
* {@snippet class = software.amazon.awssdk.transfer.s3.samples.S3TransferManagerSamples region = customTM}
* <h1>Common Usage Patterns</h1>
* <b>Upload a file to S3</b>
|
codereview_new_java_data_6597
|
private Function<String, Instant> safeParseDate(Function<String, Instant> dateUn
@Override
public Map<String, Object> unmarshall(JsonNode jsonContent, SdkField<?> field) {
- if (jsonContent == null || jsonContent.isNull()) {
return null;
}
Query : jsonContent.isNull does this mean empty json {} , why dont we use [NullJsonNode](https://github.com/aws/aws-sdk-java-v2/blob/master/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/NullJsonNode.java)
private Function<String, Instant> safeParseDate(Function<String, Instant> dateUn
@Override
public Map<String, Object> unmarshall(JsonNode jsonContent, SdkField<?> field) {
+ if (jsonContent == null) {
return null;
}
|
codereview_new_java_data_6598
|
private void attemptExecute(CompletableFuture<Response<OutputT>> future) {
if (exception instanceof Error) {
future.completeExceptionally(exception);
} else {
- maybeRetryExecute(future, (Exception) exception);
}
return;
}
Is this cast necessary?
private void attemptExecute(CompletableFuture<Response<OutputT>> future) {
if (exception instanceof Error) {
future.completeExceptionally(exception);
} else {
+ maybeRetryExecute(future, exception);
}
return;
}
|
codereview_new_java_data_6599
|
private URI endpointFromConfig(SdkClientConfiguration config) {
.withRegion(config.option(AwsClientOption.AWS_REGION))
.withProfileFile(() -> config.option(SdkClientOption.PROFILE_FILE))
.withProfileName(config.option(SdkClientOption.PROFILE_NAME))
// .putAdvancedOption(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT,
// config.option(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT))
// .withDualstackEnabled(config.option(AwsClientOption.DUALSTACK_ENDPOINT_ENABLED))
Why is this commented ? Can we remove this or Add a TODO: to remove this
private URI endpointFromConfig(SdkClientConfiguration config) {
.withRegion(config.option(AwsClientOption.AWS_REGION))
.withProfileFile(() -> config.option(SdkClientOption.PROFILE_FILE))
.withProfileName(config.option(SdkClientOption.PROFILE_NAME))
+ // TODO: disabled because this early check cases tests in endpoint-tests.json to fail.
// .putAdvancedOption(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT,
// config.option(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT))
// .withDualstackEnabled(config.option(AwsClientOption.DUALSTACK_ENDPOINT_ENABLED))
|
codereview_new_java_data_6600
|
default B serviceConfiguration(Consumer<ServiceConfiguration.Builder> serviceCon
return serviceConfiguration(ServiceConfiguration.builder().applyMutation(serviceConfiguration).build());
}
B endpointProvider(JsonEndpointProvider endpointProvider);
}
Should we add Javadoc?
default B serviceConfiguration(Consumer<ServiceConfiguration.Builder> serviceCon
return serviceConfiguration(ServiceConfiguration.builder().applyMutation(serviceConfiguration).build());
}
+ /**
+ * Set the {@link JsonEndpointProvider} implementation that will be used by the client to determine the endpoint for
+ * each request. This is optional; if none is provided a default implementation will be used the SDK.
+ */
B endpointProvider(JsonEndpointProvider endpointProvider);
}
|
codereview_new_java_data_6601
|
public enum ProxySystemSetting implements SystemSetting {
HTTPS_PROXY_HOST("https.proxyHost"),
HTTPS_PROXY_PORT("https.proxyPort"),
- HTTPS_NON_PROXY_HOSTS("https.nonProxyHosts"),
HTTPS_PROXY_USERNAME("https.proxyUser"),
HTTPS_PROXY_PASSWORD("https.proxyPassword")
;
I don't think we need `HTTPS_NON_PROXY_HOSTS("https.nonProxyHosts")`
https://docs.oracle.com/javase/8/docs/technotes/guides/net/proxies.html
>As you probably guessed these work in the exact same manner as their http counterparts, so we won't go into much detail except to mention that the default port number, this time, is 443 and that for the "non proxy hosts" list, the HTTPS protocol handler will use the same as the http handler (i.e. http.nonProxyHosts).
public enum ProxySystemSetting implements SystemSetting {
HTTPS_PROXY_HOST("https.proxyHost"),
HTTPS_PROXY_PORT("https.proxyPort"),
HTTPS_PROXY_USERNAME("https.proxyUser"),
HTTPS_PROXY_PASSWORD("https.proxyPassword")
;
|
codereview_new_java_data_6602
|
private static String getMessageForTooManyAcquireOperationsError() {
+ "Consider taking any of the following actions to mitigate the issue: increase max connections, "
+ "increase max pending acquire count, decrease connection acquisition timeout, or "
- + "slowing the request rate.\n"
+ "Increasing the max connections can increase client throughput (unless the network interface is already "
+ "fully utilized), but can eventually start to hit operation system limitations on the number of file "
nit on something you didn't write (I probably wrote it): Can we make it "slow" instead of "slowing" to match "increase" (instead of increasing) and "decrease" (instead of decreasing)?
(Active voice is better than the passive voice)
private static String getMessageForTooManyAcquireOperationsError() {
+ "Consider taking any of the following actions to mitigate the issue: increase max connections, "
+ "increase max pending acquire count, decrease connection acquisition timeout, or "
+ + "slow the request rate.\n"
+ "Increasing the max connections can increase client throughput (unless the network interface is already "
+ "fully utilized), but can eventually start to hit operation system limitations on the number of file "
|
codereview_new_java_data_6603
|
public static long calculateStreamContentLength(long originalLength, long defaul
long allChunks = maxSizeChunks * calculateChunkLength(defaultChunkSize);
long remainingInChunk = remainingBytes > 0 ? calculateChunkLength(remainingBytes) : 0;
- long lastByteSize = (long) "0".length() + (long) CRLF.length();
return allChunks + remainingInChunk + lastByteSize;
}
nit: "0".length() looks pretty weird to me. Can we just use `1`?
public static long calculateStreamContentLength(long originalLength, long defaul
long allChunks = maxSizeChunks * calculateChunkLength(defaultChunkSize);
long remainingInChunk = remainingBytes > 0 ? calculateChunkLength(remainingBytes) : 0;
+ // last byte is composed of a "0" and "\r\n"
+ long lastByteSize = 1 + (long) CRLF.length();
return allChunks + remainingInChunk + lastByteSize;
}
|
codereview_new_java_data_6604
|
public class ParameterModel {
private String type;
public String getType() {
return type;
}
Can we have a java doc since its not clear what does Type signifies here.
public class ParameterModel {
private String type;
+ /**
+ * The type of this parameter. Currently, only "boolean" and "string" are
+ * permitted for parameters.
+ */
public String getType() {
return type;
}
|
codereview_new_java_data_6605
|
public static Endpoint fromNode(JsonNode node) {
headersNode.asObject()
.forEach((k, v) -> v.asArray().forEach(e -> b.addHeader(k, e.asString())));
}
- // ObjectNode on = node.expectObjectNode("endpoints are object nodes");
- // on.expectNoAdditionalProperties(Arrays.asList("properties", "url", "headers"));
- // builder.url(on.expectStringMember("url").getValue());
- // on.getObjectMember("properties").ifPresent(props -> {
- // props.getMembers().forEach((k, v) -> {
- // builder.property(k.getValue(), Value.fromNode(v));
- // });
- //
- // });
- //
- // on.getObjectMember("headers").ifPresent(headers -> headers.getMembers().forEach(((key, value) -> {
- // String name = key.getValue();
- // value.expectArrayNode("Header values must be an array").getElements()
- // .forEach(e -> builder.addHeader(name, e.expectStringNode().getValue()));
- // })));
return b.build();
}
Is this supposed to be commented out?
public static Endpoint fromNode(JsonNode node) {
headersNode.asObject()
.forEach((k, v) -> v.asArray().forEach(e -> b.addHeader(k, e.asString())));
}
+
return b.build();
}
|
codereview_new_java_data_6606
|
public void stringBufferAttributeConverterBehaves() {
public void localeAttributeConverterBehaves() {
LocaleAttributeConverter converter = LocaleAttributeConverter.create();
- assertThat(transformFrom(converter, Locale.US).s()).isEqualTo(Locale.US);
assertThat(transformTo(converter, fromString("en-US"))).isEqualTo(Locale.US);
}
It seems this test failed. I guess Locale.toString is still using legacy format due to backwards-compatibility reasons.
```
expected: en_US
but was: "en-US"
at software.amazon.awssdk.enhanced.dynamodb.converters.attribute.StringAttributeConvertersTest.localeAttributeConverterBehaves(StringAttributeConvertersTest.java:187)
```
public void stringBufferAttributeConverterBehaves() {
public void localeAttributeConverterBehaves() {
LocaleAttributeConverter converter = LocaleAttributeConverter.create();
+ assertThat(transformFrom(converter, Locale.US).s()).isEqualTo("en-US");
assertThat(transformTo(converter, fromString("en-US"))).isEqualTo(Locale.US);
}
|
codereview_new_java_data_6607
|
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
@SdkInternalApi
-public class DocumentUnmarshaller implements JsonNodeVisitor<Document> {
@Override
public Document visitNull() {
return Document.fromNull();
Should be `final`. We should also have tests for this.
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
@SdkInternalApi
+public final class DocumentUnmarshaller implements JsonNodeVisitor<Document> {
@Override
public Document visitNull() {
return Document.fromNull();
|
codereview_new_java_data_6608
|
private int statusCode(SdkHttpFullResponse response, Optional<ExceptionMetadata>
return response.statusCode();
}
- if (modeledExceptionMetadata.isPresent()) {
- ExceptionMetadata md = modeledExceptionMetadata.get();
-
- if (md.httpStatusCode() != null) {
- return md.httpStatusCode();
- }
-
- if (md.isFault() != null) {
- if (md.isFault()) {
- return 500;
- }
- return 400;
- }
- }
-
- return 500;
}
/**
Should we maybe just set the status code to 400/500 based on isFault within the code generator so that we don't need to use isFault in the runtime?
private int statusCode(SdkHttpFullResponse response, Optional<ExceptionMetadata>
return response.statusCode();
}
+ return modeledExceptionMetadata.filter(m -> m.httpStatusCode() != null)
+ .map(ExceptionMetadata::httpStatusCode)
+ .orElse(500);
}
/**
|
codereview_new_java_data_6609
|
/**
* Interface for specifying a retry policy to use when evaluating whether or not a request should be retried , and the gap
* between each retry. The {@link #builder()} can be used to construct a retry policy with numRetries and backoffStrategy.
* When using the {@link #builder()} the SDK will use default values for fields that are not provided.A custom BackoffStrategy
- * can be used to construct a policy or a default {@link BackoffStrategy} is used .
- * <p></p>
* @see BackoffStrategy for a list of SDK provided backoff strategies
*/
@SdkPublicApi
To clarify, we need to have `<p>` but not `</p`>. Please check out https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html#styleguide
/**
* Interface for specifying a retry policy to use when evaluating whether or not a request should be retried , and the gap
* between each retry. The {@link #builder()} can be used to construct a retry policy with numRetries and backoffStrategy.
+ * <p>
* When using the {@link #builder()} the SDK will use default values for fields that are not provided.A custom BackoffStrategy
+ * can be used to construct a policy or a default {@link BackoffStrategy} is used.
+ *
* @see BackoffStrategy for a list of SDK provided backoff strategies
*/
@SdkPublicApi
|
codereview_new_java_data_6610
|
private void acceptNewConnection() {
LOGGER.warn("Failed to accept incoming connection.", e);
}
} else {
- // TODO fix with try-with-resource for the return value of .channel
LOGGER.error("Not acceptable selection: " + selected.channel());
}
}
TODOs in code are easily forgotten. Better to create an issue in the issue tracker for the project than to embed a TODO.
private void acceptNewConnection() {
LOGGER.warn("Failed to accept incoming connection.", e);
}
} else {
LOGGER.error("Not acceptable selection: " + selected.channel());
}
}
|
codereview_new_java_data_6657
|
protected List<String> normalizeRelatorStringList(List<String> stringList)
*/
protected String normalizeRelatorString(String string)
{
for (String prefix : relatorPrefixesToStrip) {
if (string.startsWith(prefix)) {
string = string.substring(prefix.length());
break;
}
}
return string
- .trim()
.toLowerCase()
.replaceAll("\\p{Punct}+", ""); //POSIX character class Punctuation: One of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
}
Would it make sense to do this last? Otherwise e.g. leading whitespace will cause the stripping to seemingly not work.
protected List<String> normalizeRelatorStringList(List<String> stringList)
*/
protected String normalizeRelatorString(String string)
{
+ string = string.trim();
for (String prefix : relatorPrefixesToStrip) {
if (string.startsWith(prefix)) {
string = string.substring(prefix.length());
break;
}
}
return string
.toLowerCase()
.replaceAll("\\p{Punct}+", ""); //POSIX character class Punctuation: One of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
}
|
codereview_new_java_data_6671
|
protected List<String> getFormatsAsList(Record record) {
result.add("ConferenceProceeding");
}
- // check the 33x fields; these may give us clear information in newer records
- // and if we find something here, it currently indicates non-book content.
List formatsFrom33x = getFormatsFrom33xFields(record);
if (formatsFrom33x.size() > 0) {
couldBeBook = false;
Minor thing but this comment could probably be clearer re why couldBeBook is being set to false, so that we reconsider if/when implementing getFormatsFrom33xFields() more fully e.g.
```
// check the 33x fields; these may give us clear information in newer records;
// in current partial implementation of getFormatsFrom33xFields(), if we find
// something here, it indicates non-book content.
```
protected List<String> getFormatsAsList(Record record) {
result.add("ConferenceProceeding");
}
+ // check the 33x fields; these may give us clear information in newer records;
+ // in current partial implementation of getFormatsFrom33xFields(), if we find
+ // something here, it indicates non-book content.
List formatsFrom33x = getFormatsFrom33xFields(record);
if (formatsFrom33x.size() > 0) {
couldBeBook = false;
|
codereview_new_java_data_6702
|
protected List<LinkedHashMap<String, String>> getRows() {
}
private void defaultVal(LinkedHashMap<String, String> rows) {
String delayDatabase = rows.get(DELAY_DATABASE);
rows.put(DELAY_DATABASE, String.valueOf(delayDatabase));
}
don't understand here
protected List<LinkedHashMap<String, String>> getRows() {
}
private void defaultVal(LinkedHashMap<String, String> rows) {
+ //if the argument is null, then a string equal to "null"
String delayDatabase = rows.get(DELAY_DATABASE);
rows.put(DELAY_DATABASE, String.valueOf(delayDatabase));
}
|
codereview_new_java_data_6703
|
private static void backLog(List<ErrorInfo> list) {
Collection<PhysicalDbInstance> values = allDbInstanceMap.values();
for (PhysicalDbInstance instance : values) {
int minCon = instance.getConfig().getMinCon() / 3;
int backLog = minCon;
keyVariables = new GetAndSyncDbInstanceKeyVariables(instance, false);
explain the magic number
private static void backLog(List<ErrorInfo> list) {
Collection<PhysicalDbInstance> values = allDbInstanceMap.values();
for (PhysicalDbInstance instance : values) {
+ // The back_log value indicates how many requests can be stacked during this short time before MySQL momentarily stops answering new requests,tge suggestions here give at least a third of the size of the mincon
int minCon = instance.getConfig().getMinCon() / 3;
int backLog = minCon;
keyVariables = new GetAndSyncDbInstanceKeyVariables(instance, false);
|
codereview_new_java_data_6704
|
void handleEndPacket(MySQLPacket curPacket, AutoTxOperation txOperation, boolean
if (txOperation == AutoTxOperation.COMMIT) {
session.checkBackupStatus();
session.setBeginCommitTime();
- handler.commit(null);
} else {
service.getLoadDataInfileHandler().clearFile(LoadDataBatch.getInstance().getSuccessFileNames());
- handler.rollback(null);
}
} else {
boolean inTransaction = service.isInTransaction();
add a new interface method for impcilit commit
void handleEndPacket(MySQLPacket curPacket, AutoTxOperation txOperation, boolean
if (txOperation == AutoTxOperation.COMMIT) {
session.checkBackupStatus();
session.setBeginCommitTime();
+ handler.commit();
} else {
service.getLoadDataInfileHandler().clearFile(LoadDataBatch.getInstance().getSuccessFileNames());
+ handler.rollback();
}
} else {
boolean inTransaction = service.isInTransaction();
|
codereview_new_java_data_6705
|
public SqlDumpLog() {
}
public void verify() {
if (!sqlDumpLogSizeBasedRotate.equals("-1")) {
sqlDumpLogSizeBasedRotate = FileSize.parse(sqlDumpLogSizeBasedRotate, 52428800L) + "";
}
Add comments for magic number
public SqlDumpLog() {
}
public void verify() {
+ // '-1' means that it is not configured
if (!sqlDumpLogSizeBasedRotate.equals("-1")) {
sqlDumpLogSizeBasedRotate = FileSize.parse(sqlDumpLogSizeBasedRotate, 52428800L) + "";
}
|
codereview_new_java_data_6706
|
public static void updateSharedContent(SharedContentArray values, boolean save)
if (wasFolderUpdate) {
// Rescan to add/remove Media Library content
- if (CONFIGURATION.getUseCache() && !LibraryScanner.isScanLibraryRunning()) {
LibraryScanner.scanLibrary();
}
}
Shouldn't the current running thread be stopped, and a new library scan started ?
public static void updateSharedContent(SharedContentArray values, boolean save)
if (wasFolderUpdate) {
// Rescan to add/remove Media Library content
+ if (CONFIGURATION.getUseCache()) {
+ LibraryScanner.stopScanLibrary();
LibraryScanner.scanLibrary();
}
}
|
codereview_new_java_data_6707
|
package net.pms.configuration;
import static org.apache.commons.lang3.StringUtils.isBlank;
-
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.locks.ReentrantReadWriteLock;
-
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
-
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.ConversionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
import net.pms.platform.PlatformProgramPaths;
import net.pms.util.ExecutableInfo;
import net.pms.util.ExternalProgramInfo;
import net.pms.util.FFmpegProgramInfo;
import net.pms.util.FileUtil;
import net.pms.util.ProgramExecutableType;
-
/**
* This class adds configurable/custom paths to {@link PlatformProgramPaths}.
*
There are a few files here with these blank lines added in the imports, can that be reverted?
package net.pms.configuration;
import static org.apache.commons.lang3.StringUtils.isBlank;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.ConversionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.pms.platform.PlatformProgramPaths;
import net.pms.util.ExecutableInfo;
import net.pms.util.ExternalProgramInfo;
import net.pms.util.FFmpegProgramInfo;
import net.pms.util.FileUtil;
import net.pms.util.ProgramExecutableType;
/**
* This class adds configurable/custom paths to {@link PlatformProgramPaths}.
*
|
codereview_new_java_data_6708
|
protected String[] getDefaultArgs() {
defaultArgsList.add("format=mpegts");
}
- if (isTranscodeToH264) {
defaultArgsList.add("-mpegopts");
defaultArgsList.add("format=mpeg2:muxrate=500000:vbuf_size=1194:abuf_size=64");
}
```suggestion
if (!isTranscodeToH264) {
```
protected String[] getDefaultArgs() {
defaultArgsList.add("format=mpegts");
}
+ if (!isTranscodeToH264) {
defaultArgsList.add("-mpegopts");
defaultArgsList.add("format=mpeg2:muxrate=500000:vbuf_size=1194:abuf_size=64");
}
|
codereview_new_java_data_6709
|
public static JsonObject getTvSeriesMetadataAsJsonObject(final Connection connec
VideoMetadataLocalized loc = MediaTableVideoMetadataLocalized.getVideoMetadataLocalized(connection, id, true, lang, imdbID, "tv", tmdbId, null, null);
if (loc != null) {
loc.localizeJsonObject(result);
- //temp fix to store tmdbID if it was not before
if (tmdbId == 0 && loc.getTmdbID() != null) {
updateTmdbId(connection, id, loc.getTmdbID());
result.remove("tmdbID");
I'm hesitant about temporary fixes since they often stick around as we forget to remove them, and it can be hard to know when it's ok to remove them. If this is really the best strategy, can we leave a comment in the code that details exactly what the plan is, including when this can be removed?
public static JsonObject getTvSeriesMetadataAsJsonObject(final Connection connec
VideoMetadataLocalized loc = MediaTableVideoMetadataLocalized.getVideoMetadataLocalized(connection, id, true, lang, imdbID, "tv", tmdbId, null, null);
if (loc != null) {
loc.localizeJsonObject(result);
+ //store tmdbID if it was not before
if (tmdbId == 0 && loc.getTmdbID() != null) {
updateTmdbId(connection, id, loc.getTmdbID());
result.remove("tmdbID");
|
codereview_new_java_data_6710
|
public static final void parseFileForDatabase(File file) {
try (RandomAccessFile srcFile = new RandomAccessFile(file, "rw")) {
// no exception happened, so we can continue
} catch (Exception e) {
- /**
- * This will happen a lot (every 500ms) for files that are being
- * copied/moved. Eventually the last one should succeed.
- */
LOGGER.debug("File will not be parsed because it is open in another process");
return;
}
It's not better to put that in the FileUtil as isLocked(File file) or something like that ?
public static final void parseFileForDatabase(File file) {
try (RandomAccessFile srcFile = new RandomAccessFile(file, "rw")) {
// no exception happened, so we can continue
} catch (Exception e) {
LOGGER.debug("File will not be parsed because it is open in another process");
return;
}
|
codereview_new_java_data_6711
|
public void addChild(DLNAResource child, boolean isNew, boolean isAddGlobally) {
* given renderer, and return the relevant engine or null as appropriate.
*
* @param renderer The target renderer
- * @return A engine if transcoding or null if streaming
*/
public Engine resolveEngine(RendererConfiguration renderer) {
// Use device-specific conf, if any
```suggestion
* @return An engine if transcoding or null if streaming
```
public void addChild(DLNAResource child, boolean isNew, boolean isAddGlobally) {
* given renderer, and return the relevant engine or null as appropriate.
*
* @param renderer The target renderer
+ * @return An engine if transcoding or null if streaming
*/
public Engine resolveEngine(RendererConfiguration renderer) {
// Use device-specific conf, if any
|
codereview_new_java_data_6712
|
public static void deleteSubs() {
* } and any ASS tags <code>
* {\*}
* </code> from subtitles file for renderers not capable of showing SubRip
- * tags correctly.* is used as a wildcard in the definition above.
*
* @param file the source subtitles
* @return InputStream with converted subtitles.
```suggestion
* tags correctly. * is used as a wildcard in the definition above.
```
public static void deleteSubs() {
* } and any ASS tags <code>
* {\*}
* </code> from subtitles file for renderers not capable of showing SubRip
+ * tags correctly. * is used as a wildcard in the definition above.
*
* @param file the source subtitles
* @return InputStream with converted subtitles.
|
codereview_new_java_data_6760
|
*/
public interface Saml2AuthenticationRequestResolver {
<T extends AbstractSaml2AuthenticationRequest> T resolve(HttpServletRequest request);
}
Please call this `DEFAULT_AUTHENTICATION_REQUEST_URI`, removing `SAML` and changing `URL` to `URI`. This follows more closely the same name found in `OAuth2AuthorizationRequestRedirectFilter`.
*/
public interface Saml2AuthenticationRequestResolver {
+ String DEFAULT_AUTHENTICATION_REQUEST_URI = "/saml2/authenticate/{registrationId}";
+
<T extends AbstractSaml2AuthenticationRequest> T resolve(HttpServletRequest request);
}
|
codereview_new_java_data_6833
|
private void scanAvailableControllerAddresses() {
for (String address : controllerAddresses) {
scanExecutor.submit(new Runnable() {
- @Override public void run() {
if (brokerOuterAPI.checkAddressCanConnect(address)) {
availableControllerAddresses.putIfAbsent(address, true);
} else {
code style
```
@Override
public void run() {
```
private void scanAvailableControllerAddresses() {
for (String address : controllerAddresses) {
scanExecutor.submit(new Runnable() {
+ @Override
+ public void run() {
if (brokerOuterAPI.checkAddressCanConnect(address)) {
availableControllerAddresses.putIfAbsent(address, true);
} else {
|
codereview_new_java_data_6834
|
public static void sleep(long timeOut, TimeUnit timeUnit) {
}
try {
timeUnit.sleep(timeOut);
- } catch (InterruptedException ignored) {
}
}
The new version is not equivalent to current version. IMO more relevant analysis is necessary to confirm this modification will not cause unexpected effects.
public static void sleep(long timeOut, TimeUnit timeUnit) {
}
try {
timeUnit.sleep(timeOut);
+ } catch (Throwable ignored) {
}
}
|
codereview_new_java_data_6835
|
import org.apache.rocketmq.store.tiered.common.TieredMessageStoreConfig;
import org.apache.rocketmq.store.tiered.common.TieredStoreExecutor;
import org.apache.rocketmq.store.tiered.container.TieredContainerManager;
-import org.apache.rocketmq.store.tiered.container.TieredFileSegment;
import org.apache.rocketmq.store.tiered.container.TieredMessageQueueContainer;
import org.apache.rocketmq.store.tiered.metrics.TieredStoreMetricsConstant;
import org.apache.rocketmq.store.tiered.metrics.TieredStoreMetricsManager;
import org.apache.rocketmq.store.tiered.util.CQItemBufferUtil;
import org.apache.rocketmq.store.tiered.util.MessageBufferUtil;
import org.apache.rocketmq.store.tiered.util.TieredStoreUtil;
Could we rename `rocketmq.store` to `rocketmq.tieredstore`?
import org.apache.rocketmq.store.tiered.common.TieredMessageStoreConfig;
import org.apache.rocketmq.store.tiered.common.TieredStoreExecutor;
import org.apache.rocketmq.store.tiered.container.TieredContainerManager;
import org.apache.rocketmq.store.tiered.container.TieredMessageQueueContainer;
import org.apache.rocketmq.store.tiered.metrics.TieredStoreMetricsConstant;
import org.apache.rocketmq.store.tiered.metrics.TieredStoreMetricsManager;
+import org.apache.rocketmq.store.tiered.provider.TieredFileSegment;
import org.apache.rocketmq.store.tiered.util.CQItemBufferUtil;
import org.apache.rocketmq.store.tiered.util.MessageBufferUtil;
import org.apache.rocketmq.store.tiered.util.TieredStoreUtil;
|
codereview_new_java_data_6836
|
public AppendResult appendIndexFile(DispatchRequest request) {
if (closed) {
return AppendResult.FILE_CLOSED;
}
// AppendResult result = indexFile.append(messageQueue, request.getOffsetId(), request.getCommitLogOffset(), request.getMsgSize(), request.getStoreTimestamp());
// if (result != AppendResult.SUCCESS) {
// return result;
Add more comments here.
public AppendResult appendIndexFile(DispatchRequest request) {
if (closed) {
return AppendResult.FILE_CLOSED;
}
+
+ // building indexes with offsetId is no longer supported because offsetId has changed in tiered storage
// AppendResult result = indexFile.append(messageQueue, request.getOffsetId(), request.getCommitLogOffset(), request.getMsgSize(), request.getStoreTimestamp());
// if (result != AppendResult.SUCCESS) {
// return result;
|
codereview_new_java_data_6837
|
private void pollBatchDispatchRequest() {
batchDispatchRequestQueue.poll();
}
} catch (Exception e) {
- LOGGER.warn(e.getMessage());
}
}
like DefaultMessageStore.LOGGER.warn(this.getServiceName() + " service has exception. ", e);
private void pollBatchDispatchRequest() {
batchDispatchRequestQueue.poll();
}
} catch (Exception e) {
+ DefaultMessageStore.LOGGER.warn(this.getServiceName() + " service has exception. ", e);
}
}
|
codereview_new_java_data_6838
|
public void shutdown() {
super.shutdown();
}
- @Override
- public void run() {
- super.run();
- }
-
@Override
public String getServiceName() {
if (DefaultMessageStore.this.getBrokerConfig().isInBrokerContainer()) {
Remove this method to simply inherit it
public void shutdown() {
super.shutdown();
}
@Override
public String getServiceName() {
if (DefaultMessageStore.this.getBrokerConfig().isInBrokerContainer()) {
|
codereview_new_java_data_6839
|
private RemotingCommand processRequest(final Channel channel, RemotingCommand re
int queueId = requestHeader.getQueueId();
hasMsg = hasMsgFromQueue(false, requestHeader, queueId);
}
- // if it has message, fetch retry again
if (!needRetry && !hasMsg) {
TopicConfig retryTopicConfig =
this.brokerController.getTopicConfigManager().selectTopicConfig(KeyBuilder.buildPopRetryTopic(requestHeader.getTopic(), requestHeader.getConsumerGroup()));
not has message?
private RemotingCommand processRequest(final Channel channel, RemotingCommand re
int queueId = requestHeader.getQueueId();
hasMsg = hasMsgFromQueue(false, requestHeader, queueId);
}
+ // if it doesn't have message, fetch retry again
if (!needRetry && !hasMsg) {
TopicConfig retryTopicConfig =
this.brokerController.getTopicConfigManager().selectTopicConfig(KeyBuilder.buildPopRetryTopic(requestHeader.getTopic(), requestHeader.getConsumerGroup()));
|
codereview_new_java_data_6840
|
public long estimateMessageCount(String topic, int queueId, long from, long to,
return 0;
}
long minOffset = consumeQueue.getMinOffsetInQueue();
- from = Math.max(from, minOffset);
- if (to < minOffset) {
- to = Math.min(minOffset + messageStoreConfig.getMaxConsumeQueueScan(), consumeQueue.getMaxOffsetInQueue());
}
long msgCount = consumeQueue.estimateMessageCount(from, to, filter);
minOffset maybe using from arguments semantics is more readable
public long estimateMessageCount(String topic, int queueId, long from, long to,
return 0;
}
+ // correct the "from" argument to min offset in queue if it is too small
long minOffset = consumeQueue.getMinOffsetInQueue();
+ if (from < minOffset) {
+ long diff = to - from;
+ from = minOffset;
+ to = from + diff;
}
long msgCount = consumeQueue.estimateMessageCount(from, to, filter);
|
codereview_new_java_data_6841
|
public class BrokerConfig extends BrokerIdentity {
private long syncControllerMetadataPeriod = 10 * 1000;
- // It is an important basis for the controller to choose the broker master. Under the same conditions,
- // the broker with higher priority will be selected as master. You can set a higher priority for the broker with better machine conditions.
private int brokerElectionPriority = 0;
public enum MetricsExporterType {
How about making the definition of "higher priority" clearer in the comment or the document? Like is the priority higher while the value of brokerElectionPriority is larger or smaller?
public class BrokerConfig extends BrokerIdentity {
private long syncControllerMetadataPeriod = 10 * 1000;
+ /**
+ * It is an important basis for the controller to choose the broker master.
+ * The higher the value of brokerElectionPriority, the higher the priority of the broker being selected as the master.
+ * You can set a higher priority for the broker with better machine conditions.
+ */
private int brokerElectionPriority = 0;
public enum MetricsExporterType {
|
codereview_new_java_data_6842
|
protected void shutdownScheduledExecutorService(ScheduledExecutorService schedul
scheduledExecutorService.awaitTermination(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignore) {
BrokerController.LOG.warn("shutdown ScheduledExecutorService was Interrupted! ", ignore);
- Thread.currentThread().interrupt();
}
}
https://github.com/apache/rocketmq/actions/runs/3449152754/jobs/5767526841
Error: /home/runner/work/rocketmq/rocketmq/broker/src/main/java/org/apache/rocketmq/broker/BrokerController.java:1427:9: File contains tab characters (this is the first instance). [FileTabCharacter]
Error: /home/runner/work/rocketmq/rocketmq/broker/src/main/java/org/apache/rocketmq/broker/BrokerController.java:1427:17: 'catch' child has incorrect indentation level 16, expected level should be 12. [Indentation]
Here has some problems need to fix in CI.
protected void shutdownScheduledExecutorService(ScheduledExecutorService schedul
scheduledExecutorService.awaitTermination(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignore) {
BrokerController.LOG.warn("shutdown ScheduledExecutorService was Interrupted! ", ignore);
+ Thread.currentThread().interrupt();
}
}
|
codereview_new_java_data_6843
|
public class ProxyMetricsManager implements StartAndShutdown {
public static ObservableLongGauge proxyUp = null;
public static void initLocalMode(BrokerMetricsManager brokerMetricsManager, ProxyConfig proxyConfig) {
ProxyMetricsManager.proxyConfig = proxyConfig;
LABEL_MAP.put(LABEL_NODE_TYPE, NODE_TYPE_PROXY);
LABEL_MAP.put(LABEL_CLUSTER_NAME, proxyConfig.getProxyClusterName());
The brokerMetricsManager could be null, use ProxyConfig#getMetricsExporterType instead.
public class ProxyMetricsManager implements StartAndShutdown {
public static ObservableLongGauge proxyUp = null;
public static void initLocalMode(BrokerMetricsManager brokerMetricsManager, ProxyConfig proxyConfig) {
+ if (proxyConfig.getMetricsExporterType() != BrokerConfig.MetricsExporterType.DISABLE) {
+ return;
+ }
ProxyMetricsManager.proxyConfig = proxyConfig;
LABEL_MAP.put(LABEL_NODE_TYPE, NODE_TYPE_PROXY);
LABEL_MAP.put(LABEL_CLUSTER_NAME, proxyConfig.getProxyClusterName());
|
codereview_new_java_data_6844
|
public class ProxyMetricsManager implements StartAndShutdown {
public static ObservableLongGauge proxyUp = null;
public static void initLocalMode(BrokerMetricsManager brokerMetricsManager, ProxyConfig proxyConfig) {
- if (proxyConfig.getMetricsExporterType() != BrokerConfig.MetricsExporterType.DISABLE) {
return;
}
ProxyMetricsManager.proxyConfig = proxyConfig;
We should skip init process when metrics exporter is disable and not the other way around.
public class ProxyMetricsManager implements StartAndShutdown {
public static ObservableLongGauge proxyUp = null;
public static void initLocalMode(BrokerMetricsManager brokerMetricsManager, ProxyConfig proxyConfig) {
+ if (proxyConfig.getMetricsExporterType() == BrokerConfig.MetricsExporterType.DISABLE) {
return;
}
ProxyMetricsManager.proxyConfig = proxyConfig;
|
codereview_new_java_data_6845
|
private TopicConfig selectTopicConfig(String topic) {
}
public boolean writeOp(Integer queueId,Message message) {
- MessageQueue opQueue;
- if ((opQueue = opQueueMap.get(queueId)) == null) {
opQueue = getOpQueueByHalf(queueId, this.brokerController.getBrokerConfig().getBrokerName());
MessageQueue oldQueue = opQueueMap.putIfAbsent(queueId, opQueue);
if (oldQueue != null) {
opQueue = oldQueue;
}
}
-
PutMessageResult result = putMessageReturnResult(makeOpMessageInner(message, opQueue));
if (result != null && result.getPutMessageStatus() == PutMessageStatus.PUT_OK) {
return true;
Assigning `opQueue` at first may be better than initializing it in `if` condition.
private TopicConfig selectTopicConfig(String topic) {
}
public boolean writeOp(Integer queueId,Message message) {
+ MessageQueue opQueue = opQueueMap.get(queueId);
+ if (opQueue == null) {
opQueue = getOpQueueByHalf(queueId, this.brokerController.getBrokerConfig().getBrokerName());
MessageQueue oldQueue = opQueueMap.putIfAbsent(queueId, opQueue);
if (oldQueue != null) {
opQueue = oldQueue;
}
}
+
PutMessageResult result = putMessageReturnResult(makeOpMessageInner(message, opQueue));
if (result != null && result.getPutMessageStatus() == PutMessageStatus.PUT_OK) {
return true;
|
codereview_new_java_data_6846
|
private RemotingCommand getConsumeStats(ChannelHandlerContext ctx,
offsetWrapper.setBrokerOffset(brokerOffset);
offsetWrapper.setConsumerOffset(consumerOffset);
- offsetWrapper.setPullOffset(pullOffset >= 0 ? pullOffset : 0);
long timeOffset = consumerOffset - 1;
if (timeOffset >= 0) {
It needs to check if pullOffset is bigger than consumerOffset. Otherwise, inflight will be negative when the user resets offset.
private RemotingCommand getConsumeStats(ChannelHandlerContext ctx,
offsetWrapper.setBrokerOffset(brokerOffset);
offsetWrapper.setConsumerOffset(consumerOffset);
+ offsetWrapper.setPullOffset(Math.max(consumerOffset, pullOffset));
long timeOffset = consumerOffset - 1;
if (timeOffset >= 0) {
|
codereview_new_java_data_6847
|
public class NamesrvConfig {
*/
private boolean enableControllerInNamesrv = false;
- private volatile boolean needWaitForService = true;
private int waitSecondsForService = 45;
Hard-coded value is not optimal, because users might adjust the interval of broker registration... Would it be better to set it to alpha * interval_of_broker_registration, where alpha is somewhat 1.5 or 2?
public class NamesrvConfig {
*/
private boolean enableControllerInNamesrv = false;
+ private volatile boolean needWaitForService = false;
private int waitSecondsForService = 45;
|
codereview_new_java_data_6848
|
public TopicRouteService(MQClientAPIFactory mqClientAPIFactory) {
try {
return load(key);
} catch (Exception e) {
return oldValue;
}
}
Add a log here is better
public TopicRouteService(MQClientAPIFactory mqClientAPIFactory) {
try {
return load(key);
} catch (Exception e) {
+ log.warn(String.format("reload topic route from namesrv. topic: %s", key), e);
return oldValue;
}
}
|
codereview_new_java_data_6849
|
public class FileRegionEncoder extends MessageToByteEncoder<FileRegion> {
protected void encode(ChannelHandlerContext ctx, FileRegion msg, final ByteBuf out) throws Exception {
WritableByteChannel writableByteChannel = new WritableByteChannel() {
@Override
- public int write(ByteBuffer src) throws IOException {
out.writeBytes(src);
- return src.limit() - src.position();
}
@Override
To ensure absolute accuracy, just compare the writer index before and after
public class FileRegionEncoder extends MessageToByteEncoder<FileRegion> {
protected void encode(ChannelHandlerContext ctx, FileRegion msg, final ByteBuf out) throws Exception {
WritableByteChannel writableByteChannel = new WritableByteChannel() {
@Override
+ public int write(ByteBuffer src) {
+ int prev = out.writerIndex();
out.writeBytes(src);
+ return out.writerIndex() - prev;
}
@Override
|
codereview_new_java_data_6850
|
protected static void createTopicTo(BrokerController masterBroker, String topicN
try {
TopicConfig topicConfig = new TopicConfig(topicName, rqn, wqn, 6, 0);
defaultMQAdminExt.createAndUpdateTopicConfig(masterBroker.getBrokerAddr(), topicConfig);
- System.out.println("Create topic " + topicName + " to " + masterBroker.getBrokerIdentity().getCanonicalName() + "@" + masterBroker.getBrokerAddr());
-
triggerSlaveSync(masterBroker.getBrokerConfig().getBrokerName(), brokerContainer1);
triggerSlaveSync(masterBroker.getBrokerConfig().getBrokerName(), brokerContainer2);
triggerSlaveSync(masterBroker.getBrokerConfig().getBrokerName(), brokerContainer3);
We should remove the useless System.out.println
protected static void createTopicTo(BrokerController masterBroker, String topicN
try {
TopicConfig topicConfig = new TopicConfig(topicName, rqn, wqn, 6, 0);
defaultMQAdminExt.createAndUpdateTopicConfig(masterBroker.getBrokerAddr(), topicConfig);
triggerSlaveSync(masterBroker.getBrokerConfig().getBrokerName(), brokerContainer1);
triggerSlaveSync(masterBroker.getBrokerConfig().getBrokerName(), brokerContainer2);
triggerSlaveSync(masterBroker.getBrokerConfig().getBrokerName(), brokerContainer3);
|
codereview_new_java_data_6851
|
public BrokerController getBrokerController() {
public boolean escapeMessage(MessageExtBrokerInner messageInner) {
PutMessageResult putMessageResult = this.brokerController.getEscapeBridge().putMessage(messageInner);
- if (putMessageResult != null
- && putMessageResult.getPutMessageStatus() == PutMessageStatus.PUT_OK) {
return true;
} else {
LOGGER.error("Escaping message failed, topic: {}, queueId: {}, msgId: {}",
how about use `org.apache.rocketmq.store.PutMessageResult#isOk` to verify whether success,
It's a little bit cleaner and it's consistent with everything else
public BrokerController getBrokerController() {
public boolean escapeMessage(MessageExtBrokerInner messageInner) {
PutMessageResult putMessageResult = this.brokerController.getEscapeBridge().putMessage(messageInner);
+ if (putMessageResult != null && putMessageResult.isOk()) {
return true;
} else {
LOGGER.error("Escaping message failed, topic: {}, queueId: {}, msgId: {}",
|
codereview_new_java_data_6852
|
private void sendHeartbeatToAllBroker() {
if (addr == null) {
continue;
}
- if (consumerEmpty) {
- if (id != MixAll.MASTER_ID)
- continue;
}
try {
```suggestion
if (consumerEmpty && MixAll.MASTER_ID != id) {
continue;
}
```
private void sendHeartbeatToAllBroker() {
if (addr == null) {
continue;
}
+ if (consumerEmpty && MixAll.MASTER_ID != id) {
+ continue;
}
try {
|
codereview_new_java_data_6853
|
public ControllerResult<GetReplicaInfoResponseHeader> getReplicaInfo(final GetRe
result.setBody(new SyncStateSet(syncStateInfo.getSyncStateSet(), syncStateInfo.getSyncStateSetEpoch()).encode());
return result;
}
- result.setCodeAndRemark(ResponseCode.CONTROLLER_INVALID_REQUEST, "Broker metadata is not existed");
return result;
}
How about CONTROLLER_BROKER_MEATA_NOT_EXIST?
public ControllerResult<GetReplicaInfoResponseHeader> getReplicaInfo(final GetRe
result.setBody(new SyncStateSet(syncStateInfo.getSyncStateSet(), syncStateInfo.getSyncStateSetEpoch()).encode());
return result;
}
+ result.setCodeAndRemark(ResponseCode.CONTROLLER_BROKER_METADATA_NOT_EXIST, "Broker metadata is not existed");
return result;
}
|
codereview_new_java_data_6854
|
public void assign(Collection<MessageQueue> messageQueues) {
@Override
public void setSubExpression4Assgin(final String topic, final String subExpresion) {
- defaultLitePullConsumerImpl.setSubExpression4Assgin(topic, subExpresion);
}
@Override
need to consider name space.
public void assign(Collection<MessageQueue> messageQueues) {
@Override
public void setSubExpression4Assgin(final String topic, final String subExpresion) {
+ defaultLitePullConsumerImpl.setSubExpression4Assgin(withNamespace(topic), subExpresion);
}
@Override
|
codereview_new_java_data_6855
|
public void assign(Collection<MessageQueue> messageQueues) {
}
@Override
- public void setSubExpression4Assign(final String topic, final String subExpresion) {
- defaultLitePullConsumerImpl.setSubExpression4Assign(withNamespace(topic), subExpresion);
}
@Override
Naming is inconsistent with the existing style
public void assign(Collection<MessageQueue> messageQueues) {
}
@Override
+ public void setSubExpressionForAssign(final String topic, final String subExpresion) {
+ defaultLitePullConsumerImpl.setSubExpressionForAssign(withNamespace(topic), subExpresion);
}
@Override
|
codereview_new_java_data_6856
|
protected <T> RunnableFuture<T> newTaskFor(final Runnable runnable, final T valu
}
};
this.heartbeatManager = new DefaultBrokerHeartbeatManager(this.controllerConfig);
this.controller = new DLedgerController(this.controllerConfig, (cluster, brokerAddr) -> this.heartbeatManager.isBrokerActive(cluster, brokerAddr),
this.nettyServerConfig, this.nettyClientConfig, this.brokerHousekeepingService);
'is null or empty' may be more accurate.
protected <T> RunnableFuture<T> newTaskFor(final Runnable runnable, final T valu
}
};
this.heartbeatManager = new DefaultBrokerHeartbeatManager(this.controllerConfig);
+ if (StringUtils.isEmpty(this.controllerConfig.getControllerDLegerPeers())) {
+ throw new IllegalArgumentException("Attribute value controllerDLegerPeers of ControllerConfig is null or empty");
+ }
+ if (StringUtils.isEmpty(this.controllerConfig.getControllerDLegerSelfId())) {
+ throw new IllegalArgumentException("Attribute value controllerDLegerSelfId of ControllerConfig is null or empty");
+ }
this.controller = new DLedgerController(this.controllerConfig, (cluster, brokerAddr) -> this.heartbeatManager.isBrokerActive(cluster, brokerAddr),
this.nettyServerConfig, this.nettyClientConfig, this.brokerHousekeepingService);
|
codereview_new_java_data_6857
|
public class PlainPermissionManagerTest {
PlainAccessConfig plainAccessConfig = new PlainAccessConfig();
Set<Integer> adminCode = new HashSet<>();
- private static final String PATH = PlainPermissionManagerTest.class.getResource("/").getFile();
private static final String DEFAULT_TOPIC = "topic-acl";
Why not load test resources from classpath? It is a much more idiomatic
public class PlainPermissionManagerTest {
PlainAccessConfig plainAccessConfig = new PlainAccessConfig();
Set<Integer> adminCode = new HashSet<>();
+ private static final String PATH = PlainPermissionManagerTest.class.getResource(File.separator).getFile();
private static final String DEFAULT_TOPIC = "topic-acl";
|
codereview_new_java_data_6858
|
public void setGroupPerms(List<String> groupPerms) {
public String toString() {
return "PlainAccessConfig{" +
"accessKey='" + accessKey + '\'' +
- ", secretKey='" + secretKey + '\'' +
", whiteRemoteAddress='" + whiteRemoteAddress + '\'' +
", admin=" + admin +
", defaultTopicPerm='" + defaultTopicPerm + '\'' +
It is awkward and error-prone to manually concatenate strings. Why not use JSON.toJsonString(this)?
Another thing, it would be better to omit the access secret part for safety reasons.
public void setGroupPerms(List<String> groupPerms) {
public String toString() {
return "PlainAccessConfig{" +
"accessKey='" + accessKey + '\'' +
", whiteRemoteAddress='" + whiteRemoteAddress + '\'' +
", admin=" + admin +
", defaultTopicPerm='" + defaultTopicPerm + '\'' +
|
codereview_new_java_data_6859
|
public class DefaultMQProducer extends ClientConfig implements MQProducer {
/**
* on BackpressureForAsyncMode, limit maximum message size of on-going sending async messages
*/
- private Semaphore semaphoreAsyncSize = new Semaphore(512 * 1024 * 1024, true);
/**
* Default constructor.
expose the integer value instead of Semaphore directly.
It is better to initialize the semaphore in the constructor of DefaultMQProducerImpl
public class DefaultMQProducer extends ClientConfig implements MQProducer {
/**
* on BackpressureForAsyncMode, limit maximum message size of on-going sending async messages
+ * default is 100M
*/
+ private Semaphore semaphoreAsyncSize = new Semaphore(100 * 1024 * 1024, true);
/**
* Default constructor.
|
codereview_new_java_data_6860
|
public class DefaultMQProducer extends ClientConfig implements MQProducer {
/**
* on BackpressureForAsyncMode, limit maximum message size of on-going sending async messages
*/
- private Semaphore semaphoreAsyncSize = new Semaphore(512 * 1024 * 1024, true);
/**
* Default constructor.
default to 100M is enough.
public class DefaultMQProducer extends ClientConfig implements MQProducer {
/**
* on BackpressureForAsyncMode, limit maximum message size of on-going sending async messages
+ * default is 100M
*/
+ private Semaphore semaphoreAsyncSize = new Semaphore(100 * 1024 * 1024, true);
/**
* Default constructor.
|
codereview_new_java_data_6861
|
private String generateKey(StringBuilder keyBuilder, MessageExt messageExt) {
public void updateMaxMessageSize(PutMessageThreadLocal putMessageThreadLocal) {
// dynamically adjust maxMessageSize, but not support DLedger mode temporarily
int newMaxMessageSize = this.defaultMessageStore.getMessageStoreConfig().getMaxMessageSize();
- if (putMessageThreadLocal.getEncoder().getMaxMessageBodySize() != newMaxMessageSize) {
putMessageThreadLocal.getEncoder().updateEncoderBufferCapacity(newMaxMessageSize);
}
}
It is better to do some checks to prevent negeative values.
if (newMaxMessageSize < 10) {
return
}
private String generateKey(StringBuilder keyBuilder, MessageExt messageExt) {
public void updateMaxMessageSize(PutMessageThreadLocal putMessageThreadLocal) {
// dynamically adjust maxMessageSize, but not support DLedger mode temporarily
int newMaxMessageSize = this.defaultMessageStore.getMessageStoreConfig().getMaxMessageSize();
+ if (newMaxMessageSize >= 10 &&
+ putMessageThreadLocal.getEncoder().getMaxMessageBodySize() != newMaxMessageSize) {
putMessageThreadLocal.getEncoder().updateEncoderBufferCapacity(newMaxMessageSize);
}
}
|
codereview_new_java_data_6862
|
public RemotingClient getRemotingClient() {
public String fetchNameServerAddr() {
try {
String addrs = this.topAddressing.fetchNSAddr();
- if (addrs != null && !UtilAll.isBlank(addrs)) {
if (!addrs.equals(this.nameSrvAddr)) {
log.info("name server address changed, old=" + this.nameSrvAddr + ", new=" + addrs);
this.updateNameServerAddressList(addrs);
UtillAll.isBlank already has nullable checking
https://github.com/apache/rocketmq/blob/da01deb961807c68b102aeccb1f06d9721ca700e/common/src/main/java/org/apache/rocketmq/common/UtilAll.java#L415
public RemotingClient getRemotingClient() {
public String fetchNameServerAddr() {
try {
String addrs = this.topAddressing.fetchNSAddr();
+ if (!UtilAll.isBlank(addrs)) {
if (!addrs.equals(this.nameSrvAddr)) {
log.info("name server address changed, old=" + this.nameSrvAddr + ", new=" + addrs);
this.updateNameServerAddressList(addrs);
|
codereview_new_java_data_6863
|
public void shutdown() {
public String fetchNameServerAddr() {
try {
String addrs = this.topAddressing.fetchNSAddr();
- if (addrs != null && !UtilAll.isBlank(addrs)) {
if (!addrs.equals(this.nameSrvAddr)) {
log.info("name server address changed, old: {} new: {}", this.nameSrvAddr, addrs);
this.updateNameServerAddressList(addrs);
UtillAll.isBlank already has nullable checking
https://github.com/apache/rocketmq/blob/da01deb961807c68b102aeccb1f06d9721ca700e/common/src/main/java/org/apache/rocketmq/common/UtilAll.java#L415
public void shutdown() {
public String fetchNameServerAddr() {
try {
String addrs = this.topAddressing.fetchNSAddr();
+ if (!UtilAll.isBlank(addrs)) {
if (!addrs.equals(this.nameSrvAddr)) {
log.info("name server address changed, old: {} new: {}", this.nameSrvAddr, addrs);
this.updateNameServerAddressList(addrs);
|
codereview_new_java_data_6864
|
public void shutdown() {
public String fetchNameServerAddr() {
try {
String addrs = this.topAddressing.fetchNSAddr();
- if (addrs != null && !UtilAll.isBlank(addrs)) {
if (!addrs.equals(this.nameSrvAddr)) {
log.info("name server address changed, old: {} new: {}", this.nameSrvAddr, addrs);
this.updateNameServerAddressList(addrs);
It would be better to combine one with the following if.
public void shutdown() {
public String fetchNameServerAddr() {
try {
String addrs = this.topAddressing.fetchNSAddr();
+ if (!UtilAll.isBlank(addrs)) {
if (!addrs.equals(this.nameSrvAddr)) {
log.info("name server address changed, old: {} new: {}", this.nameSrvAddr, addrs);
this.updateNameServerAddressList(addrs);
|
codereview_new_java_data_6865
|
public RemotingCommand getRouteInfoByTopic(ChannelHandlerContext ctx,
byte[] content;
Boolean standardJsonOly = requestHeader.getAcceptStandardJsonOnly();
- if (request.getVersion() >= Version.V4_9_3.ordinal() || (null != standardJsonOly && standardJsonOly)) {
content = topicRouteData.encode(SerializerFeature.BrowserCompatible,
SerializerFeature.QuoteFieldNames, SerializerFeature.SkipTransientField,
SerializerFeature.MapSortField);
The 4.9.3 has been released.
So here should > instead of >= ?
public RemotingCommand getRouteInfoByTopic(ChannelHandlerContext ctx,
byte[] content;
Boolean standardJsonOly = requestHeader.getAcceptStandardJsonOnly();
+ if (request.getVersion() >= Version.V4_9_4.ordinal() || (null != standardJsonOly && standardJsonOly)) {
content = topicRouteData.encode(SerializerFeature.BrowserCompatible,
SerializerFeature.QuoteFieldNames, SerializerFeature.SkipTransientField,
SerializerFeature.MapSortField);
|
codereview_new_java_data_6866
|
public class MixAll {
public static final long FIRST_SLAVE_ID = 1L;
public static final long CURRENT_JVM_PID = getPID();
public final static int UNIT_PRE_SIZE_FOR_MSG = 28;
- public final static int ALL_ACK_IN_SYNC_STATE_SET_NUM = -1;
public static final String RETRY_GROUP_TOPIC_PREFIX = "%RETRY%";
public static final String DLQ_GROUP_TOPIC_PREFIX = "%DLQ%";
Would better just name it in ALL_ACK_IN_SYNC_STATE_SET without NUM since it's only a constant status. Adding NUM seems a bit weird IMO.
public class MixAll {
public static final long FIRST_SLAVE_ID = 1L;
public static final long CURRENT_JVM_PID = getPID();
public final static int UNIT_PRE_SIZE_FOR_MSG = 28;
+ public final static int ALL_ACK_IN_SYNC_STATE_SET = -1;
public static final String RETRY_GROUP_TOPIC_PREFIX = "%RETRY%";
public static final String DLQ_GROUP_TOPIC_PREFIX = "%DLQ%";
|
codereview_new_java_data_6867
|
public void correctMinOffset(long phyMinOffset) {
}
@Override
- public void dispatch(DispatchRequest request) {
final int maxRetries = 30;
boolean canWrite = this.messageStore.getRunningFlags().isCQWriteable();
if (request.getMsgBaseOffset() < 0 || request.getBatchSize() < 0) {
No good too.
public void correctMinOffset(long phyMinOffset) {
}
@Override
+ public void putMessagePositionInfoWrapper(DispatchRequest request) {
final int maxRetries = 30;
boolean canWrite = this.messageStore.getRunningFlags().isCQWriteable();
if (request.getMsgBaseOffset() < 0 || request.getBatchSize() < 0) {
|
codereview_new_java_data_6868
|
public void accept(Backend.Holder h) {
llvmType = options.llvmKompileType;
break;
default:
- throw KEMException.criticalError("Non-valid argument for --llvm-kompile-type: " + options.llvmKompileType + ". Expected [main|search|library|static|python]");
}
String llvmOutput = "interpreter";
```suggestion
throw KEMException.criticalError("Non-valid argument for --llvm-kompile-type: " + options.llvmKompileType + ". Expected [main|search|static|python]");
```
public void accept(Backend.Holder h) {
llvmType = options.llvmKompileType;
break;
default:
+ throw KEMException.criticalError("Non-valid argument for --llvm-kompile-type: " + options.llvmKompileType + ". Expected [main|search|static|python]");
}
String llvmOutput = "interpreter";
|
codereview_new_java_data_6870
|
public K prettyRead(Module mod, Sort sort, CompiledDefinition def, Source source
case PROGRAM:
return def.parseSingleTerm(mod, sort, kem, files, stringToParse, source);
case RULE:
- throw KEMException.criticalError("Should have been handled directly by the kast front end: " + inputMode);
default:
throw KEMException.criticalError("Unsupported input mode: " + inputMode);
}
this should probably be an internal error.
public K prettyRead(Module mod, Sort sort, CompiledDefinition def, Source source
case PROGRAM:
return def.parseSingleTerm(mod, sort, kem, files, stringToParse, source);
case RULE:
+ throw KEMException.internalError("Should have been handled directly by the kast front end: " + inputMode);
default:
throw KEMException.criticalError("Unsupported input mode: " + inputMode);
}
|
codereview_new_java_data_6877
|
public void proverChecksX(Module specModule, Module mainDefModule) {
ModuleTransformer mt = ModuleTransformer.fromSentenceTransformer((m, s) -> {
if (s instanceof Rule && (s.att().contains(Att.SIMPLIFICATION()))) {
KLabel kl = m.matchKLabel((Rule) s);
- scala.collection.Set<Production> prods = m.productionsFor().get(kl).getOrElse(() -> {
- throw KEMException.criticalError("Could not find productions for label " + kl.name(), s);
- });
- Att atts = prods.iterator().next().att();
if (!(atts.contains(Att.FUNCTION()) || atts.contains(Att.FUNCTIONAL()) || atts.contains("mlOp")))
errors.add(KEMException.compilerError("Simplification rules expect function/functional/mlOp symbols at the top of the left hand side term.", s));
}
This is probably a somewhat common code pattern? Could we write a function called `getUniqueProductionFor(kl)`, which encapsulates all this logic? Basically it calls `productionsFor().get(kl).getOrElse(() -> { error })` and then asserts that the length of the returned productions in exactly 1, and then returns that unique production? I'm guessing that there are many places in the code using this pattern.
public void proverChecksX(Module specModule, Module mainDefModule) {
ModuleTransformer mt = ModuleTransformer.fromSentenceTransformer((m, s) -> {
if (s instanceof Rule && (s.att().contains(Att.SIMPLIFICATION()))) {
KLabel kl = m.matchKLabel((Rule) s);
+ Att atts = m.attributesFor().get(kl).getOrElse(Att::empty);
if (!(atts.contains(Att.FUNCTION()) || atts.contains(Att.FUNCTIONAL()) || atts.contains("mlOp")))
errors.add(KEMException.compilerError("Simplification rules expect function/functional/mlOp symbols at the top of the left hand side term.", s));
}
|
codereview_new_java_data_6887
|
public CompiledDefinition run(File definitionFile, String mainModuleName, String
m.checkSorts();
if (kompileOptions.postProcess != null) {
kompiledDefinition = postProcessJSON(kompiledDefinition, kompileOptions.postProcess);
- files.saveToKompiled("jsoned.txt", kompiledDefinition.toString());
}
files.saveToKompiled("allRules.txt", ruleSourceMap(kompiledDefinition));
I would call this `post-processed.txt` instead.
public CompiledDefinition run(File definitionFile, String mainModuleName, String
m.checkSorts();
if (kompileOptions.postProcess != null) {
kompiledDefinition = postProcessJSON(kompiledDefinition, kompileOptions.postProcess);
+ files.saveToKompiled("post-processed.txt", kompiledDefinition.toString());
}
files.saveToKompiled("allRules.txt", ruleSourceMap(kompiledDefinition));
|
codereview_new_java_data_7088
|
public XMPPPacketReader(DocumentFactory factory) {
/**
* Retrieves a collection of namespaces declared in the current element that the parser is on, that are not defined
- * in {@link #IGNORED_NAMESPACE_ON_STANZA}
*
* @param xpp the parser
* @return A collection of namespaces
- * @throws XmlPullParserException
*/
@Nonnull
- public static Set<Namespace> getNamespacesOnCurrentElement(XmlPullParser xpp) throws XmlPullParserException
{
final Set<Namespace> results = new HashSet<>();
final int nsStart = xpp.getNamespaceCount(xpp.getDepth()-1);
I reckon this method would be a great place for a unit test. I can see what it should be doing, but a unit test would at least validate it does what I think it does.
public XMPPPacketReader(DocumentFactory factory) {
/**
* Retrieves a collection of namespaces declared in the current element that the parser is on, that are not defined
+ * in {@link #IGNORED_NAMESPACE_ON_STANZA}, and that are not the default namespace (the namespaces returned all have
+ * a defined prefix).
*
* @param xpp the parser
* @return A collection of namespaces
+ * @throws XmlPullParserException On any problem thrown by the XML parser.
*/
@Nonnull
+ public static Set<Namespace> getPrefixedNamespacesOnCurrentElement(XmlPullParser xpp) throws XmlPullParserException
{
final Set<Namespace> results = new HashSet<>();
final int nsStart = xpp.getNamespaceCount(xpp.getDepth()-1);
|
codereview_new_java_data_7089
|
public void onConnect(Session session)
public void onClose(int statusCode, String reason)
{
// Handle asynchronously, to prevent deadlocks. See OF-2473.
- HttpBindManager.getInstance().getSessionManager().execute(this::closeSession);
}
@OnWebSocketMessage
You'll need to wrap this in a try/catch to ensure any errors during processing are properly logged and not lost in the ether. Either in this call, or in closeSession itself.
public void onConnect(Session session)
public void onClose(int statusCode, String reason)
{
// Handle asynchronously, to prevent deadlocks. See OF-2473.
+ HttpBindManager.getInstance().getSessionManager().execute(() -> {
+ try {
+ closeSession();
+ } catch (Throwable t) {
+ Log.warn("An exception occurred while trying to process @OnWebSocketClose for session {}.", wsSession, t);
+ }
+ });
}
@OnWebSocketMessage
|
codereview_new_java_data_7090
|
public String getPageFunctions() {
sb.append("\tfunction toggleColumnOrder(sortColumnNumber) {\n")
// Orders based on a particular column, reversing the order if that column was already ordered on.
.append(String.format("\t\tvar formObject = document.getElementById('%s');\n", PAGINATION_FORM_ID))
- .append(String.format("\t\tvar previousSortColumnNumber = formObject.%s.value || '0';\n", "sortColumnNumber"))
- .append(String.format("\t\tvar previousSortOrder = formObject.%s.value || '1';\n", "sortOrder"))
- .append(String.format("\t\tformObject.%s.value = sortColumnNumber;\n", "sortColumnNumber"))
- .append(String.format("\t\tformObject.%s.value = parseInt(previousSortColumnNumber) === sortColumnNumber ? 1-previousSortOrder : 1;\n", "sortOrder"))
.append("\t\tsubmitForm();\n")
.append("\t\treturn false;\n")
.append("\t}\n")
These next few lines seem to use `String.format` unnecessarily - passing in a string constant that may as well just have been in the format string? should `"sortColumnNumber"` have been a `private static final String` definition and used elsewhere? Possibly `REQUEST_PARAMETER_KEY_SORT_COLUMN_NUMBER `(and similarly for the next few lines)
public String getPageFunctions() {
sb.append("\tfunction toggleColumnOrder(sortColumnNumber) {\n")
// Orders based on a particular column, reversing the order if that column was already ordered on.
.append(String.format("\t\tvar formObject = document.getElementById('%s');\n", PAGINATION_FORM_ID))
+ .append(String.format("\t\tvar previousSortColumnNumber = formObject.%s.value || '0';\n", REQUEST_PARAMETER_KEY_SORT_COLUMN_NUMBER))
+ .append(String.format("\t\tvar previousSortOrder = formObject.%s.value || '1';\n", REQUEST_PARAMETER_KEY_SORT_ORDER))
+ .append(String.format("\t\tformObject.%s.value = sortColumnNumber;\n", REQUEST_PARAMETER_KEY_SORT_COLUMN_NUMBER))
+ .append(String.format("\t\tformObject.%s.value = parseInt(previousSortColumnNumber) === sortColumnNumber ? 1-previousSortOrder : 1;\n", REQUEST_PARAMETER_KEY_SORT_ORDER))
.append("\t\tsubmitForm();\n")
.append("\t\treturn false;\n")
.append("\t}\n")
|
codereview_new_java_data_7094
|
private static List<Region> internalParse(
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setXIncludeAware(false);
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
document = documentBuilder.parse(input);
why not use `getDocumentBuilderFactory`?
private static List<Region> internalParse(
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setXIncludeAware(false);
+ factory.setExpandEntityReferences(false);
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
document = documentBuilder.parse(input);
|
codereview_new_java_data_7095
|
public class PinpointNotificationActivityTests {
@Before
public void setup() {
- PinpointNotificationActivity.setNotificationClient((NotificationClient) null);
notificationClient = Mockito.mock(NotificationClient.class);
activityController = Robolectric.buildActivity(PinpointNotificationActivity.class);
PinpointNotificationActivity.setNotificationClient(notificationClient);
why are we setting this to `null` here before immediately overriding it with a mock?
public class PinpointNotificationActivityTests {
@Before
public void setup() {
notificationClient = Mockito.mock(NotificationClient.class);
activityController = Robolectric.buildActivity(PinpointNotificationActivity.class);
PinpointNotificationActivity.setNotificationClient(notificationClient);
|
codereview_new_java_data_7096
|
private void openURL(final String url, final boolean noSchemeValidation) {
try {
pinpointContext.getApplicationContext().startActivity(intent);
} catch (ActivityNotFoundException e) {
- log.error("Couldn't find an app to open ACTION_VIEW Intent.");
}
}
Can we include `e` or `e.getMessage` for additional context on error?
private void openURL(final String url, final boolean noSchemeValidation) {
try {
pinpointContext.getApplicationContext().startActivity(intent);
} catch (ActivityNotFoundException e) {
+ log.error("Couldn't find an app to open ACTION_VIEW Intent.", e);
}
}
|
codereview_new_java_data_7098
|
cdpSession, getDomains().target().detachFromTarget(Optional.of(id), Optional.emp
// Exceptions should not prevent closing the connection and the web driver
log.warning("Exception while detaching from target: " + e.getMessage());
}
- cdpSession = null;
}
}
This is the only bit I do not understand. Why is this needed?
cdpSession, getDomains().target().detachFromTarget(Optional.of(id), Optional.emp
// Exceptions should not prevent closing the connection and the web driver
log.warning("Exception while detaching from target: " + e.getMessage());
}
}
}
|
codereview_new_java_data_7103
|
public Either<WebDriverException, ActiveSession> apply(CreateSessionRequest sess
}
try {
- Capabilities mergedCapabilities =
- sessionRequest.getDesiredCapabilities().merge(this.getStereotype());
- CreateSessionRequest mergedSessionRequest = new CreateSessionRequest(
- sessionRequest.getDownstreamDialects(),
- mergedCapabilities,
- sessionRequest.getMetadata());
-
- Either<WebDriverException, ActiveSession> possibleSession =
- factory.apply(mergedSessionRequest);
if (possibleSession.isRight()) {
ActiveSession session = possibleSession.right();
Would this overwrite the browser options passed by the user? Like, if the custom stereotype has a `goog:chromeOptions`, would it overwrite what the user has passed?
public Either<WebDriverException, ActiveSession> apply(CreateSessionRequest sess
}
try {
+ Either<WebDriverException, ActiveSession> possibleSession = factory.apply(sessionRequest);
if (possibleSession.isRight()) {
ActiveSession session = possibleSession.right();
|
codereview_new_java_data_7109
|
public static BrowsingContextInfo fromJson(JsonInput input) {
children = input.read(LIST_OF_BROWSING_CONTEXT_INFO);
break;
- case "parent]":
parentBrowsingContext = input.read(String.class);
break;
Is the extraneous `]` intentional here?
public static BrowsingContextInfo fromJson(JsonInput input) {
children = input.read(LIST_OF_BROWSING_CONTEXT_INFO);
break;
+ case "parent":
parentBrowsingContext = input.read(String.class);
break;
|
codereview_new_java_data_7110
|
protected Node(Tracer tracer, NodeId id, URI uri, Secret registrationSecret) {
post("/session/{sessionId}/se/file")
.to(params -> new UploadFile(this, sessionIdFrom(params)))
.with(spanDecorator("node.upload_file")),
- get("/session/{sessionId}/file")
- .to(params -> new DownloadFile(this, sessionIdFrom(params)))
- .with(spanDecorator("node.download_file")),
get("/session/{sessionId}/se/file")
.to(params -> new DownloadFile(this, sessionIdFrom(params)))
.with(spanDecorator("node.download_file")),
We only would like to have a prefixed `se` endpoint because this particular functionality is not part of the W3C standard. The upload one is kept in both ways for backwards compatibility reasons.
protected Node(Tracer tracer, NodeId id, URI uri, Secret registrationSecret) {
post("/session/{sessionId}/se/file")
.to(params -> new UploadFile(this, sessionIdFrom(params)))
.with(spanDecorator("node.upload_file")),
get("/session/{sessionId}/se/file")
.to(params -> new DownloadFile(this, sessionIdFrom(params)))
.with(spanDecorator("node.download_file")),
|
codereview_new_java_data_7111
|
public class NodeFlags implements HasRoles {
private String nodeImplementation = DEFAULT_NODE_IMPLEMENTATION;
@Parameter(
- names = {"--downloads-dir"},
description = "The default location wherein all browser triggered file downloads would be "
+ "available to be retrieved from. This is usually the directory that you configure in "
+ "your browser as the default location for storing downloaded files.")
- @ConfigValue(section = NODE_SECTION, name = "downloads-dir", example = "")
- private String downloadsDir = "";
@Override
public Set<Role> getRoles() {
```suggestion
@ConfigValue(section = NODE_SECTION, name = "downloads-path", example = "")
```
public class NodeFlags implements HasRoles {
private String nodeImplementation = DEFAULT_NODE_IMPLEMENTATION;
@Parameter(
+ names = {"--downloads-path"},
description = "The default location wherein all browser triggered file downloads would be "
+ "available to be retrieved from. This is usually the directory that you configure in "
+ "your browser as the default location for storing downloaded files.")
+ @ConfigValue(section = NODE_SECTION, name = "downloads-path", example = "")
+ private String downloadsPath = "";
@Override
public Set<Role> getRoles() {
|
codereview_new_java_data_7112
|
public class NodeFlags implements HasRoles {
private String nodeImplementation = DEFAULT_NODE_IMPLEMENTATION;
@Parameter(
- names = {"--downloads-dir"},
description = "The default location wherein all browser triggered file downloads would be "
+ "available to be retrieved from. This is usually the directory that you configure in "
+ "your browser as the default location for storing downloaded files.")
- @ConfigValue(section = NODE_SECTION, name = "downloads-dir", example = "")
- private String downloadsDir = "";
@Override
public Set<Role> getRoles() {
```suggestion
private String downloadsPath = "";
```
public class NodeFlags implements HasRoles {
private String nodeImplementation = DEFAULT_NODE_IMPLEMENTATION;
@Parameter(
+ names = {"--downloads-path"},
description = "The default location wherein all browser triggered file downloads would be "
+ "available to be retrieved from. This is usually the directory that you configure in "
+ "your browser as the default location for storing downloaded files.")
+ @ConfigValue(section = NODE_SECTION, name = "downloads-path", example = "")
+ private String downloadsPath = "";
@Override
public Set<Role> getRoles() {
|
codereview_new_java_data_7113
|
public Optional<URI> getPublicGridUri() {
}
public Optional<String> getDownloadsDirectory() {
- return config.get(NODE_SECTION, "downloads-dir");
}
public Node getNode() {
```suggestion
return config.get(NODE_SECTION, "downloads-path");
```
public Optional<URI> getPublicGridUri() {
}
public Optional<String> getDownloadsDirectory() {
+ return config.get(NODE_SECTION, "downloads-path");
}
public Node getNode() {
|
codereview_new_java_data_7114
|
public HttpResponse uploadFile(HttpRequest req, SessionId id) {
@Override
public HttpResponse downloadFile(HttpRequest req, SessionId id) {
- throw new UnsupportedOperationException("uploadFile");
}
@Override
```suggestion
throw new UnsupportedOperationException("downloadFile");
```
public HttpResponse uploadFile(HttpRequest req, SessionId id) {
@Override
public HttpResponse downloadFile(HttpRequest req, SessionId id) {
+ throw new UnsupportedOperationException("downloadFile");
}
@Override
|
codereview_new_java_data_7115
|
public Optional<URI> getPublicGridUri() {
}
}
- public Optional<String> getDownloadsDirectory() {
return config.get(NODE_SECTION, "downloads-path");
}
This code is not invoked anywhere. I believe it should be called from the `create` method in `LocalNodeFactory`.
public Optional<URI> getPublicGridUri() {
}
}
+ public Optional<String> getDownloadsPath() {
return config.get(NODE_SECTION, "downloads-path");
}
|
codereview_new_java_data_7292
|
public ServiceUnitStateData(ServiceUnitState state, String broker, boolean force
public static ServiceUnitState state(ServiceUnitStateData data) {
return data == null ? ServiceUnitState.Init : data.state();
}
-
- public static long versionId(ServiceUnitStateData data) {
- return data == null ? 0 : data.versionId();
- }
}
Can we use the `VERSION_ID_INIT` as the default value?
public ServiceUnitStateData(ServiceUnitState state, String broker, boolean force
public static ServiceUnitState state(ServiceUnitStateData data) {
return data == null ? ServiceUnitState.Init : data.state();
}
}
|
codereview_new_java_data_7293
|
public void testClearDelayedMessagesWhenClearBacklog() throws PulsarClientExcept
Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
.topic(topic).create();
- final int messages = 10;
for (int i = 0; i < messages; i++) {
producer.newMessage().deliverAfter(1, TimeUnit.HOURS).value("Delayed Message - " + i).send();
}
Is it related to this PR?
public void testClearDelayedMessagesWhenClearBacklog() throws PulsarClientExcept
Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
.topic(topic).create();
+ final int messages = 60;
for (int i = 0; i < messages; i++) {
producer.newMessage().deliverAfter(1, TimeUnit.HOURS).value("Delayed Message - " + i).send();
}
|
codereview_new_java_data_7294
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E
// At default info level, suppress all subsequent exceptions that are thrown when the connection has already
// failed
if (log.isDebugEnabled()) {
- log.debug("[{}] Got exception: {}", remoteAddress, cause.getMessage(), cause);
}
}
ctx.close();
Is it worth using `ClientCnx.isKnownException(cause) ? cause : ExceptionUtils.getStackTrace(cause)` link we do on line 391?
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E
// At default info level, suppress all subsequent exceptions that are thrown when the connection has already
// failed
if (log.isDebugEnabled()) {
+ log.debug("[{}] Got exception {}", remoteAddress,
+ ClientCnx.isKnownException(cause) ? cause : ExceptionUtils.getStackTrace(cause));
}
}
ctx.close();
|
codereview_new_java_data_7295
|
private void closeConsumerTasks() {
stats.getStatTimeout().ifPresent(Timeout::cancel);
// Execute "clearIncomingMessages" regardless of whether "internalPinnedExecutor" has shutdown or not.
// Call "clearIncomingMessages" in "internalPinnedExecutor" is used to clear messages in flight.
- clearIncomingMessages();
- internalPinnedExecutor.execute(this::clearIncomingMessages);
}
void activeConsumerChanged(boolean isActive) {
If `internalPinnedExecutor` is shutdown, it will throw an exception. Please catch it. Or if you can confirm that this method always runs before the `internalPinnedExecutor` shutdown.
private void closeConsumerTasks() {
stats.getStatTimeout().ifPresent(Timeout::cancel);
// Execute "clearIncomingMessages" regardless of whether "internalPinnedExecutor" has shutdown or not.
// Call "clearIncomingMessages" in "internalPinnedExecutor" is used to clear messages in flight.
+ if (!internalPinnedExecutor.isShutdown()) {
+ internalPinnedExecutor.execute(this::clearIncomingMessages);
+ } else {
+ clearIncomingMessages();
+ }
}
void activeConsumerChanged(boolean isActive) {
|
codereview_new_java_data_7296
|
private void closeConsumerTasks() {
stats.getStatTimeout().ifPresent(Timeout::cancel);
// Execute "clearIncomingMessages" regardless of whether "internalPinnedExecutor" has shutdown or not.
// Call "clearIncomingMessages" in "internalPinnedExecutor" is used to clear messages in flight.
if (!internalPinnedExecutor.isShutdown()) {
internalPinnedExecutor.execute(this::clearIncomingMessages);
- } else {
- clearIncomingMessages();
}
}
If the `executor` has shutdown, it is still running some task in background.
private void closeConsumerTasks() {
stats.getStatTimeout().ifPresent(Timeout::cancel);
// Execute "clearIncomingMessages" regardless of whether "internalPinnedExecutor" has shutdown or not.
// Call "clearIncomingMessages" in "internalPinnedExecutor" is used to clear messages in flight.
+ clearIncomingMessages();
if (!internalPinnedExecutor.isShutdown()) {
internalPinnedExecutor.execute(this::clearIncomingMessages);
}
}
|
codereview_new_java_data_7297
|
public String toString() {
* by {@param itemAfterTerminatedHandler}.
*/
public void terminate(@Nullable Consumer<T> itemAfterTerminatedHandler) {
- terminated = true;
- if (itemAfterTerminatedHandler != null) {
- this.itemAfterTerminatedHandler = itemAfterTerminatedHandler;
- }
// After wait for the in-flight item enqueue, it means the operation of terminate is finished.
long stamp = tailLock.writeLock();
- tailLock.unlockWrite(stamp);
}
public boolean isTerminated() {
```suggestion
// After wait for the in-flight item enqueue, it means the operation of terminate is finished.
long stamp = tailLock.writeLock();
terminated = true;
if (itemAfterTerminatedHandler != null) {
this.itemAfterTerminatedHandler = itemAfterTerminatedHandler;
}
tailLock.unlockWrite(stamp);
```
Is it better to understand?
public String toString() {
* by {@param itemAfterTerminatedHandler}.
*/
public void terminate(@Nullable Consumer<T> itemAfterTerminatedHandler) {
// After wait for the in-flight item enqueue, it means the operation of terminate is finished.
long stamp = tailLock.writeLock();
+ try {
+ terminated = true;
+ if (itemAfterTerminatedHandler != null) {
+ this.itemAfterTerminatedHandler = itemAfterTerminatedHandler;
+ }
+ } finally {
+ tailLock.unlockWrite(stamp);
+ }
}
public boolean isTerminated() {
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.