id
stringlengths 29
30
| content
stringlengths 152
2.6k
|
|---|---|
codereview_new_java_data_12506
|
private ApiError validateAlterConfig(ConfigResource configResource,
for (ApiMessageAndVersion recordImplicitlyDeleted : recordsImplicitlyDeleted) {
ConfigRecord configRecord = (ConfigRecord) recordImplicitlyDeleted.message();
allConfigs.remove(configRecord.name());
- // do not include these implicit deletions in the alter config policy check
}
try {
validator.validate(configResource, allConfigs);
Can you add a reference to this JIRA, so that people can understand this (somewhat weird) behavior?
We should note that this is for compatibility with ZK mode
private ApiError validateAlterConfig(ConfigResource configResource,
for (ApiMessageAndVersion recordImplicitlyDeleted : recordsImplicitlyDeleted) {
ConfigRecord configRecord = (ConfigRecord) recordImplicitlyDeleted.message();
allConfigs.remove(configRecord.name());
+ // As per KAFKA-14039, do not include implicit deletions caused by using the legacy AlterConfigs API
+ // in the list passed to the policy in order to maintain backwards compatibility
}
try {
validator.validate(configResource, allConfigs);
|
codereview_new_java_data_12507
|
private ApiError validateAlterConfig(ConfigResource configResource,
for (ApiMessageAndVersion recordImplicitlyDeleted : recordsImplicitlyDeleted) {
ConfigRecord configRecord = (ConfigRecord) recordImplicitlyDeleted.message();
allConfigs.remove(configRecord.name());
- // As per KAFKA-14039, do not include implicit deletions caused by using the legacy AlterConfigs API
// in the list passed to the policy in order to maintain backwards compatibility
}
try {
Should this documentation come before the lines 269-270?
private ApiError validateAlterConfig(ConfigResource configResource,
for (ApiMessageAndVersion recordImplicitlyDeleted : recordsImplicitlyDeleted) {
ConfigRecord configRecord = (ConfigRecord) recordImplicitlyDeleted.message();
allConfigs.remove(configRecord.name());
+ // As per KAFKA-14195, do not include implicit deletions caused by using the legacy AlterConfigs API
// in the list passed to the policy in order to maintain backwards compatibility
}
try {
|
codereview_new_java_data_12508
|
static void createCompactedTopic(String topicName, short partitions, short repli
}
if (cause instanceof UnsupportedVersionException) {
log.debug("Unable to create topic '{}' since the brokers do not support the CreateTopics API." +
- " Falling back to assume topic exist or will be auto-created by the broker.",
topicName);
}
if (cause instanceof ClusterAuthorizationException) {
`upon the brokers` sounds strange. Maybe we can just drop that part of the sentence?
static void createCompactedTopic(String topicName, short partitions, short repli
}
if (cause instanceof UnsupportedVersionException) {
log.debug("Unable to create topic '{}' since the brokers do not support the CreateTopics API." +
+ " Falling back to assume topic exists or will be auto-created by the broker.",
topicName);
}
if (cause instanceof ClusterAuthorizationException) {
|
codereview_new_java_data_12509
|
import java.util.Set;
/**
- * ForwardingAdmin is the default value of `forwarding.admin.class` in MM2.
- * MM2 users who wish to use customized behaviour Admin; they can extend the ForwardingAdmin and override some behaviours
- * without need to provide a whole implementation of Admin.
- * The class must have a contractor that accept configuration (Map<String, Object> config) to configure
- * {@link KafkaAdminClient} and any other needed resource management clients.
*/
public class ForwardingAdmin implements Admin {
private final Admin delegate;
```suggestion
* {@code ForwardingAdmin} is the default value of {@code forwarding.admin.class} in MM2.
* Users who wish to customize the MM2 behaviour for the creation of topics and access control lists can extend this
* class without needing to provide a whole implementation of {@code Admin}.
* The class must have a constructor with signature {@code (Map<String, Object> config)} for configuring
* a decorated {@link KafkaAdminClient} and any other clients needed for external resource management.
```
import java.util.Set;
/**
+ * {@code ForwardingAdmin} is the default value of {@code forwarding.admin.class} in MM2.
+ * Users who wish to customize the MM2 behaviour for the creation of topics and access control lists can extend this
+ * class without needing to provide a whole implementation of {@code Admin}.
+ * The class must have a constructor with signature {@code (Map<String, Object> config)} for configuring
+ * a decorated {@link KafkaAdminClient} and any other clients needed for external resource management.
*/
public class ForwardingAdmin implements Admin {
private final Admin delegate;
|
codereview_new_java_data_12510
|
import java.util.Set;
/**
- * {@code ForwardingAdmin} is the default value of {@code forwarding.admin.class} in MM2.
- * Users who wish to customize the MM2 behaviour for the creation of topics and access control lists can extend this
* class without needing to provide a whole implementation of {@code Admin}.
* The class must have a constructor with signature {@code (Map<String, Object> config)} for configuring
* a decorated {@link KafkaAdminClient} and any other clients needed for external resource management.
Should we say `MirrorMaker` instead of just `MM2`?
import java.util.Set;
/**
+ * {@code ForwardingAdmin} is the default value of {@code forwarding.admin.class} in MirrorMaker.
+ * Users who wish to customize the MirrorMaker behaviour for the creation of topics and access control lists can extend this
* class without needing to provide a whole implementation of {@code Admin}.
* The class must have a constructor with signature {@code (Map<String, Object> config)} for configuring
* a decorated {@link KafkaAdminClient} and any other clients needed for external resource management.
|
codereview_new_java_data_12511
|
public class MirrorClientConfig extends AbstractConfig {
public static final String FORWARDING_ADMIN_CLASS = "forwarding.admin.class";
public static final String FORWARDING_ADMIN_CLASS_DOC = "Class which extends ForwardingAdmin to define custom cluster resource management (topics, configs, etc). " +
- "The class must have a contractor that accept configuration (Map<String, Object> config) to configure KafkaAdminClient and any other needed clients.";
public static final Class<?> FORWARDING_ADMIN_CLASS_DEFAULT = ForwardingAdmin.class;
public static final String ADMIN_CLIENT_PREFIX = "admin.";
public static final String CONSUMER_CLIENT_PREFIX = "consumer.";
`contractor` -> `constructor`
public class MirrorClientConfig extends AbstractConfig {
public static final String FORWARDING_ADMIN_CLASS = "forwarding.admin.class";
public static final String FORWARDING_ADMIN_CLASS_DOC = "Class which extends ForwardingAdmin to define custom cluster resource management (topics, configs, etc). " +
+ "The class must have a constructor that accept configuration (Map<String, Object> config) to configure KafkaAdminClient and any other needed clients.";
public static final Class<?> FORWARDING_ADMIN_CLASS_DEFAULT = ForwardingAdmin.class;
public static final String ADMIN_CLIENT_PREFIX = "admin.";
public static final String CONSUMER_CLIENT_PREFIX = "consumer.";
|
codereview_new_java_data_12512
|
public void testPutConnectorConfig() throws Exception {
FutureCallback<Herder.Created<ConnectorInfo>> reconfigureCallback = new FutureCallback<>();
herder.putConnectorConfig(CONNECTOR_NAME, newConnConfig, true, reconfigureCallback);
Herder.Created<ConnectorInfo> newConnectorInfo = reconfigureCallback.get(1000L, TimeUnit.SECONDS);
- ConnectorInfo newConnInfo = new ConnectorInfo(CONNECTOR_NAME, newConnConfig, singletonList(new ConnectorTaskId(CONNECTOR_NAME, 0)),
ConnectorType.SOURCE);
assertEquals(newConnInfo, newConnectorInfo.result());
My IDE has been nagging me about this one too, for years. I've left it as-is (maybe not here but in other places) since it's not performance-critical and it's easier to modify in case we need to add other elements, or construct an empty list. I think we should revert this change.
public void testPutConnectorConfig() throws Exception {
FutureCallback<Herder.Created<ConnectorInfo>> reconfigureCallback = new FutureCallback<>();
herder.putConnectorConfig(CONNECTOR_NAME, newConnConfig, true, reconfigureCallback);
Herder.Created<ConnectorInfo> newConnectorInfo = reconfigureCallback.get(1000L, TimeUnit.SECONDS);
+ ConnectorInfo newConnInfo = new ConnectorInfo(CONNECTOR_NAME, newConnConfig, Arrays.asList(new ConnectorTaskId(CONNECTOR_NAME, 0)),
ConnectorType.SOURCE);
assertEquals(newConnInfo, newConnectorInfo.result());
|
codereview_new_java_data_12513
|
ClusterAssignment performTaskAssignment(
scheduledRebalance = time.milliseconds() + delay;
} else if (!toExplicitlyRevoke.isEmpty()) {
// We had a revocation in this round but not in the previous round. Let's store that state.
- log.debug("Revoking rebalance. Setting the revokedInPrevious flag to true");
revokedInPrevious = true;
} else if (revokedInPrevious) {
// No revocations in this round but the previous round had one. Probably the workers
The name of the flag is probably not very useful to users who aren't familiar with Java, and there's no guarantee that this log line will remain in sync with changes to the field name or type. This could be clearer with something like:
```suggestion
log.debug("Performing allocation-balancing revocation immediately as no revocations took place during the previous rebalance");
```
ClusterAssignment performTaskAssignment(
scheduledRebalance = time.milliseconds() + delay;
} else if (!toExplicitlyRevoke.isEmpty()) {
// We had a revocation in this round but not in the previous round. Let's store that state.
+ log.debug("Performing allocation-balancing revocation immediately as no revocations took place during the previous rebalance");
revokedInPrevious = true;
} else if (revokedInPrevious) {
// No revocations in this round but the previous round had one. Probably the workers
|
codereview_new_java_data_12515
|
public interface TasksRegistry {
void addPendingTaskToInit(final Collection<Task> tasks);
- void addNewActiveTasks(final Collection<Task> newTasks);
- void addNewStandbyTasks(final Collection<Task> newTasks);
void addTask(final Task task);
I think in future we can consolidate `addNewActiveTasks()` and `addNewStandbyTasks()` into `addTasks()`.
Just an idea, no action needed for this PR!
public interface TasksRegistry {
void addPendingTaskToInit(final Collection<Task> tasks);
+ void addActiveTasks(final Collection<Task> tasks);
+ void addStandbyTasks(final Collection<Task> tasks);
void addTask(final Task task);
|
codereview_new_java_data_12516
|
public enum MetadataVersion {
public static final String FEATURE_NAME = "metadata.version";
/**
- * The first version we currently support in KRaft. We chose 3.3IV0 since it is the first
- * version that supports storing the metadata.version in the log.
*/
public static final MetadataVersion MINIMUM_KRAFT_VERSION = IBP_3_0_IV1;
This comment needs to be fixed.
public enum MetadataVersion {
public static final String FEATURE_NAME = "metadata.version";
/**
+ * The first version we currently support in KRaft.
*/
public static final MetadataVersion MINIMUM_KRAFT_VERSION = IBP_3_0_IV1;
|
codereview_new_java_data_12518
|
public void testBackgroundConnectorDeletion() throws Exception {
// Task configs for the deleted connector should also be removed from the snapshot
assertEquals(Collections.emptyList(), configState.allTaskConfigs(CONNECTOR_IDS.get(0)));
assertEquals(0, configState.taskCount(CONNECTOR_IDS.get(0)));
- assertEquals(0, configStorage.deferredTaskUpdates.size());
configStorage.stop();
Nit: it's better if we can do a comparison of the entire map here, since that provides better error messages if the assertion fails.
Also, we should add a comment explaining why we have this check since it may get removed in a future change if it's unclear why this is necessary.
```suggestion
// Make sure the deleted connector is removed from the map in order to prevent unbounded growth
assertEquals(Collections.emptyMap(), configStorage.deferredTaskUpdates);
```
public void testBackgroundConnectorDeletion() throws Exception {
// Task configs for the deleted connector should also be removed from the snapshot
assertEquals(Collections.emptyList(), configState.allTaskConfigs(CONNECTOR_IDS.get(0)));
assertEquals(0, configState.taskCount(CONNECTOR_IDS.get(0)));
+ // Ensure that the deleted connector's deferred task updates have been cleaned up
+ // in order to prevent unbounded growth of the map
+ assertEquals(Collections.emptyMap(), configStorage.deferredTaskUpdates);
configStorage.stop();
|
codereview_new_java_data_12522
|
private void handleError(
case GROUP_AUTHORIZATION_FAILED:
// Member level errors.
case UNKNOWN_MEMBER_ID:
- case FENCED_INSTANCE_ID:
log.debug("OffsetCommit request for group id {} failed due to error {}.",
groupId.idValue, error);
partitionResults.put(topicPartition, error);
When would we encounter this error? My understanding is that it'll only be returned when the broker receives a request with a group instance ID defined, and IIUC it's not possible to define one with the admin API we expose right now.
private void handleError(
case GROUP_AUTHORIZATION_FAILED:
// Member level errors.
case UNKNOWN_MEMBER_ID:
log.debug("OffsetCommit request for group id {} failed due to error {}.",
groupId.idValue, error);
partitionResults.put(topicPartition, error);
|
codereview_new_java_data_12523
|
public synchronized void handleCommit(BatchReader<Integer> reader) {
}
log.debug("Counter incremented from {} to {}", initialCommitted, committed);
- // A snapshot is being taken here too, not being able to -
- // `import org.apache.kafka.metadata.utils.SnapshotReason`, figure out why?
if (lastOffsetSnapshotted + snapshotDelayInRecords < lastCommittedOffset) {
log.debug(
- "Generating new snapshot with committed offset {} and epoch {} since the previoud snapshot includes {}",
lastCommittedOffset,
lastCommittedEpoch,
lastOffsetSnapshotted
The `raft` module only relies on the `clients` module so it can't import a class from the `metadata` module.
public synchronized void handleCommit(BatchReader<Integer> reader) {
}
log.debug("Counter incremented from {} to {}", initialCommitted, committed);
if (lastOffsetSnapshotted + snapshotDelayInRecords < lastCommittedOffset) {
log.debug(
+ "Generating new snapshot with committed offset {} and epoch {} since the previous snapshot includes {}",
lastCommittedOffset,
lastCommittedEpoch,
lastOffsetSnapshotted
|
codereview_new_java_data_12526
|
public static String[] enumOptions(Class<? extends Enum<?>> enumClass) {
.toArray(String[]::new);
}
- /**
- * Ensures that the provided {@code reason} remains within a range of 255 chars.
- * @param reason This is the reason that is sent to the broker over the wire
- * as a part of {@code JoinGroupRequest}, {@code LeaveGroupRequest} or {@code RemoveMembersFromConsumerGroupOptions} messages.
- * @return a provided reason as is or truncated reason if it exceeds the 255 chars threshold.
- */
- public static String truncateIfRequired(final String reason) {
- if (reason.length() > 255) {
- return reason.substring(0, 255);
- } else {
- return reason;
- }
- }
}
nit: As this is tight to the reason, I would rather put it in `JoinGroupRequest`. Should we call it `maybeTruncateReason`?
public static String[] enumOptions(Class<? extends Enum<?>> enumClass) {
.toArray(String[]::new);
}
}
|
codereview_new_java_data_12527
|
public int hashCode() {
*
* This method does not block until the task is paused.
*
- * The task to be paused is not removed from the restored active tasks and the failed tasks.
* Stateless tasks will never be paused since they are immediately added to the
* restored active tasks.
*
Shouldn't this be:
```
Restored tasks and failed tasks are not paused.
```
or
```
Tasks in restored active tasks and failed tasks are not paused.
```
public int hashCode() {
*
* This method does not block until the task is paused.
*
+ * Restored tasks, removed tasks and failed tasks are not paused so this action would be an no-op for them.
* Stateless tasks will never be paused since they are immediately added to the
* restored active tasks.
*
|
codereview_new_java_data_12530
|
public ListConsumerGroupOffsetsOptions topicPartitions(List<TopicPartition> topi
/**
* Sets an optional requireStable flag.
*/
- public void requireStable(final boolean requireStable) {
this.requireStable = requireStable;
}
/**
Do we need a KIP for this change?
public ListConsumerGroupOffsetsOptions topicPartitions(List<TopicPartition> topi
/**
* Sets an optional requireStable flag.
*/
+ public ListConsumerGroupOffsetsOptions requireStable(final boolean requireStable) {
this.requireStable = requireStable;
+ return this;
}
/**
|
codereview_new_java_data_12532
|
* In contrast, two sub-topologies are not connected but can be linked to each other via topics, i.e., if one
* sub-topology {@link Topology#addSink(String, String, String...) writes} into a topic and another sub-topology
* {@link Topology#addSource(String, String...) reads} from the same topic.
- * Processors and Transformers created with the Processor API are treated as black boxes and are not represented in the topology graph.
* <p>
* When {@link KafkaStreams#start()} is called, different sub-topologies will be constructed and executed as independent
* {@link StreamTask tasks}.
> are not represented
Sounds a little bit like "missing". Also, using the (plain) Processor API, there are only `Processors` anyway -- `Transformers` are part of the DSL-PAPI-integration.
If you use the Processor API, you would still connect Processors to define your graph (eg, `addProcessor(..., <parentProcessor>)` and those connections are represented in the `TopologyDescription`.
The point from the jira was (if I understood it correctly), that `context.forward()` (which does not define the actually structure of the topology, as it does not connect `Processor` but just uses _existing_ connections) is not part of the `TopologyDescription`.
* In contrast, two sub-topologies are not connected but can be linked to each other via topics, i.e., if one
* sub-topology {@link Topology#addSink(String, String, String...) writes} into a topic and another sub-topology
* {@link Topology#addSource(String, String...) reads} from the same topic.
+ * Message {@link ProcessorContext#forward(Object, Object) forwards} using custom Processors and Transformers are not considered in the topology graph.
* <p>
* When {@link KafkaStreams#start()} is called, different sub-topologies will be constructed and executed as independent
* {@link StreamTask tasks}.
|
codereview_new_java_data_12533
|
public void shouldQueryStoresAfterAddingAndRemovingStreamThread() throws Excepti
});
}
- private Matcher<String> retrievableException() {
return is(
- anyOf(
- containsString("Cannot get state store source-table because the stream thread is PARTITIONS_ASSIGNED, not RUNNING"),
- containsString("The state store, source-table, may have migrated to another instance"),
- containsString("Cannot get state store source-table because the stream thread is STARTING, not RUNNING"),
- containsString("The specified partition 1 for store source-table does not exist.")
- )
);
}
I see that this might happen, but I am wondering if we can solve that differently. The reason is that a bug could also throw that exception and we would just retry. Due to exceeding the timeout we would probably understand that it is a bug, but it seems really hard to investigate.
public void shouldQueryStoresAfterAddingAndRemovingStreamThread() throws Excepti
});
}
+ private Matcher<String> retriableException() {
return is(
+ anyOf(
+ containsString("Cannot get state store source-table because the stream thread is PARTITIONS_ASSIGNED, not RUNNING"),
+ containsString("The state store, source-table, may have migrated to another instance"),
+ containsString("Cannot get state store source-table because the stream thread is STARTING, not RUNNING"),
+ containsString("The specified partition 1 for store source-table does not exist.")
+ )
);
}
|
codereview_new_java_data_12537
|
public Optional<QuerySpecification> getCurrentQuerySpecification()
return currentQuerySpecification;
}
@Immutable
public static final class Insert
{
you can use
`functionHandles.values().stream().map(FunctionHandle::getName).collect(toImmutableList());`
public Optional<QuerySpecification> getCurrentQuerySpecification()
return currentQuerySpecification;
}
+ public List<String> getInvokedFunctionNames()
+ {
+ return ImmutableList.copyOf(functionHandles.values().stream().map(FunctionHandle::getName).collect(toImmutableSet()));
+ }
+
@Immutable
public static final class Insert
{
|
codereview_new_java_data_12592
|
private static TextIO.Write writeWithCSVFormatHeaderAndComments(
result.add(
withHeaderCommentsRemoved
// The withSkipHeaderRecord parameter prevents CSVFormat from outputting two copies of
- // the header; we already
.withSkipHeaderRecord()
.format((Object[]) header));
TODO: @damondouglas Fix typo when checks finalize
private static TextIO.Write writeWithCSVFormatHeaderAndComments(
result.add(
withHeaderCommentsRemoved
// The withSkipHeaderRecord parameter prevents CSVFormat from outputting two copies of
+ // the header.
.withSkipHeaderRecord()
.format((Object[]) header));
|
codereview_new_java_data_12595
|
public void testConcurrentNewSampler() throws Exception {
() -> {
for (int i = 0; i < 1000000; i++) {
sampler.sampleOutput("pcollection-" + i, coder).sample(0);
-
- // This sleep is here to allow for the test to stop this thread.
- try {
- Thread.sleep(0);
- } catch (InterruptedException e) {
- return;
- }
}
});
This and the interrupt below are unnecessary. Your test should be able to join all the sampler creating threads.
```suggestion
```
public void testConcurrentNewSampler() throws Exception {
() -> {
for (int i = 0; i < 1000000; i++) {
sampler.sampleOutput("pcollection-" + i, coder).sample(0);
}
});
|
codereview_new_java_data_12627
|
public enum RunecraftAction implements ItemSkillAction
@Override
public String getName(final ItemManager itemManager)
{
- return "Blood Rune (Zeah)";
}
},
TRUE_BLOOD_RUNE(ItemID.BLOOD_RUNE, 77, 10.5f, false)
```suggestion
return "Blood rune (Zeah)";
```
public enum RunecraftAction implements ItemSkillAction
@Override
public String getName(final ItemManager itemManager)
{
+ return "Blood rune (Zeah)";
}
},
TRUE_BLOOD_RUNE(ItemID.BLOOD_RUNE, 77, 10.5f, false)
|
codereview_new_java_data_12628
|
default int outlineFeather()
position = 7,
keyName = "npcToHighlight",
name = "NPCs to Highlight",
- description = "List of NPC names to highlight<br>Separate entries with commas (,)<br>Click anywhere in plugin to reflect changes"
)
default String getNpcToHighlight()
{
```suggestion
description = "List of NPC names to highlight. Format: (NPC), (NPC)"
```
This is the format used by ground items.
default int outlineFeather()
position = 7,
keyName = "npcToHighlight",
name = "NPCs to Highlight",
+ description = "List of NPC names to highlight. Format: (NPC), (NPC)"
)
default String getNpcToHighlight()
{
|
codereview_new_java_data_12629
|
public Dimension render(Graphics2D graphics)
sb.append("Run Time Remaining: ").append(plugin.getEstimatedRunTimeRemaining(false));
}
- if (client.getVarbitValue(Varbits.RUN_SLOWED_DEPLETION_ACTIVE) == 0 && plugin.getRingOfEnduranceCharges() == null && plugin.isRingOfEnduranceEquipped())
{
sb.append("</br>Check your Ring of endurance to get the time remaining.");
}
I don't think this makes sense to show `Run time remaining: xyz<br>Check your Ring of endurance to get the time remaining.` like you are doing here since it is self-contradictory. I would probably do what I had prior to your last change.
public Dimension render(Graphics2D graphics)
sb.append("Run Time Remaining: ").append(plugin.getEstimatedRunTimeRemaining(false));
}
+ if (client.getVarbitValue(Varbits.RUN_SLOWED_DEPLETION_ACTIVE) == 0
+ && plugin.isRingOfEnduranceEquipped()
+ && plugin.getRingOfEnduranceCharges() == null)
{
sb.append("</br>Check your Ring of endurance to get the time remaining.");
}
|
codereview_new_java_data_12630
|
@Getter
public enum FishingSpot
{
- SHRIMP("Shrimp, Sardine, Herring, Anchovies", "Anchovies", ItemID.RAW_SHRIMPS,
FISHING_SPOT_1514, FISHING_SPOT_1517, FISHING_SPOT_1518,
FISHING_SPOT_1521, FISHING_SPOT_1523, FISHING_SPOT_1524,
FISHING_SPOT_1525, FISHING_SPOT_1528, FISHING_SPOT_1530,
These should be grouped by fishing type, eg. net first then bait
```suggestion
SHRIMP("Shrimp, Anchovies, Sardine, Herring", "Anchovies", ItemID.RAW_SHRIMPS,
```
@Getter
public enum FishingSpot
{
+ SHRIMP("Shrimp, Anchovies, Sardine, Herring", "Anchovies", ItemID.RAW_SHRIMPS,
FISHING_SPOT_1514, FISHING_SPOT_1517, FISHING_SPOT_1518,
FISHING_SPOT_1521, FISHING_SPOT_1523, FISHING_SPOT_1524,
FISHING_SPOT_1525, FISHING_SPOT_1528, FISHING_SPOT_1530,
|
codereview_new_java_data_12631
|
package io.cdap.cdap.sourcecontrol.operationrunner;
/**
- * Exception thrown when push operation fails in operation runner.
- * Encapsulates all underlying exceptions.
*/
-public class PushFailureException extends Exception {
- public PushFailureException(String message, Exception cause) {
super(message, cause);
}
- public PushFailureException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public PushFailureException(String message) {
super(message);
}
}
Any reason we want it to extend `RuntimeException`?
package io.cdap.cdap.sourcecontrol.operationrunner;
/**
+ * Exception thrown when source control operation fails in runner.
+ * Encapsulates some underlying exceptions.
+ * Should be subclassed for common root-causes
*/
+// TODO https://cdap.atlassian.net/browse/CDAP-20410 Classify and make suberrors based on root causes
+public class SourceControlException extends RuntimeException {
+ public SourceControlException(String message, Throwable cause) {
super(message, cause);
}
+ public SourceControlException(String message) {
super(message);
}
}
|
codereview_new_java_data_12948
|
private static boolean themeConfigurationChanged(Options options,
JsonObject statsJson,
FrontendDependenciesScanner frontendDependencies)
throws IOException {
- Map<String, String> themeJsonHashes = new HashMap<>(1);
if (options.jarFiles == null) {
return false;
nit: I don't think `1` is necessary here
private static boolean themeConfigurationChanged(Options options,
JsonObject statsJson,
FrontendDependenciesScanner frontendDependencies)
throws IOException {
+ Map<String, String> themeJsonHashes = new HashMap<>();
if (options.jarFiles == null) {
return false;
|
codereview_new_java_data_12950
|
public class BuildFrontendMojo extends FlowModeAbstractMojo
* If using pnpm, the install will be run with {@code --frozen-lockfile}
* parameter.
*
- * This makes sure that the package lock file will not be overwritten.
*/
@Parameter(property = InitParameters.CI_BUILD, defaultValue = "false")
private boolean ciBuild;
```suggestion
* This makes sure that the versions in package lock file will not be overwritten and production builds are reproducible.
```
public class BuildFrontendMojo extends FlowModeAbstractMojo
* If using pnpm, the install will be run with {@code --frozen-lockfile}
* parameter.
*
+ * This makes sure that the versions in package lock file will not be overwritten and production builds are reproducible.
*/
@Parameter(property = InitParameters.CI_BUILD, defaultValue = "false")
private boolean ciBuild;
|
codereview_new_java_data_12951
|
public void applicationTheme_GlobalCss_isUsedOnlyInEmbeddedComponent() {
"none", background);
// font-family from web component doesn't leak to the document
- Assert.assertFalse(body.getCssValue("font-family").contains("Ostrich"));
// font-family of the document is applied and not overridden by Lumo
Assert.assertTrue(
Isn't this the same as the old `assertNotEquals`?
public void applicationTheme_GlobalCss_isUsedOnlyInEmbeddedComponent() {
"none", background);
// font-family from web component doesn't leak to the document
+ Assert.assertNotEquals("Ostrich", body.getCssValue("font-family"));
// font-family of the document is applied and not overridden by Lumo
Assert.assertTrue(
|
codereview_new_java_data_12952
|
* <p>
* Vaadin gets the SystemMessages from the {@link SystemMessagesProvider}
* configured in {@link VaadinService}. You can customize this by creating a
- * {@link VaadinServiceInitListener} that sets an instance on
* {@link SystemMessagesProvider} to
* {@link VaadinService#setSystemMessagesProvider(SystemMessagesProvider)}, that
* in turns creates instances of CustomizedSystemMessages.
Should this be "an instance of" ?
* <p>
* Vaadin gets the SystemMessages from the {@link SystemMessagesProvider}
* configured in {@link VaadinService}. You can customize this by creating a
+ * {@link VaadinServiceInitListener} that sets an instance of
* {@link SystemMessagesProvider} to
* {@link VaadinService#setSystemMessagesProvider(SystemMessagesProvider)}, that
* in turns creates instances of CustomizedSystemMessages.
|
codereview_new_java_data_12953
|
public SecurityContextHolderStrategy securityContextHolderStrategy() {
return vaadinAwareSecurityContextHolderStrategy;
}
-}
\ No newline at end of file
new line missing
```suggestion
}
```
public SecurityContextHolderStrategy securityContextHolderStrategy() {
return vaadinAwareSecurityContextHolderStrategy;
}
\ No newline at end of file
+}
|
codereview_new_java_data_12954
|
public interface EndpointRequestUtil extends Serializable {
boolean isAnonymousEndpoint(HttpServletRequest request);
/**
- * Shows whether the Hilla is used in the project.
*
- * @return true if Hilla is used, false otherwise
*/
static boolean isEndpointUsed() {
try {
```suggestion
* @return true if Hilla is available, false otherwise
```
public interface EndpointRequestUtil extends Serializable {
boolean isAnonymousEndpoint(HttpServletRequest request);
/**
+ * Checks if Hilla is available.
*
+ * @return true if Hilla is available, false otherwise
*/
static boolean isEndpointUsed() {
try {
|
codereview_new_java_data_12955
|
public void filter_messageNotYetSeen_addToCacheAndContinue() {
Assert.assertEquals("Expecting message not seen on client to be sent",
ACTION.CONTINUE, action.action());
Assert.assertSame(
- "Message should not be altered by filter when aborting",
message, action.message());
Mockito.verify(cache).addToCache(ArgumentMatchers.eq(broadcasterId),
ArgumentMatchers.eq(RESOURCE_UUID),
Should this be "Message should not be altered by filter when continuing"
public void filter_messageNotYetSeen_addToCacheAndContinue() {
Assert.assertEquals("Expecting message not seen on client to be sent",
ACTION.CONTINUE, action.action());
Assert.assertSame(
+ "Message should not be altered by filter when continuing",
message, action.message());
Mockito.verify(cache).addToCache(ArgumentMatchers.eq(broadcasterId),
ArgumentMatchers.eq(RESOURCE_UUID),
|
codereview_new_java_data_12956
|
public boolean isNavigationSupported() {
* @return the currently active route instance if available
*/
public Optional<Component> getCurrentView() {
- try {
- return Optional.ofNullable((Component) getInternals()
- .getActiveRouterTargetsChain().get(0));
- } catch (Exception e) {
- // Current route is not always available
return Optional.empty();
}
}
/**
What exceptions may be raised by this code?
If it is only to catch `IndexOutOfBoundsException`, I would prefer a check on `List.isEmpty()`.
public boolean isNavigationSupported() {
* @return the currently active route instance if available
*/
public Optional<Component> getCurrentView() {
+ if(getInternals().getActiveRouterTargetsChain().isEmpty()) {
return Optional.empty();
}
+ return Optional.of((Component) getInternals()
+ .getActiveRouterTargetsChain().get(0));
}
/**
|
codereview_new_java_data_12957
|
import com.vaadin.flow.server.VaadinServletContext;
import jakarta.servlet.ServletContext;
-import jakarta.servlet.ServletContextListener;
import jakarta.websocket.DeploymentException;
import jakarta.websocket.server.ServerContainer;
import jakarta.websocket.server.ServerEndpointConfig;
/**
* Creates the websocket endpoint that the Vite client JS connects to.
*/
-public class ViteWebsocketEndpointInitializer
- implements ServletContextListener {
/**
* Creates the websocket endpoint that Vite connects to.
It looks like that the only usage of this class is in `ViteHandler` and it is instantiated manually.
What is the purpose of making it implement `ServletContextListener`?
Is it meant for manual registrations in `ServeltContext`?
import com.vaadin.flow.server.VaadinServletContext;
import jakarta.servlet.ServletContext;
import jakarta.websocket.DeploymentException;
import jakarta.websocket.server.ServerContainer;
import jakarta.websocket.server.ServerEndpointConfig;
/**
* Creates the websocket endpoint that the Vite client JS connects to.
*/
+public class ViteWebsocketEndpointInitializer {
/**
* Creates the websocket endpoint that Vite connects to.
|
codereview_new_java_data_12958
|
public void onOpen(Session session, EndpointConfig config) {
proxy = new ViteWebsocketProxy(session, vitePort);
session.addMessageHandler(proxy);
} catch (Exception e) {
- getLogger().debug("Error creating Vite proxy connection", e);
try {
session.close();
} catch (IOException e1) {
Should we log at `error` level to make it more evident why it is not working as expected?
public void onOpen(Session session, EndpointConfig config) {
proxy = new ViteWebsocketProxy(session, vitePort);
session.addMessageHandler(proxy);
} catch (Exception e) {
+ getLogger().error("Error creating Vite proxy connection", e);
try {
session.close();
} catch (IOException e1) {
|
codereview_new_java_data_12959
|
* that manages instances according to the conventions of that framework.
* <p>
* {@link VaadinService} will by default use {@link ServiceLoader} for finding
- * an instantiator implementation. It is possible to override this mechanism by
- * overriding {@link VaadinService#createInstantiator}.
*
* @author Vaadin Ltd
* @since 1.0
Isn't it still true that `DefaulInstantiator` will be used if no custom implementation is found?
* that manages instances according to the conventions of that framework.
* <p>
* {@link VaadinService} will by default use {@link ServiceLoader} for finding
+ * an instantiator implementation. If not found {@link DefaultInstantiator} will
+ * be used. It is possible to override this mechanism by overriding
+ * {@link VaadinService#createInstantiator}.
*
* @author Vaadin Ltd
* @since 1.0
|
codereview_new_java_data_12960
|
public void testAddOn() {
}
@Test
- public void noFrontendFilesCreated() {
File baseDir = new File(System.getProperty("user.dir", "."));
- // shouldn't create a dev-bundle
Assert.assertTrue("New devBundle should be generated",
new File(baseDir, "dev-bundle").exists());
Assert.assertTrue("node_modules should be downloaded",
```suggestion
public void frontendFilesCreated() {
```
public void testAddOn() {
}
@Test
+ public void frontendFilesCreated() {
File baseDir = new File(System.getProperty("user.dir", "."));
+ // should create a dev-bundle
Assert.assertTrue("New devBundle should be generated",
new File(baseDir, "dev-bundle").exists());
Assert.assertTrue("node_modules should be downloaded",
|
codereview_new_java_data_12961
|
public void fetchCurrentURL(SerializableConsumer<URL> callback) {
* to be notified when the direction is resolved.
*/
public void fetchPageDirection(SerializableConsumer<Direction> callback) {
- UI.getCurrent().getPage().executeJs("return document.dir")
- .then(String.class, dir -> {
- Direction direction = getDirectionByClientName(dir);
- callback.accept(direction);
- });
}
private Direction getDirectionByClientName(String directionClientName) {
Do we need `UI.getCurrent().getPage()` here, since the method is not static? Could it be simply a call to `executeJs`?
```suggestion
executeJs("return document.dir")
```
public void fetchCurrentURL(SerializableConsumer<URL> callback) {
* to be notified when the direction is resolved.
*/
public void fetchPageDirection(SerializableConsumer<Direction> callback) {
+ executeJs("return document.dir").then(String.class, dir -> {
+ Direction direction = getDirectionByClientName(dir);
+ callback.accept(direction);
+ });
}
private Direction getDirectionByClientName(String directionClientName) {
|
codereview_new_java_data_12962
|
&& frontendFileExists(localModulePath)) {
notFoundMessage(resourceNotFound, prefix, suffix));
}
if (!npmNotFound.isEmpty() && getLogger().isInfoEnabled()
- && (options.productionMode || options.isDevBundleBuild())) {
getLogger().info(notFoundMessage(npmNotFound,
"Failed to find the following imports in the `node_modules` tree:",
getImportsNotFoundMessage()));
Is this condition correct? Shouldn't it output the warnings also when running in dev mode with a dev server?
&& frontendFileExists(localModulePath)) {
notFoundMessage(resourceNotFound, prefix, suffix));
}
+ boolean devModeWithoutServer = !options.productionMode
+ && !options.isEnableDevServer() && !options.isDevBundleBuild();
if (!npmNotFound.isEmpty() && getLogger().isInfoEnabled()
+ && !devModeWithoutServer) {
getLogger().info(notFoundMessage(npmNotFound,
"Failed to find the following imports in the `node_modules` tree:",
getImportsNotFoundMessage()));
|
codereview_new_java_data_12963
|
protected void checkLogsForErrors(
"Received error message in browser log console right after opening the page, message: %s",
logEntry));
} else {
- if (logEntry.getMessage().contains(
- "Lit is in dev mode. Not recommended for production")) {
- return;
- }
LoggerFactory.getLogger(TestBenchHelpers.class.getName()).warn(
"This message in browser log console may be a potential error: '{}'",
logEntry);
This is no longer needed as it is checked above
protected void checkLogsForErrors(
"Received error message in browser log console right after opening the page, message: %s",
logEntry));
} else {
LoggerFactory.getLogger(TestBenchHelpers.class.getName()).warn(
"This message in browser log console may be a potential error: '{}'",
logEntry);
|
codereview_new_java_data_12964
|
public <T> T findAncestor(Class<T> componentType) {
* Removes the component from its parent.
*/
public void removeFromParent() {
- findAncestor(HasComponents.class).remove(this);
}
}
There's no guarantee the immediate parent component implements `HasComponents` since that's just a marker interface that adds some convenience methods. I think it would be safer to use `this.getElement().removeFromParent()` instead.
public <T> T findAncestor(Class<T> componentType) {
* Removes the component from its parent.
*/
public void removeFromParent() {
+ getElement().removeFromParent();
}
}
|
codereview_new_java_data_12965
|
public class InitParameters implements Serializable {
* Configuration name for the time waiting for the frontend build tool to
* output a success or error pattern.
*/
- public static final String SERVLET_PARAMETER_DEVMODE_WEBPACK_TIMEOUT = "devmode.webpack.output.pattern.timeout";
/**
* Configuration name for adding extra options to the vite.
Could this just be changed to be `SERVLET_PARAMETER_DEVMODE_TIMEOUT` and `devmode.output.pattern.timeout`?
public class InitParameters implements Serializable {
* Configuration name for the time waiting for the frontend build tool to
* output a success or error pattern.
*/
+ public static final String SERVLET_PARAMETER_DEVMODE_TIMEOUT = "devmode.output.pattern.timeout";
/**
* Configuration name for adding extra options to the vite.
|
codereview_new_java_data_12966
|
import org.apache.commons.io.FileUtils;
/**
- * Utility class for stubbing Node.JS and Vite scripts.
*/
public class FrontendStubs {
Should we just say bundler instead of naming the specific one used?
import org.apache.commons.io.FileUtils;
/**
+ * Utility class for stubbing Node.JS and frontend tooling.
*/
public class FrontendStubs {
|
codereview_new_java_data_12968
|
.getResourceAsStream("version.properties"));
} catch (Exception e) {
LoggerFactory.getLogger(PolymerTemplate.class.getName())
- .warn("Unable to read the version.properties file.", e);
- throw new ExceptionInInitializerError(e);
}
LicenseChecker.checkLicenseFromStaticBlock("flow-polymer-template",
Should this be an error log level without `e` (because it would be logged twice, because the exception is thrown)?
.getResourceAsStream("version.properties"));
} catch (Exception e) {
LoggerFactory.getLogger(PolymerTemplate.class.getName())
+ .error("Unable to read the version.properties file.", e);
}
LicenseChecker.checkLicenseFromStaticBlock("flow-polymer-template",
|
codereview_new_java_data_12969
|
import java.net.URISyntaxException;
import java.nio.file.Path;
-import org.apache.commons.lang3.Conversion;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
Leftover? Remove if not used.
import java.net.URISyntaxException;
import java.nio.file.Path;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
|
codereview_new_java_data_12970
|
*/
public class TaskGenerateBootstrap extends AbstractTaskClientGenerator {
- static final String DEV_TOOLS_IMPORT = String.format("import '"
- + FrontendUtils.JAR_RESOURCES_IMPORT + "vaadin-dev-tools.js';%n");
private final FrontendDependenciesScanner frontDeps;
private final File frontendGeneratedDirectory;
private final File frontendDirectory;
```suggestion
static final String DEV_TOOLS_IMPORT = String.format("import '%svaadin-dev-tools.js';%n", FrontendUtils.JAR_RESOURCES_IMPORT );
```
As it's string format we should just use the format format.
*/
public class TaskGenerateBootstrap extends AbstractTaskClientGenerator {
+ static final String DEV_TOOLS_IMPORT = String.format("import '%svaadin-dev-tools.js';%n", FrontendUtils.JAR_RESOURCES_IMPORT );
private final FrontendDependenciesScanner frontDeps;
private final File frontendGeneratedDirectory;
private final File frontendDirectory;
|
codereview_new_java_data_12972
|
default boolean isPnpmEnabled() {
* Returns whether server-side and offline license checking are enabled or
* not.
* <p>
- * New license checker is only available in NPM mode with enabled live reload.
* Once compatibility/bower mode is used or live reload is disabled,
* the old license checker is used.
*
- * @return {@code true} if disabled - old JavaScript license checker is used,
* {@code false} if new license checker enabled
* @since 2.8
*/
Why is the license checker related to if you want to use live reload?
default boolean isPnpmEnabled() {
* Returns whether server-side and offline license checking are enabled or
* not.
* <p>
+ * New license checker is only available in npm mode with enabled live reload.
* Once compatibility/bower mode is used or live reload is disabled,
* the old license checker is used.
*
+ * @return {@code true} if old JavaScript license checker is used,
* {@code false} if new license checker enabled
* @since 2.8
*/
|
codereview_new_java_data_12973
|
public static class Builder implements Serializable {
* Whether to disable server-side and offline new license checking
* features and enable old JavaScript license checker.
*/
- private boolean enableOldLicenseChecker = false;
/**
* Create a builder instance given an specific npm folder.
```suggestion
private boolean oldLicenseChecker = false;
```
public static class Builder implements Serializable {
* Whether to disable server-side and offline new license checking
* features and enable old JavaScript license checker.
*/
+ private boolean oldLicenseChecker = false;
/**
* Create a builder instance given an specific npm folder.
|
codereview_new_java_data_12974
|
protected void configure(HttpSecurity http) throws Exception {
* {@link org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration}
* to configure the current {@link SecurityContextHolderStrategy}.
*/
- @Bean
public SecurityContextHolderStrategy securityContextHolderStrategy() {
VaadinAwareSecurityContextHolderStrategy vaadinAwareSecurityContextHolderStrategy = new VaadinAwareSecurityContextHolderStrategy();
// Use a security context holder that can find the context from Vaadin
Should this been be named `vaadinSecurityContextHolderStrategy`?
protected void configure(HttpSecurity http) throws Exception {
* {@link org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration}
* to configure the current {@link SecurityContextHolderStrategy}.
*/
+ @Bean(name = "VaadinSecurityContextHolderStrategy")
public SecurityContextHolderStrategy securityContextHolderStrategy() {
VaadinAwareSecurityContextHolderStrategy vaadinAwareSecurityContextHolderStrategy = new VaadinAwareSecurityContextHolderStrategy();
// Use a security context holder that can find the context from Vaadin
|
codereview_new_java_data_12975
|
/*
- * Copyright 2000-2017 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
```suggestion
* Copyright 2000-2022 Vaadin Ltd.
```
/*
+ * Copyright 2000-2022 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
|
codereview_new_java_data_12977
|
protected UI(UIInternalUpdater internalsHandler) {
getNode().getFeature(ElementData.class).setTag("body");
Component.setElement(this, Element.get(getNode()));
pushConfiguration = new PushConfigurationImpl(this);
- // Component::setVisible relies on hidden attribute.
- // Adds a global display:none style to elements with hidden attribute
- page.addStyleSheet("./frontend/styles/hidden.css");
}
/**
Doesn't this cause a separate request for this file? It should be part of the index page or bundle
protected UI(UIInternalUpdater internalsHandler) {
getNode().getFeature(ElementData.class).setTag("body");
Component.setElement(this, Element.get(getNode()));
pushConfiguration = new PushConfigurationImpl(this);
}
/**
|
codereview_new_java_data_12978
|
public void should_failWithIllegalStateException_when_customWebpackConfigFileExi
IllegalStateException.class,
() -> builder.build().execute());
Assert.assertTrue(exception.getMessage().contains(
- "webpack related config file 'webpack.config.js' is detected in your"));
}
}
```suggestion
"Webpack related config file 'webpack.config.js' is detected in your"));
```
public void should_failWithIllegalStateException_when_customWebpackConfigFileExi
IllegalStateException.class,
() -> builder.build().execute());
Assert.assertTrue(exception.getMessage().contains(
+ "Webpack related config file 'webpack.config.js' is detected in your"));
}
}
|
codereview_new_java_data_12979
|
public class FeatureFlags implements Serializable {
"collaborationEngineBackend",
"https://github.com/vaadin/platform/issues/1988", true, null);
public static final Feature GRID_MULTI_SORT_PRIORITY_APPEND = new Feature(
- "Grid Grid MultiSort priority new behavior",
"multiSortPriorityAppend",
"https://github.com/vaadin/platform/issues/3052", false, null);
private List<Feature> features = new ArrayList<>();
```suggestion
"Grid MultiSort priority new behavior",
```
public class FeatureFlags implements Serializable {
"collaborationEngineBackend",
"https://github.com/vaadin/platform/issues/1988", true, null);
public static final Feature GRID_MULTI_SORT_PRIORITY_APPEND = new Feature(
+ "Grid MultiSort priority new behavior",
"multiSortPriorityAppend",
"https://github.com/vaadin/platform/issues/3052", false, null);
private List<Feature> features = new ArrayList<>();
|
codereview_new_java_data_12980
|
public interface TaskGenerateHilla extends FallibleCommand {
* the project root directory. In a Maven multi-module project,
* this is the module root, not the main project one.
* @param buildDirectoryName
- * the name of the build directory (i.e. "build" or
* "target").
*/
default void configure(File projectDirectory, String buildDirectoryName) {
I think HTML space entity is not needed
```suggestion
* the name of the build directory (i.e. "build" or
```
public interface TaskGenerateHilla extends FallibleCommand {
* the project root directory. In a Maven multi-module project,
* this is the module root, not the main project one.
* @param buildDirectoryName
+ * the name of the build directory (i.e. "build" or
* "target").
*/
default void configure(File projectDirectory, String buildDirectoryName) {
|
codereview_new_java_data_12981
|
public boolean hasListener(Class<? extends ComponentEvent> eventType) {
*
* @param eventType
* the component event type
- * @return A collection with all registered listeners. Empty if no listeners
- * are found.
*/
- protected Collection<?> getListeners(
Class<? extends ComponentEvent> eventType) {
if (eventType == null) {
throw new IllegalArgumentException("Event type cannot be null");
I suggest to make this method public, since from the component event bus perspective it's a public API
public boolean hasListener(Class<? extends ComponentEvent> eventType) {
*
* @param eventType
* the component event type
+ * @return A collection with all registered listeners for a given event
+ * type. Empty if no listeners are found.
*/
+ public Collection<?> getListeners(
Class<? extends ComponentEvent> eventType) {
if (eventType == null) {
throw new IllegalArgumentException("Event type cannot be null");
|
codereview_new_java_data_12982
|
public static <T extends ComponentEvent<?>> boolean hasEventListener(
*
* @param eventType
* the component event type
- * @return A collection with all registered listeners. Empty if no listeners
- * are found.
*/
public static Collection<?> getListeners(Component component,
Class<? extends ComponentEvent> eventType) {
-> "A collection with all registered listeners for a given event type"
public static <T extends ComponentEvent<?>> boolean hasEventListener(
*
* @param eventType
* the component event type
+ * @return A collection with all registered listeners for a given event
+ * type. Empty if no listeners are found.
*/
public static Collection<?> getListeners(Component component,
Class<? extends ComponentEvent> eventType) {
|
codereview_new_java_data_12983
|
public class TaskUpdateThemeImport implements FallibleCommand {
TaskUpdateThemeImport(File npmFolder, ThemeDefinition theme,
File frontendDirectory) {
- this(npmFolder, theme, frontendDirectory,
- new File(frontendDirectory, GENERATED));
- }
-
- TaskUpdateThemeImport(File npmFolder, ThemeDefinition theme,
- File frontendDirectory, File frontendGeneratedFolder) {
this.theme = theme;
this.frontendDirectory = frontendDirectory;
this.npmFolder = npmFolder;
themeImportFile = new File(frontendGeneratedFolder, THEME_IMPORTS_NAME);
themeImportFileDefinition = new File(frontendGeneratedFolder,
THEME_IMPORTS_D_TS_NAME);
Is there a need to add this instead of changing the below one?
public class TaskUpdateThemeImport implements FallibleCommand {
TaskUpdateThemeImport(File npmFolder, ThemeDefinition theme,
File frontendDirectory) {
this.theme = theme;
this.frontendDirectory = frontendDirectory;
this.npmFolder = npmFolder;
+ File frontendGeneratedFolder = new File(frontendDirectory, GENERATED);
themeImportFile = new File(frontendGeneratedFolder, THEME_IMPORTS_NAME);
themeImportFileDefinition = new File(frontendGeneratedFolder,
THEME_IMPORTS_D_TS_NAME);
|
codereview_new_java_data_12984
|
default Validator<V> getDefaultValidator() {
* */
* @Override
* public Validator getDefaultValidator() {
- * return (value, valueContext) -> clientSideValid ? ValidationResult.ok()
* : ValidationResult.error("Invalid date format");
* }
*
```suggestion
* return (value, valueContext) -> clientSideValid ? ValidationResult.ok()
```
default Validator<V> getDefaultValidator() {
* */
* @Override
* public Validator getDefaultValidator() {
+ * return (value, valueContext) -> clientSideValid ? ValidationResult.ok()
* : ValidationResult.error("Invalid date format");
* }
*
|
codereview_new_java_data_12985
|
Map<String, String> getDefaultDependencies() {
defaults.put("@polymer/polymer", POLYMER_VERSION);
- defaults.put("lit", "2.2.5");
// Constructable style sheets is only implemented for chrome,
// polyfill needed for FireFox et.al. at the moment
```suggestion
defaults.put("lit", "2.2.3");
```
Map<String, String> getDefaultDependencies() {
defaults.put("@polymer/polymer", POLYMER_VERSION);
+ defaults.put("lit", "2.2.3");
// Constructable style sheets is only implemented for chrome,
// polyfill needed for FireFox et.al. at the moment
|
codereview_new_java_data_12986
|
public void should_BeAbleToCustomizeFolders() throws Exception {
.exists());
}
- @Ignore("Vite doesn't take into account v14 bootstrapping")
@Test
public void should_SetIsClientBootstrapMode_When_EnableClientSideBootstrapMode()
throws ExecutionFailedException, IOException {
```suggestion
@Ignore("Making Vite support v14 bootstrapping is not planned. V14 bootstrapping requires Webpack to be enabled.")
```
public void should_BeAbleToCustomizeFolders() throws Exception {
.exists());
}
+ @Ignore("Making Vite support v14 bootstrapping is not planned. V14 bootstrapping requires Webpack to be enabled.")
@Test
public void should_SetIsClientBootstrapMode_When_EnableClientSideBootstrapMode()
throws ExecutionFailedException, IOException {
|
codereview_new_java_data_12987
|
import org.junit.After;
import org.junit.Ignore;
-@Ignore("Vite, service worker not working on nested path")
public class ServiceWorkerOnNestedMappingIT extends ServiceWorkerIT {
@Override
Issue reference is needed
import org.junit.After;
import org.junit.Ignore;
+@Ignore("Service worker not working on nested path with VITE. See https://github.com/vaadin/flow/issues/14227")
public class ServiceWorkerOnNestedMappingIT extends ServiceWorkerIT {
@Override
|
codereview_new_java_data_12988
|
JsonObject getPlatformPinnedDependencies() throws IOException {
URL commVersionsResource = finder
.getResource(Constants.VAADIN_VERSIONS_JSON);
if (commVersionsResource == null) {
- log().info(
- "Couldn't find {} file to pin dependency versions for commercial components."
+ " Transitive dependencies won't be pinned for npm/pnpm.",
Constants.VAADIN_VERSIONS_JSON);
return versionsJson;
Is there a way to determine if a commercial component is used? Otherwise this would be printed always and kinda looks like a bad advertisement every-time the app is build.
JsonObject getPlatformPinnedDependencies() throws IOException {
URL commVersionsResource = finder
.getResource(Constants.VAADIN_VERSIONS_JSON);
if (commVersionsResource == null) {
+ log().trace(
+ "{} file is not present in the classpath, so cannot pin dependency versions for commercial components."
+ " Transitive dependencies won't be pinned for npm/pnpm.",
Constants.VAADIN_VERSIONS_JSON);
return versionsJson;
|
codereview_new_java_data_12989
|
* subscribe for each other's validation statuses and enable/disable or clear
* values, etc. respectively.
*
- * @since 23.2
*
* @see HasValidator
* @see com.vaadin.flow.data.binder.Binder.BindingBuilderImpl#bind(ValueProvider,
```suggestion
* @since 2.7
```
* subscribe for each other's validation statuses and enable/disable or clear
* values, etc. respectively.
*
+ * @since 2.7
*
* @see HasValidator
* @see com.vaadin.flow.data.binder.Binder.BindingBuilderImpl#bind(ValueProvider,
|
codereview_new_java_data_12990
|
default Validator<V> getDefaultValidator() {
*
* @see com.vaadin.flow.data.binder.Binder.BindingBuilderImpl#bind(ValueProvider,
* Setter)
- * @since 23.2
*
* @return Registration of the added listener.
*/
```suggestion
* @since 2.7
```
default Validator<V> getDefaultValidator() {
*
* @see com.vaadin.flow.data.binder.Binder.BindingBuilderImpl#bind(ValueProvider,
* Setter)
+ * @since 2.7
*
* @return Registration of the added listener.
*/
|
codereview_new_java_data_12991
|
* {@link ValidationStatusChangeListener#validationStatusChanged(ValidationStatusChangeEvent)}
* invoked.
*
- * @since 23.2
*
* @param <V>
* the value type
```suggestion
* @since 2.7
```
* {@link ValidationStatusChangeListener#validationStatusChanged(ValidationStatusChangeEvent)}
* invoked.
*
+ * @since 2.7
*
* @param <V>
* the value type
|
codereview_new_java_data_12992
|
* {@link ValidationStatusChangeListener#validationStatusChanged(ValidationStatusChangeEvent)}
* invoked.
*
- * @since 23.2
*
* @param <V>
* the value type
```suggestion
* @since 2.7
```
* {@link ValidationStatusChangeListener#validationStatusChanged(ValidationStatusChangeEvent)}
* invoked.
*
+ * @since 2.7
*
* @param <V>
* the value type
|
codereview_new_java_data_12993
|
default Validator<V> getDefaultValidator() {
*
* @see com.vaadin.flow.data.binder.Binder.BindingBuilderImpl#bind(ValueProvider,
* Setter)
- * @since 23.2
*
* @return Registration of the added listener.
*/
if this method is down-ported to anything from 14.x to 23.1.x - this since tag is really weird
default Validator<V> getDefaultValidator() {
*
* @see com.vaadin.flow.data.binder.Binder.BindingBuilderImpl#bind(ValueProvider,
* Setter)
+ * @since 2.7
*
* @return Registration of the added listener.
*/
|
codereview_new_java_data_12994
|
* subscribe for each other's validation statuses and enable/disable or clear
* values, etc. respectively.
*
- * @since 23.2
*
* @see HasValidator
* @see com.vaadin.flow.data.binder.Binder.BindingBuilderImpl#bind(ValueProvider,
```suggestion
* @since 2.7
```
* subscribe for each other's validation statuses and enable/disable or clear
* values, etc. respectively.
*
+ * @since 2.7
*
* @see HasValidator
* @see com.vaadin.flow.data.binder.Binder.BindingBuilderImpl#bind(ValueProvider,
|
codereview_new_java_data_13006
|
private final class AsyncReply {
this.noResponseFuture =
getTaskScheduler()
.schedule(() -> {
- cleanUp(this.haveSemaphore, this.connection, this.connection.getConnectionId());
- this.future.completeExceptionally(
new MessageTimeoutException(requestMessage,
- "Timed out waiting for response"));
}, Instant.now().plusMillis(remoteTimeout));
}
else {
I think there's a new race here; we could end up releasing the semaphore twice because `onMessage` calls cleanup before completing the future.
Perhaps check if `pendingReplies` was actually removed in cleanup before releasing the semaphore?
private final class AsyncReply {
this.noResponseFuture =
getTaskScheduler()
.schedule(() -> {
+ if (this.future.completeExceptionally(
new MessageTimeoutException(requestMessage,
+ "Timed out waiting for response"))) {
+
+ cleanUp(this.haveSemaphore, this.connection, this.connection.getConnectionId());
+ }
}, Instant.now().plusMillis(remoteTimeout));
}
else {
|
codereview_new_java_data_13007
|
private <T extends IntegrationNode> ReceiveCounters retrieveCounters(T node, Str
(long) (failures == null ? 0 : failures.count()));
}
- private static TimerStats buildTimerStats(Timer timer) {
return timer == null
? ZERO_TIMER_STATS
: new TimerStats(timer.count(), timer.mean(TimeUnit.MILLISECONDS), timer.max(TimeUnit.MILLISECONDS));
```suggestion
private static TimerStats buildTimerStats(@Nullable Timer timer) {
```
private <T extends IntegrationNode> ReceiveCounters retrieveCounters(T node, Str
(long) (failures == null ? 0 : failures.count()));
}
+ private static TimerStats buildTimerStats(@Nullable Timer timer) {
return timer == null
? ZERO_TIMER_STATS
: new TimerStats(timer.count(), timer.mean(TimeUnit.MILLISECONDS), timer.max(TimeUnit.MILLISECONDS));
|
codereview_new_java_data_13008
|
public void setLengthCheck(boolean lengthCheck) {
/**
* If true, DNS reverse lookup is done on the remote ip address.
- * Default false: not all environments (e.g. Docker containers) does a reliable DNS resolution.
* @param lookupHost the lookupHost to set
*/
public void setLookupHost(boolean lookupHost) {
```suggestion
* Default false: not all environments (e.g. Docker containers) perform reliable DNS
* resolution.
```
public void setLengthCheck(boolean lengthCheck) {
/**
* If true, DNS reverse lookup is done on the remote ip address.
+ * Default false: not all environments (e.g. Docker containers) perform reliable DNS
+ * resolution.
* @param lookupHost the lookupHost to set
*/
public void setLookupHost(boolean lookupHost) {
|
codereview_new_java_data_13162
|
public void startCommand(@NotNull Project project, @NotNull FlutterSdk sdk, @Nul
ProgramRunnerUtil.executeConfiguration(env, false, true);
}
- public void startCommandInBazelContext(@NotNull Project project, @NotNull Workspace workspace, AnActionEvent event) {
FlutterInitializer.sendAnalyticsAction(this);
RunConfiguration configuration = findRunConfig(project);
Looks like `event` should be `@NotNull`.
public void startCommand(@NotNull Project project, @NotNull FlutterSdk sdk, @Nul
ProgramRunnerUtil.executeConfiguration(env, false, true);
}
+ public void startCommandInBazelContext(@NotNull Project project, @NotNull Workspace workspace, @NotNull AnActionEvent event) {
FlutterInitializer.sendAnalyticsAction(this);
RunConfiguration configuration = findRunConfig(project);
|
codereview_new_java_data_13163
|
public VirtualFile getPackagesFile() {
public @Nullable Map<String, String> getPackagesMap() {
final var packageConfigFile = getPackageConfigFile();
- if(packageConfigFile != null) {
return DotPackagesFileUtil.getPackagesMapFromPackageConfigJsonFile(packageConfigFile);
}
final var packagesFile = getPackagesFile();
- if(packagesFile != null) {
return DotPackagesFileUtil.getPackagesMap(packagesFile);
}
"if (" -- needs a space
public VirtualFile getPackagesFile() {
public @Nullable Map<String, String> getPackagesMap() {
final var packageConfigFile = getPackageConfigFile();
+ if (packageConfigFile != null) {
return DotPackagesFileUtil.getPackagesMapFromPackageConfigJsonFile(packageConfigFile);
}
final var packagesFile = getPackagesFile();
+ if (packagesFile != null) {
return DotPackagesFileUtil.getPackagesMap(packagesFile);
}
|
codereview_new_java_data_13164
|
public static PubRoot forEventWithRefresh(@NotNull final AnActionEvent event) {
}
}
- //final Project project = event.getData(CommonDataKeys.PROJECT);
- //if (project != null) {
- // final List<PubRoot> roots = PubRoots.forProject(project);
- // if (!roots.isEmpty()) {
- // return roots.get(0);
- // }
- //}
-
return null;
}
Can you add a comment about why this is commented out?
public static PubRoot forEventWithRefresh(@NotNull final AnActionEvent event) {
}
}
return null;
}
|
codereview_new_java_data_13471
|
private void initBloggingSection() {
initBloggingPrompts();
// check if there's still any blogging settings visible, if not remove the whole section
- PreferenceCategory blogging = (PreferenceCategory) findPreference(getString(R.string.pref_key_blogging));
if (blogging.getPreferenceCount() == 0) removeBloggingSection();
}
Nitpick: would it make sense to make if `final`?
private void initBloggingSection() {
initBloggingPrompts();
// check if there's still any blogging settings visible, if not remove the whole section
+ final PreferenceCategory blogging = (PreferenceCategory) findPreference(getString(R.string.pref_key_blogging));
if (blogging.getPreferenceCount() == 0) removeBloggingSection();
}
|
codereview_new_java_data_13474
|
private void initBloggingReminders() {
.getBlogSettingsUiState(mSite.getId())
.observe(getAppCompatActivity(), s -> {
if (mBloggingRemindersPref != null) {
- CharSequence summary = mUiHelpers.getTextOfUiString(getActivity(), s);
mBloggingRemindersPref.setSummary(summary);
}
});
Nitpick: would it make sense to make it `final`?
private void initBloggingReminders() {
.getBlogSettingsUiState(mSite.getId())
.observe(getAppCompatActivity(), s -> {
if (mBloggingRemindersPref != null) {
+ final CharSequence summary = mUiHelpers.getTextOfUiString(getActivity(), s);
mBloggingRemindersPref.setSummary(summary);
}
});
|
codereview_new_java_data_13486
|
public static Intent createMainActivityAndShowBloggingPromptsOnboardingActivityI
}
public static void showBloggingPromptsListActivity(final Activity activity) {
- Intent intent = BloggingPromptsListActivity.createIntent(activity);
activity.startActivity(intent);
}
Nitpick: would it make sense to make it `final`?
public static Intent createMainActivityAndShowBloggingPromptsOnboardingActivityI
}
public static void showBloggingPromptsListActivity(final Activity activity) {
+ final Intent intent = BloggingPromptsListActivity.createIntent(activity);
activity.startActivity(intent);
}
|
codereview_new_java_data_13506
|
public void onClick(View view) {
}
});
- if (getEditPostRepository() != null) hideSpecificViews(getEditPostRepository().isPage());
setupSettingHintsForAccessibility();
applyAccessibilityHeadingToSettings();
Small nitpick:
Maybe we can align this with the common used pattern in this file and add braces for the if statement.
public void onClick(View view) {
}
});
+ if (getEditPostRepository() != null) {
+ hideSpecificViews(getEditPostRepository().isPage());
+ }
setupSettingHintsForAccessibility();
applyAccessibilityHeadingToSettings();
|
codereview_new_java_data_13511
|
public enum UndeletablePrefKey implements PrefKey {
// Indicates if this is the first time we try to get the user flags in Jetpack automatically
IS_FIRST_TRY_USER_FLAGS_JETPACK,
- // Indicates if this is the first time we try to get the user flags in Jetpack automatically
IS_FIRST_TRY_READER_SAVED_POSTS_JETPACK
}
Would it make sense to replace this part of the comment: `"...to get the user flags..."` with `"...to get the reader saved posts..."` or something like that?
public enum UndeletablePrefKey implements PrefKey {
// Indicates if this is the first time we try to get the user flags in Jetpack automatically
IS_FIRST_TRY_USER_FLAGS_JETPACK,
+ // Indicates if this is the first time we try to get the reader saved posts in Jetpack automatically
IS_FIRST_TRY_READER_SAVED_POSTS_JETPACK
}
|
codereview_new_java_data_13515
|
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
-import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver;
import android.widget.TextView;
unused import here
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.TextView;
|
codereview_new_java_data_13516
|
public static void scrollIntoView(Integer scrollableContainerID, ViewInteraction
}
public static void dismissJetpackAdIfPresent() {
- String jpAdText = "Stats, Reader, Notifications, and other features are powered by Jetpack.";
// Dismiss Jetpack ad that might be shown after Sign-Up or after opening Stats
- if (isElementDisplayed(onView(withText(jpAdText)))) {
clickOn(onView(withId(R.id.secondary_button)));
}
nitpick, I think writing it as Jetpack instead of jp makes it easier to read, the word Jetpack is already being used in the function name and comment
```suggestion
String jetpackAdText = "Stats, Reader, Notifications, and other features are powered by Jetpack.";
```
public static void scrollIntoView(Integer scrollableContainerID, ViewInteraction
}
public static void dismissJetpackAdIfPresent() {
+ String jetpackAdText = "Stats, Reader, Notifications, and other features are powered by Jetpack.";
// Dismiss Jetpack ad that might be shown after Sign-Up or after opening Stats
+ if (isElementDisplayed(onView(withText(jetpackAdText)))) {
clickOn(onView(withId(R.id.secondary_button)));
}
|
codereview_new_java_data_13517
|
public static void scrollIntoView(Integer scrollableContainerID, ViewInteraction
}
public static void dismissJetpackAdIfPresent() {
- String jpAdText = "Stats, Reader, Notifications, and other features are powered by Jetpack.";
// Dismiss Jetpack ad that might be shown after Sign-Up or after opening Stats
- if (isElementDisplayed(onView(withText(jpAdText)))) {
clickOn(onView(withId(R.id.secondary_button)));
}
I'm a little wary of adding implicit waits to tests. But I'm not sure if there is a way to add a "wait until not visible" in this framework to check this here. Also when this is not added, do you see the test failing?
If this wait is unavoidable at this time, maybe we can add a comment in the code to explain why it's there.
public static void scrollIntoView(Integer scrollableContainerID, ViewInteraction
}
public static void dismissJetpackAdIfPresent() {
+ String jetpackAdText = "Stats, Reader, Notifications, and other features are powered by Jetpack.";
// Dismiss Jetpack ad that might be shown after Sign-Up or after opening Stats
+ if (isElementDisplayed(onView(withText(jetpackAdText)))) {
clickOn(onView(withId(R.id.secondary_button)));
}
|
codereview_new_java_data_13519
|
public static void populateTextFieldWithin(Integer elementID, String text) {
}
public static void populateTextField(ViewInteraction element, String text) {
- waitForElementToBeDisplayed(element);
clickOn(element);
element.perform(replaceText(text))
.perform(closeSoftKeyboard());
Looks like there is also `waitForElementToBeDisplayed(viewInteraction);` in `clickOn()`. Should we remove the one from line 267 since it's going to be called twice with this change?
public static void populateTextFieldWithin(Integer elementID, String text) {
}
public static void populateTextField(ViewInteraction element, String text) {
clickOn(element);
element.perform(replaceText(text))
.perform(closeSoftKeyboard());
|
codereview_new_java_data_13526
|
public void onMediaUploadRetry(String localMediaId, MediaType mediaType) {
@Override
public void onMediaUploadSucceeded(final String localMediaId, final MediaFile mediaFile) {
mUploadingMediaProgressMax.remove(localMediaId);
- String mediaURL;
- if (!TextUtils.isEmpty(mediaFile.getFileUrlLargeSize())) {
- mediaURL = mediaFile.getFileUrlLargeSize();
- } else if (!TextUtils.isEmpty(mediaFile.getFileUrlMediumSize())) {
- mediaURL = mediaFile.getFileUrlMediumSize();
- } else {
- mediaURL = mediaFile.getFileURL();
- }
-
- getGutenbergContainerFragment().mediaFileUploadSucceeded(Integer.valueOf(localMediaId), mediaURL,
- Integer.valueOf(mediaFile.getMediaId()));
}
@Override
Not sure if linting rules changed, but I'm seeing suggestions in AS to replace `Integer.valueOf` with `Integer.parseInt`.. OTOH, there are other places with the same suggestion that are not part of this PR :man_shrugging: . Please consider this non-blocking - just mentioning it, since I noticed it. :smile:
public void onMediaUploadRetry(String localMediaId, MediaType mediaType) {
@Override
public void onMediaUploadSucceeded(final String localMediaId, final MediaFile mediaFile) {
mUploadingMediaProgressMax.remove(localMediaId);
+ getGutenbergContainerFragment()
+ .mediaFileUploadSucceeded(Integer.parseInt(localMediaId), mediaFile.getOptimalFileURL(),
+ Integer.parseInt(mediaFile.getMediaId()));
}
@Override
|
codereview_new_java_data_13527
|
&& getIntent().getExtras().getBoolean(ARG_CONTINUE_JETPACK_CONNECT, false)) {
onSetPromptReminderClick(getIntent().getIntExtra(ARG_OPEN_BLOGGING_REMINDERS, 0));
}
- int selectedSiteLocalId = mSelectedSiteRepository.getSelectedSiteLocalId(true);
- SiteModel site = selectedSiteLocalId == SelectedSiteRepository.UNAVAILABLE ? null
- : mSiteStore.getSiteByLocalId(selectedSiteLocalId);
if (BuildConfig.IS_JETPACK_APP
&& mStatsRevampV2FeatureConfig.isEnabled()
&& AppPrefs.shouldDisplayStatsRevampFeatureAnnouncement()
- && site != null
- && site.isUsingWpComRestApi()
) {
StatsNewFeaturesIntroDialogFragment.newInstance().show(
getSupportFragmentManager(), StatsNewFeaturesIntroDialogFragment.TAG
What is this required for?
WPMainActivity initializes selected site (initSelectedSite() L:1508)
There's also a method getSelectedSite() (L:1490)
if really required then, we could do like
if (!mSelectedSiteRepository.hasSelectedSite()) {
initSelectedSite();
}
getSelectedSite() != null
&& getIntent().getExtras().getBoolean(ARG_CONTINUE_JETPACK_CONNECT, false)) {
onSetPromptReminderClick(getIntent().getIntExtra(ARG_OPEN_BLOGGING_REMINDERS, 0));
}
+ if (!mSelectedSiteRepository.hasSelectedSite()) {
+ initSelectedSite();
+ }
if (BuildConfig.IS_JETPACK_APP
&& mStatsRevampV2FeatureConfig.isEnabled()
&& AppPrefs.shouldDisplayStatsRevampFeatureAnnouncement()
+ && getSelectedSite() != null
) {
StatsNewFeaturesIntroDialogFragment.newInstance().show(
getSupportFragmentManager(), StatsNewFeaturesIntroDialogFragment.TAG
|
codereview_new_java_data_13528
|
&& getIntent().getExtras().getBoolean(ARG_CONTINUE_JETPACK_CONNECT, false)) {
onSetPromptReminderClick(getIntent().getIntExtra(ARG_OPEN_BLOGGING_REMINDERS, 0));
}
- int selectedSiteLocalId = mSelectedSiteRepository.getSelectedSiteLocalId(true);
- SiteModel site = selectedSiteLocalId == SelectedSiteRepository.UNAVAILABLE ? null
- : mSiteStore.getSiteByLocalId(selectedSiteLocalId);
if (BuildConfig.IS_JETPACK_APP
&& mStatsRevampV2FeatureConfig.isEnabled()
&& AppPrefs.shouldDisplayStatsRevampFeatureAnnouncement()
- && site != null
- && site.isUsingWpComRestApi()
) {
StatsNewFeaturesIntroDialogFragment.newInstance().show(
getSupportFragmentManager(), StatsNewFeaturesIntroDialogFragment.TAG
Since we're already checking IS_JETPACK_APP, isUsingWpComRestApi() check seems redundant here
&& getIntent().getExtras().getBoolean(ARG_CONTINUE_JETPACK_CONNECT, false)) {
onSetPromptReminderClick(getIntent().getIntExtra(ARG_OPEN_BLOGGING_REMINDERS, 0));
}
+ if (!mSelectedSiteRepository.hasSelectedSite()) {
+ initSelectedSite();
+ }
if (BuildConfig.IS_JETPACK_APP
&& mStatsRevampV2FeatureConfig.isEnabled()
&& AppPrefs.shouldDisplayStatsRevampFeatureAnnouncement()
+ && getSelectedSite() != null
) {
StatsNewFeaturesIntroDialogFragment.newInstance().show(
getSupportFragmentManager(), StatsNewFeaturesIntroDialogFragment.TAG
|
codereview_new_java_data_13532
|
public static BitmapDrawable getAztecPlaceholderDrawableFromResID(Context contex
public static int getMaximumThumbnailSizeForEditor(Context context) {
Rect size = DisplayUtils.getWindowSize(context);
- int screenWidth = size.height();
- int screenHeight = size.width();
int maximumThumbnailWidthForEditor = Math.min(screenWidth, screenHeight);
int padding = DisplayUtils.dpToPx(context, 48) * 2;
maximumThumbnailWidthForEditor -= padding;
Can we recheck the assignments: `size.height()` to `screenWidth` and `size.width()` to `screenHeight`?
public static BitmapDrawable getAztecPlaceholderDrawableFromResID(Context contex
public static int getMaximumThumbnailSizeForEditor(Context context) {
Rect size = DisplayUtils.getWindowSize(context);
+ int screenWidth = size.width();
+ int screenHeight = size.height();
int maximumThumbnailWidthForEditor = Math.min(screenWidth, screenHeight);
int padding = DisplayUtils.dpToPx(context, 48) * 2;
maximumThumbnailWidthForEditor -= padding;
|
codereview_new_java_data_13976
|
/**
* The <tt>Conference</tt>s of this <tt>Videobridge</tt> mapped by their local IDs.
*
- * TODO: The only remaining use of this ID is for the colibri WebSocket conference identifier. This should be
- * replaced with meetingId.
*/
private final Map<String, Conference> conferencesById = new HashMap<>();
I believe it's also used for the debug API, where it should also be replaced.
/**
* The <tt>Conference</tt>s of this <tt>Videobridge</tt> mapped by their local IDs.
*
+ * TODO: The only remaining uses of this ID are for the HTTP debug interface and the colibri WebSocket conference
+ * identifier. This should be replaced with meetingId (while making sure jvb-rtcstats-push doesn't break).
*/
private final Map<String, Conference> conferencesById = new HashMap<>();
|
codereview_new_java_data_13977
|
public IQ healthCheckIqReceived(@NotNull HealthCheckIQ iq)
* Number of endpoints whose ICE connection was established, but DTLS
* wasn't (at the time of expiration).
*/
- public CounterMetric dtlsFailedEndpoints = VideobridgeMetricsContainer.getInstance().registerCounter(
- "dtls_failed_endpoints",
"Number of endpoints whose ICE connection was established, but DTLS wasn't (at time of expiration).");
/**
Can you rename this to endpoints_dtls_failed for consistency (we have other endpoints_ metrics, right?)
public IQ healthCheckIqReceived(@NotNull HealthCheckIQ iq)
* Number of endpoints whose ICE connection was established, but DTLS
* wasn't (at the time of expiration).
*/
+ public CounterMetric endpointsDtlsFailed = VideobridgeMetricsContainer.getInstance().registerCounter(
+ "endpoints_dtls_failed",
"Number of endpoints whose ICE connection was established, but DTLS wasn't (at time of expiration).");
/**
|
codereview_new_java_data_13979
|
private void updateStatisticsOnExpire()
if (hasPartiallyFailed)
{
- videobridgeStatistics.totalPartiallyFailedConferences.incAndGet();
}
if (hasFailed)
{
- videobridgeStatistics.totalFailedConferences.incAndGet();
}
if (logger.isInfoEnabled())
Can you also rename the variables please ("total" is not necessary).
private void updateStatisticsOnExpire()
if (hasPartiallyFailed)
{
+ videobridgeStatistics.partiallyFailedConferences.incAndGet();
}
if (hasFailed)
{
+ videobridgeStatistics.failedConferences.incAndGet();
}
if (logger.isInfoEnabled())
|
codereview_new_java_data_13980
|
public boolean hasNonZeroEffectiveConstraints(String endpointId)
*/
void expire()
{
ScheduledFuture<?> updateTask = this.updateTask;
if (updateTask != null)
{
updateTask.cancel(false);
}
- expired = true;
}
/**
I'd put the expired = true before the cancel, I think it handles races better?
public boolean hasNonZeroEffectiveConstraints(String endpointId)
*/
void expire()
{
+ expired = true;
ScheduledFuture<?> updateTask = this.updateTask;
if (updateTask != null)
{
updateTask.cancel(false);
}
}
/**
|
codereview_new_java_data_13981
|
package org.jitsi.videobridge.metrics;
/**
- * Supplies the current value of a metric, cast as an {@code Object}.
* Metrics are held in the {@link MetricsContainer}.
*/
@FunctionalInterface
-public interface Metric
{
/**
- * Supplies the value of a metric.
*
* @return the current value of a metric
*/
- Object getMetricValue();
}
Returning an `Object` is strange. Should this be parametrized instead? e.g. `Metric<T>` and `T getMetricValue()`
package org.jitsi.videobridge.metrics;
/**
+ * Supplies the current value of a metric.
* Metrics are held in the {@link MetricsContainer}.
*/
@FunctionalInterface
+public interface Metric<T>
{
/**
+ * Supplies the current value of a metric.
*
* @return the current value of a metric
*/
+ T get();
}
|
codereview_new_java_data_13985
|
public JvbHealthChecker getJvbHealthChecker()
void localEndpointCreated(boolean visitor)
{
statistics.currentLocalEndpoints.inc();
}
void localEndpointExpired(boolean visitor)
{
long remainingEndpoints = statistics.currentLocalEndpoints.decAndGet();
if (remainingEndpoints < 0)
{
logger.warn("Invalid endpoint count " + remainingEndpoints + ". Disabling endpoint-count based shutdown!");
Did you mean to inc a stat here?
public JvbHealthChecker getJvbHealthChecker()
void localEndpointCreated(boolean visitor)
{
statistics.currentLocalEndpoints.inc();
+ if (visitor)
+ {
+ statistics.currentVisitors.inc();
+ }
}
void localEndpointExpired(boolean visitor)
{
long remainingEndpoints = statistics.currentLocalEndpoints.decAndGet();
+ if (visitor)
+ {
+ statistics.currentVisitors.dec();
+ }
+
if (remainingEndpoints < 0)
{
logger.warn("Invalid endpoint count " + remainingEndpoints + ". Disabling endpoint-count based shutdown!");
|
codereview_new_java_data_13987
|
public void endpointMessageTransportConnected(@NotNull AbstractEndpoint abstract
{
endpoint.sendMessage(new DominantSpeakerMessage(recentSpeakers, speechActivity.isInSilence()));
}
-
- abstractEndpoint.onMessageTransportConnect();
}
}
We already have `Endpoint.endpointMessageTransportConnected`. I don't see you implement this in `Relay`, so I think you can just merge your code into it.
public void endpointMessageTransportConnected(@NotNull AbstractEndpoint abstract
{
endpoint.sendMessage(new DominantSpeakerMessage(recentSpeakers, speechActivity.isInSilence()));
}
}
}
|
codereview_new_java_data_14387
|
import java.util.function.Function;
public class FtpWithProxyStageTest extends BaseFtpSupport implements CommonFtpStageTest {
- // Trigger actually running the tests
@Rule public final LogCapturingJunit4 logCapturing = new LogCapturingJunit4();
private final Integer PROXYPORT = 3128;
```suggestion
```
import java.util.function.Function;
public class FtpWithProxyStageTest extends BaseFtpSupport implements CommonFtpStageTest {
@Rule public final LogCapturingJunit4 logCapturing = new LogCapturingJunit4();
private final Integer PROXYPORT = 3128;
|
codereview_new_java_data_14773
|
private SelectResponse process(RegionTask regionTask) {
.getRegionStoreClientBuilder()
.build(region, store, storeType);
client.addResolvedLocks(startTs, resolvedLocks);
- // client.setTimeout(clientSession.getConf().getTimeout(),);
Collection<RegionTask> tasks =
client.coprocess(backOffer, dagRequest, ranges, responseQueue, startTs);
if (tasks != null) {
it seems no use here.
private SelectResponse process(RegionTask regionTask) {
.getRegionStoreClientBuilder()
.build(region, store, storeType);
client.addResolvedLocks(startTs, resolvedLocks);
Collection<RegionTask> tasks =
client.coprocess(backOffer, dagRequest, ranges, responseQueue, startTs);
if (tasks != null) {
|
codereview_new_java_data_14774
|
private static String wrapColumnName(String columnName) {
/**
* Spark SQL will parse string literal without escape, So we need to parse partition definition
- * without escape too. wrapValue will replace the first '' to "", so that antlr will not regard
- * the first '' as a part of string literal. wrapValue will also delete the escape character in
- * string literal. e.g. 'string' -> "string" '''string''' -> "'string'" 'string''' -> "string'"
- * Can't handle '""'. e.g. '"string"' -> ""string"". parseExpression will parse ""string"" to
* empty string, parse '"string"' to 'string'
*
* @param value
`'string''' -> "string'"` looks strange
private static String wrapColumnName(String columnName) {
/**
* Spark SQL will parse string literal without escape, So we need to parse partition definition
+ * without escape too.
+ *
+ * <p>wrapValue will replace the first '' to "", so that antlr will not regard the first '' as a
+ * part of string literal.
+ *
+ * <p>wrapValue will also delete the escape character in string literal.
+ *
+ * <p>e.g. 'string' -> "string" '''string''' -> "'string'" 'string''' -> "string'"
+ *
+ * <p>Can't handle '""'. e.g. '"string"' -> ""string"". parseExpression will parse ""string"" to
* empty string, parse '"string"' to 'string'
*
* @param value
|
codereview_new_java_data_14776
|
private Iterator<SelectResponse> processByStreaming(RangeSplitter.RegionTask reg
}
}
public Boolean isMppStoreAlive(long id, RegionStoreClient client) {
try {
Boolean isStoreAlive = storeStatusCache.get(id);
comment to add link to this PR. I think the PR description is valuable.
private Iterator<SelectResponse> processByStreaming(RangeSplitter.RegionTask reg
}
}
+ // See https://github.com/pingcap/tispark/pull/2619 for more details
public Boolean isMppStoreAlive(long id, RegionStoreClient client) {
try {
Boolean isStoreAlive = storeStatusCache.get(id);
|
codereview_new_java_data_14780
|
public TiDAGRequest buildTiDAGReq(
TiKVScanPlan plan =
buildIndexScan(columnList, conditions, index, table, tableStatistics, false);
if (plan.getCost() < minIndexCost) {
- minIndexPlan = plan;
minIndexCost = plan.getCost();
}
}
```suggestion
minCostIndexPlan = plan;
```
public TiDAGRequest buildTiDAGReq(
TiKVScanPlan plan =
buildIndexScan(columnList, conditions, index, table, tableStatistics, false);
if (plan.getCost() < minIndexCost) {
+ minCostIndexPlan = plan;
minIndexCost = plan.getCost();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.