id stringlengths 29 30 | content stringlengths 152 2.6k |
|---|---|
codereview_new_java_data_8544 | public AbstractCoordinator(GroupRebalanceConfig rebalanceConfig,
/**
* Invoked prior to each group join or rejoin. This is typically used to perform any
* cleanup from the previous generation (such as committing offsets for the consumer)
* @param generation The previous generation or -1 if there was none
* @param memberId The identifier of this member in the previous group or "" if there was none
* @return true If onJoinPrepare async commit succeeded, false otherwise
We should also add param `timer` into javadoc above
public AbstractCoordinator(GroupRebalanceConfig rebalanceConfig,
/**
* Invoked prior to each group join or rejoin. This is typically used to perform any
* cleanup from the previous generation (such as committing offsets for the consumer)
+ * @param timer Timer bounding how long this method can block
* @param generation The previous generation or -1 if there was none
* @param memberId The identifier of this member in the previous group or "" if there was none
* @return true If onJoinPrepare async commit succeeded, false otherwise |
codereview_new_java_data_8546 | public void start() {
stateUpdaterThread = new StateUpdaterThread("state-updater", changelogReader, offsetResetter);
stateUpdaterThread.start();
shutdownGate = new CountDownLatch(1);
}
- // initialize the last commit as of now to prevent first commit happens immediately
- this.lastCommitMs = time.milliseconds();
}
@Override
Shouldn't this go inside the `if`-branch? Otherwise it would be possible to change the last committed time of already started state updaters.
public void start() {
stateUpdaterThread = new StateUpdaterThread("state-updater", changelogReader, offsetResetter);
stateUpdaterThread.start();
shutdownGate = new CountDownLatch(1);
+
+ // initialize the last commit as of now to prevent first commit happens immediately
+ this.lastCommitMs = time.milliseconds();
}
}
@Override |
codereview_new_java_data_8548 | public class ListConsumerGroupOffsetsResult {
final KafkaFuture<Map<TopicPartition, OffsetAndMetadata>> future;
- public ListConsumerGroupOffsetsResult(KafkaFuture<Map<TopicPartition, OffsetAndMetadata>> future) {
this.future = future;
}
We need to push this public in order to be used in admin client callers.
public class ListConsumerGroupOffsetsResult {
final KafkaFuture<Map<TopicPartition, OffsetAndMetadata>> future;
+ ListConsumerGroupOffsetsResult(KafkaFuture<Map<TopicPartition, OffsetAndMetadata>> future) {
this.future = future;
}
|
codereview_new_java_data_8549 | public class ListConsumerGroupOffsetsHandler extends AdminApiHandler.Batched<Coo
private final AdminApiLookupStrategy<CoordinatorKey> lookupStrategy;
public ListConsumerGroupOffsetsHandler(
- String groupId,
- List<TopicPartition> partitions,
- LogContext logContext
) {
this(groupId, partitions, false, logContext);
}
nit: Indentation seems to be off in comparison to the other constructor/methods.
public class ListConsumerGroupOffsetsHandler extends AdminApiHandler.Batched<Coo
private final AdminApiLookupStrategy<CoordinatorKey> lookupStrategy;
public ListConsumerGroupOffsetsHandler(
+ String groupId,
+ List<TopicPartition> partitions,
+ LogContext logContext
) {
this(groupId, partitions, false, logContext);
} |
codereview_new_java_data_8550 | public ListConsumerGroupOffsetsResult listConsumerGroupOffsets(final String grou
final ListConsumerGroupOffsetsOptions options) {
SimpleAdminApiFuture<CoordinatorKey, Map<TopicPartition, OffsetAndMetadata>> future =
ListConsumerGroupOffsetsHandler.newFuture(groupId);
- ListConsumerGroupOffsetsHandler handler = new ListConsumerGroupOffsetsHandler(groupId, options.topicPartitions(), options.shouldRequireStable(), logContext);
invokeDriver(handler, future, options.timeoutMs);
return new ListConsumerGroupOffsetsResult(future.get(CoordinatorKey.byGroupId(groupId)));
}
Do you need to adapt/add a unit test for this change?
public ListConsumerGroupOffsetsResult listConsumerGroupOffsets(final String grou
final ListConsumerGroupOffsetsOptions options) {
SimpleAdminApiFuture<CoordinatorKey, Map<TopicPartition, OffsetAndMetadata>> future =
ListConsumerGroupOffsetsHandler.newFuture(groupId);
+ ListConsumerGroupOffsetsHandler handler = new ListConsumerGroupOffsetsHandler(groupId, options.topicPartitions(), options.requireStable(), logContext);
invokeDriver(handler, future, options.timeoutMs);
return new ListConsumerGroupOffsetsResult(future.get(CoordinatorKey.byGroupId(groupId)));
} |
codereview_new_java_data_8553 | protected AbstractWorkerSourceTask(ConnectorTaskId id,
this.admin = admin;
this.offsetReader = offsetReader;
this.offsetWriter = offsetWriter;
- this.offsetStore = offsetStore;
this.closeExecutor = closeExecutor;
this.sourceTaskContext = sourceTaskContext;
this.stopRequestedLatch = new CountDownLatch(1);
this.sourceTaskMetricsGroup = new SourceTaskMetricsGroup(id, connectMetrics);
this.topicTrackingEnabled = workerConfig.getBoolean(TOPIC_TRACKING_ENABLE_CONFIG);
this.topicCreation = TopicCreation.newTopicCreation(workerConfig, topicGroups);
- Objects.requireNonNull(this.offsetStore);
}
@Override
Two nits:
1. We should probably add a message just in case something changes later and this ends up breaking in prod; something like "offset store cannot be null for source tasks" should be fine
2. We don't even have to give this its own line; we can just tweak the line above from `this.offsetStore = offsetStore;` to `this.offsetStore = Objects.requireNonNull(offsetStore, "some message");`
protected AbstractWorkerSourceTask(ConnectorTaskId id,
this.admin = admin;
this.offsetReader = offsetReader;
this.offsetWriter = offsetWriter;
+ this.offsetStore = Objects.requireNonNull(offsetStore, "offset store cannot be null for source tasks");
this.closeExecutor = closeExecutor;
this.sourceTaskContext = sourceTaskContext;
this.stopRequestedLatch = new CountDownLatch(1);
this.sourceTaskMetricsGroup = new SourceTaskMetricsGroup(id, connectMetrics);
this.topicTrackingEnabled = workerConfig.getBoolean(TOPIC_TRACKING_ENABLE_CONFIG);
this.topicCreation = TopicCreation.newTopicCreation(workerConfig, topicGroups);
}
@Override |
codereview_new_java_data_8554 | public void configure(Map<String, ?> configs, boolean isKey) {
@Override
public void close() {
- this.serializer.close();
- this.deserializer.close();
}
@Override
```suggestion
Utils.closeQuietly(this.serializer, "JSON converter serializer");
Utils.closeQuietly(this.deserializer, "JSON converter deserializer");
```
public void configure(Map<String, ?> configs, boolean isKey) {
@Override
public void close() {
+ Utils.closeQuietly(this.serializer, "JSON converter serializer");
+ Utils.closeQuietly(this.deserializer, "JSON converter deserializer");
}
@Override |
codereview_new_java_data_8555 | public SchemaAndValue toConnectHeader(String topic, String headerKey, byte[] val
@Override
public void close() {
- Utils.closeQuietly(this.serializer, "number format serializer");
- Utils.closeQuietly(this.deserializer, "number format deserializer");
}
}
What is `format`? Would `number converter serializer` or even just `number serializer` make more sense here?
public SchemaAndValue toConnectHeader(String topic, String headerKey, byte[] val
@Override
public void close() {
+ Utils.closeQuietly(this.serializer, "number converter serializer");
+ Utils.closeQuietly(this.deserializer, "number converter deserializer");
}
} |
codereview_new_java_data_8556 | boolean joinGroupIfNeeded(final Timer timer) {
resetJoinGroupFuture();
synchronized (AbstractCoordinator.this) {
final String shortReason = String.format("rebalance failed due to an exception: (%s)",
- exception.getMessage(),
exception.getClass().getSimpleName());
final String fullReason = String.format("rebalance failed due to '%s' (%s)",
exception.getMessage(),
@jnh5y If I understand correctly, you are saying that `exception.getMessage()` contained the stack trace. Am I right? I wonder why. Usually, the message is not suppose to contain it, no? It is a bit annoying because we are losing information without the message here.
nit: You pass two arguments but have only one `%s` in the pattern.
boolean joinGroupIfNeeded(final Timer timer) {
resetJoinGroupFuture();
synchronized (AbstractCoordinator.this) {
final String shortReason = String.format("rebalance failed due to an exception: (%s)",
exception.getClass().getSimpleName());
final String fullReason = String.format("rebalance failed due to '%s' (%s)",
exception.getMessage(), |
codereview_new_java_data_8557 | boolean joinGroupIfNeeded(final Timer timer) {
resetJoinGroupFuture();
synchronized (AbstractCoordinator.this) {
- final String shortReason = String.format("rebalance failed due to an exception: (%s)",
exception.getClass().getSimpleName());
final String fullReason = String.format("rebalance failed due to '%s' (%s)",
exception.getMessage(),
nit: How about `rebalance failed due to %s`? `an exception` is redundant in my opinion.
boolean joinGroupIfNeeded(final Timer timer) {
resetJoinGroupFuture();
synchronized (AbstractCoordinator.this) {
+ final String shortReason = String.format("rebalance failed due to %s",
exception.getClass().getSimpleName());
final String fullReason = String.format("rebalance failed due to '%s' (%s)",
exception.getMessage(), |
codereview_new_java_data_8562 | public void shouldQuerySpecificActivePartitionStores() throws Exception {
assertThat(store1.get(key), is(notNullValue()));
assertThat(getStore(kafkaStreams2, storeQueryParam2).get(key), is(nullValue()));
final InvalidStateStoreException exception =
- assertThrows(InvalidStateStoreException.class, () -> getStore(kafkaStreams1, storeQueryParam2).get(key));
assertThat(
exception.getMessage(),
containsString("The specified partition 1 for store source-table does not exist.")
nit
```suggestion
assertThrows(InvalidStateStoreException.class, () -> getStore(kafkaStreams1, storeQueryParam2).get(key));
```
public void shouldQuerySpecificActivePartitionStores() throws Exception {
assertThat(store1.get(key), is(notNullValue()));
assertThat(getStore(kafkaStreams2, storeQueryParam2).get(key), is(nullValue()));
final InvalidStateStoreException exception =
+ assertThrows(InvalidStateStoreException.class, () -> getStore(kafkaStreams1, storeQueryParam2).get(key));
assertThat(
exception.getMessage(),
containsString("The specified partition 1 for store source-table does not exist.") |
codereview_new_java_data_8563 | public void shouldQuerySpecificActivePartitionStores() throws Exception {
assertThat(store1.get(key), is(notNullValue()));
assertThat(getStore(kafkaStreams2, storeQueryParam2).get(key), is(nullValue()));
final InvalidStateStoreException exception =
- assertThrows(InvalidStateStoreException.class, () -> getStore(kafkaStreams1, storeQueryParam2).get(key));
assertThat(
exception.getMessage(),
containsString("The specified partition 1 for store source-table does not exist.")
nit:
```suggestion
exception.getMessage(),
containsString("The specified partition 1 for store source-table does not exist.")
```
public void shouldQuerySpecificActivePartitionStores() throws Exception {
assertThat(store1.get(key), is(notNullValue()));
assertThat(getStore(kafkaStreams2, storeQueryParam2).get(key), is(nullValue()));
final InvalidStateStoreException exception =
+ assertThrows(InvalidStateStoreException.class, () -> getStore(kafkaStreams1, storeQueryParam2).get(key));
assertThat(
exception.getMessage(),
containsString("The specified partition 1 for store source-table does not exist.") |
codereview_new_java_data_8564 | public static String safeUniqueTestName(final Class<?> testClass, final TestName
.replace('=', '_');
}
- public static String safeUniqueClassTestName(final Class<?> testClass) {
- return (testClass.getSimpleName())
- .replace(':', '_')
- .replace('.', '_')
- .replace('[', '_')
- .replace(']', '_')
- .replace(' ', '_')
- .replace('=', '_');
- }
-
/**
* Removes local state stores. Useful to reset state in-between integration test runs.
*
This should be dead code now that we do not need this method in `DefaultStateUpdater`. Could you please remove it?
public static String safeUniqueTestName(final Class<?> testClass, final TestName
.replace('=', '_');
}
/**
* Removes local state stores. Useful to reset state in-between integration test runs.
* |
codereview_new_java_data_8565 |
CompletableFuture<Long> await(T threshold, long maxWaitTimeMs);
/**
- * Complete awaiting futures whose associated values are smaller than the given threshold value.
- * The completion callbacks will be triggered from the calling thread.
*
* @param value the threshold value used to determine which futures can be completed
* @param currentTimeMs the current time in milliseconds that will be passed to
Thanks for this fix. I think the phrase "associated values" is still misleading. How about:
> Complete awaiting futures whose threshold value from {@link await} is smaller than the given threshold value.
CompletableFuture<Long> await(T threshold, long maxWaitTimeMs);
/**
+ * Complete awaiting futures whose threshold value from {@link FuturePurgatory#await} are smaller
+ * than the given threshold value. The completion callbacks will be triggered from the calling thread.
*
* @param value the threshold value used to determine which futures can be completed
* @param currentTimeMs the current time in milliseconds that will be passed to |
codereview_new_java_data_8576 | public void testCommitAsyncWithUserAssignedType() {
// should try to find coordinator since we are commit async
coordinator.commitOffsetsAsync(singletonMap(t1p, new OffsetAndMetadata(100L)), (offsets, exception) -> {
- throw new AssertionError("Commit should not get responses");
});
coordinator.poll(time.timer(0));
assertTrue(coordinator.coordinatorUnknown());
nit: use `fail` instead, and we might need to log the callback parameters for troubleshooting.
```
fail("Commit should not get responses, but got offsets:" + offsets +", and exception:" + exception)
```
public void testCommitAsyncWithUserAssignedType() {
// should try to find coordinator since we are commit async
coordinator.commitOffsetsAsync(singletonMap(t1p, new OffsetAndMetadata(100L)), (offsets, exception) -> {
+ fail("Commit should not get responses, but got offsets:" + offsets +", and exception:" + exception);
});
coordinator.poll(time.timer(0));
assertTrue(coordinator.coordinatorUnknown()); |
codereview_new_java_data_8577 | void handleBrokerUnfenced(int brokerId, long brokerEpoch, List<ApiMessageAndVers
* @param records The record list to append to.
*/
void handleBrokerInControlledShutdown(int brokerId, long brokerEpoch, List<ApiMessageAndVersion> records) {
- if (featureControl.metadataVersion().isInControlledShutdownStateSupported()) {
records.add(new ApiMessageAndVersion(new BrokerRegistrationChangeRecord().
setBrokerId(brokerId).setBrokerEpoch(brokerEpoch).
setInControlledShutdown(BrokerRegistrationInControlledShutdownChange.IN_CONTROLLED_SHUTDOWN.value()),
Is it possible for the broker to send multiple heartbeats with a shutdown request? Do we want to handle that case and avoid writing another record?
Looking at the implementation for `generateLeaderAndIsrUpdates`, it looks like it already avoids generating multiple partition change records since the broker was removed from the ISR.
void handleBrokerUnfenced(int brokerId, long brokerEpoch, List<ApiMessageAndVers
* @param records The record list to append to.
*/
void handleBrokerInControlledShutdown(int brokerId, long brokerEpoch, List<ApiMessageAndVersion> records) {
+ if (featureControl.metadataVersion().isInControlledShutdownStateSupported()
+ && !clusterControl.inControlledShutdown(brokerId)) {
records.add(new ApiMessageAndVersion(new BrokerRegistrationChangeRecord().
setBrokerId(brokerId).setBrokerEpoch(brokerEpoch).
setInControlledShutdown(BrokerRegistrationInControlledShutdownChange.IN_CONTROLLED_SHUTDOWN.value()), |
codereview_new_java_data_8578 |
import java.util.stream.Collectors;
public enum BrokerRegistrationInControlledShutdownChange {
NONE(0, Optional.empty()),
IN_CONTROLLED_SHUTDOWN(1, Optional.of(true));
What do you think about document why `Optional.of(false)` is not a valid change?
import java.util.stream.Collectors;
public enum BrokerRegistrationInControlledShutdownChange {
+ // Note that Optional.of(true) is not a valid state change here. The only
+ // way to leave the in controlled shutdown state is by registering the
+ // broker with a new incarnation id.
NONE(0, Optional.empty()),
IN_CONTROLLED_SHUTDOWN(1, Optional.of(true));
|
codereview_new_java_data_8579 |
private final Processor<KIn, VIn, KOut, VOut> processor;
private final FixedKeyProcessor<KIn, VIn, VOut> fixedKeyProcessor;
private final String name;
- protected final Time time;
public final Set<String> stateStores;
- protected InternalProcessorContext<KOut, VOut> internalProcessorContext;
- protected String threadId;
private boolean closed = true;
I do not think you need to do this. You can simply use the context that is passed in into the `init()` method of `SinkNode`.
private final Processor<KIn, VIn, KOut, VOut> processor;
private final FixedKeyProcessor<KIn, VIn, VOut> fixedKeyProcessor;
private final String name;
+ private final Time time;
public final Set<String> stateStores;
+ private InternalProcessorContext<KOut, VOut> internalProcessorContext;
+ private String threadId;
private boolean closed = true;
|
codereview_new_java_data_8580 |
private final Processor<KIn, VIn, KOut, VOut> processor;
private final FixedKeyProcessor<KIn, VIn, VOut> fixedKeyProcessor;
private final String name;
- protected final Time time;
public final Set<String> stateStores;
- protected InternalProcessorContext<KOut, VOut> internalProcessorContext;
- protected String threadId;
private boolean closed = true;
Is this really needed? Could not find where is is used outside `ProcessorNode`.
private final Processor<KIn, VIn, KOut, VOut> processor;
private final FixedKeyProcessor<KIn, VIn, VOut> fixedKeyProcessor;
private final String name;
+ private final Time time;
public final Set<String> stateStores;
+ private InternalProcessorContext<KOut, VOut> internalProcessorContext;
+ private String threadId;
private boolean closed = true;
|
codereview_new_java_data_8581 |
private final Processor<KIn, VIn, KOut, VOut> processor;
private final FixedKeyProcessor<KIn, VIn, VOut> fixedKeyProcessor;
private final String name;
- protected final Time time;
public final Set<String> stateStores;
- protected InternalProcessorContext<KOut, VOut> internalProcessorContext;
- protected String threadId;
private boolean closed = true;
Also this does not seem to be strictly needed since in `SinkNode` you could use `Thread.currentThread().getName()` as in `init()` of `SourceNode`. I even think you need to use `Thread.currentThread().getName()` in `SinkNode` since you use `threadId` before the variable is set in `super.init()`.
private final Processor<KIn, VIn, KOut, VOut> processor;
private final FixedKeyProcessor<KIn, VIn, VOut> fixedKeyProcessor;
private final String name;
+ private final Time time;
public final Set<String> stateStores;
+ private InternalProcessorContext<KOut, VOut> internalProcessorContext;
+ private String threadId;
private boolean closed = true;
|
codereview_new_java_data_8756 | private static com.google.datastore.v1.Key getKey(Mutation m) {
} else if (m.hasUpdate()) {
return m.getUpdate().getKey();
} else {
- throw new IllegalArgumentException(String.format("Mutation %s is not valid.", m));
}
}
Are these 4 cases exhaustive? I also see `OPERATION_NOT_SET` in Mutation's source code. Maybe just add a warning and return an empty Key? Otherwise LGTM.
private static com.google.datastore.v1.Key getKey(Mutation m) {
} else if (m.hasUpdate()) {
return m.getUpdate().getKey();
} else {
+ LOG.warning("Mutation %s does not have an operation type set.", m);
+ return "";
}
}
|
codereview_new_java_data_8757 | private static com.google.datastore.v1.Key getKey(Mutation m) {
return m.getUpdate().getKey();
} else {
LOG.warning("Mutation %s does not have an operation type set.", m);
- return "";
}
}
ah need to return a Key.getDefaultInstance()
private static com.google.datastore.v1.Key getKey(Mutation m) {
return m.getUpdate().getKey();
} else {
LOG.warning("Mutation %s does not have an operation type set.", m);
+ return Entity.getDefaultInstance().getKey();
}
}
|
codereview_new_java_data_8758 | private static com.google.datastore.v1.Key getKey(Mutation m) {
} else if (m.hasUpdate()) {
return m.getUpdate().getKey();
} else {
- LOG.warning("Mutation %s does not have an operation type set.", m);
return Entity.getDefaultInstance().getKey();
}
}
```suggestion
LOG.warn("Mutation {} does not have an operation type set.", m);
```
private static com.google.datastore.v1.Key getKey(Mutation m) {
} else if (m.hasUpdate()) {
return m.getUpdate().getKey();
} else {
+ LOG.warn("Mutation {} does not have an operation type set.", m);
return Entity.getDefaultInstance().getKey();
}
} |
codereview_new_java_data_8759 | public static Set<String> getJavaCapabilities() {
capabilities.add("beam:version:sdk_base:" + JAVA_SDK_HARNESS_CONTAINER_URL);
capabilities.add(BeamUrns.getUrn(SplittableParDoComponents.TRUNCATE_SIZED_RESTRICTION));
capabilities.add(BeamUrns.getUrn(Primitives.TO_STRING));
- capabilities.add(BeamUrns.getUrn(RunnerApi.StandardProtocols.Enum.DATA_SAMPLING));
return capabilities.build();
}
```suggestion
capabilities.add(BeamUrns.getUrn(StandardProtocols.Enum.DATA_SAMPLING));
```
public static Set<String> getJavaCapabilities() {
capabilities.add("beam:version:sdk_base:" + JAVA_SDK_HARNESS_CONTAINER_URL);
capabilities.add(BeamUrns.getUrn(SplittableParDoComponents.TRUNCATE_SIZED_RESTRICTION));
capabilities.add(BeamUrns.getUrn(Primitives.TO_STRING));
+ capabilities.add(BeamUrns.getUrn(StandardProtocols.Enum.DATA_SAMPLING));
return capabilities.build();
}
|
codereview_new_java_data_8760 | public void accept(WindowedValue<T> input) throws Exception {
// Use the ExecutionStateTracker and enter an appropriate state to track the
// Process Bundle Execution time metric and also ensure user counters can get an appropriate
- // metrics container.
for (int size = consumerAndMetadatas.size(), i = 0; i < size; ++i) {
ConsumerAndMetadata consumerAndMetadata = consumerAndMetadatas.get(i);
ExecutionState state = consumerAndMetadata.getExecutionState();
You may want to add comment here to avoid using `for (ConsumerAndMetadata consumerAndMetadata : consumerAndMetadatas)`
public void accept(WindowedValue<T> input) throws Exception {
// Use the ExecutionStateTracker and enter an appropriate state to track the
// Process Bundle Execution time metric and also ensure user counters can get an appropriate
+ // metrics container. We specifically don't use a for-each loop since it creates an iterator
+ // on a hot path.
for (int size = consumerAndMetadatas.size(), i = 0; i < size; ++i) {
ConsumerAndMetadata consumerAndMetadata = consumerAndMetadatas.get(i);
ExecutionState state = consumerAndMetadata.getExecutionState(); |
codereview_new_java_data_8764 | static String createJobIdWithDestination(
public enum JobType {
LOAD,
TEMP_TABLE_LOAD,
- ZERO_LOAD,
COPY,
EXPORT,
QUERY,
}
/**
SCHEMA_UPDATE is more informative? wdyt
static String createJobIdWithDestination(
public enum JobType {
LOAD,
TEMP_TABLE_LOAD,
COPY,
EXPORT,
QUERY,
+ SCHEMA_UPDATE,
}
/** |
codereview_new_java_data_8769 | public class ProcessBundleHandler {
@VisibleForTesting final BundleProcessorCache bundleProcessorCache;
private final Set<String> runnerCapabilities;
- private DataSampler dataSampler;
public ProcessBundleHandler(
PipelineOptions options,
```suggestion
private final DataSampler dataSampler;
```
public class ProcessBundleHandler {
@VisibleForTesting final BundleProcessorCache bundleProcessorCache;
private final Set<String> runnerCapabilities;
+ private final DataSampler dataSampler;
public ProcessBundleHandler(
PipelineOptions options, |
codereview_new_java_data_8770 |
*/
public class OutputSampler<T> {
private final Coder<T> coder;
- private final List<T> buffer = new ArrayList<>();
private static final Logger LOG = LoggerFactory.getLogger(OutputSampler.class);
// Maximum number of elements in buffer.
setup the capacity of the buffer so we don't pay and resizing costs
```suggestion
private final List<T> buffer = new ArrayList<>(maxElements);
```
*/
public class OutputSampler<T> {
private final Coder<T> coder;
+ private final List<T> buffer = new ArrayList<>(maxElements);
private static final Logger LOG = LoggerFactory.getLogger(OutputSampler.class);
// Maximum number of elements in buffer. |
codereview_new_java_data_8771 | public static void main(
FinalizeBundleHandler finalizeBundleHandler = new FinalizeBundleHandler(executorService);
// Create the sampler, if the experiment is enabled.
- Optional<List<String>> experimentList =
- Optional.ofNullable(options.as(ExperimentalOptions.class).getExperiments());
- boolean shouldSample =
- experimentList.isPresent()
- && experimentList.get().contains(ENABLE_DATA_SAMPLING_EXPERIMENT);
// Retrieves the ProcessBundleDescriptor from cache. Requests the PBD from the Runner if it
// doesn't exist. Additionally, runs any graph modifications.
```suggestion
boolean shouldSample = ExperimentalOptions.hasExperiment(options, ENABLE_DATA_SAMPLING_EXPERIMENT);
```
public static void main(
FinalizeBundleHandler finalizeBundleHandler = new FinalizeBundleHandler(executorService);
// Create the sampler, if the experiment is enabled.
+ boolean shouldSample = ExperimentalOptions.hasExperiment(options, ENABLE_DATA_SAMPLING_EXPERIMENT);
// Retrieves the ProcessBundleDescriptor from cache. Requests the PBD from the Runner if it
// doesn't exist. Additionally, runs any graph modifications. |
codereview_new_java_data_8772 | public DataSampler() {
* @param sampleEveryN Sets how often to sample.
*/
public DataSampler(int maxSamples, int sampleEveryN) {
- this.maxSamples = maxSamples <= 0 ? 10 : maxSamples;
- this.sampleEveryN = sampleEveryN <= 0 ? 1000 : sampleEveryN;
}
// Maximum number of elements in buffer.
Its usually better to throw an IllegalArgumentException in these cases instead of silently having a different behavior then before.
```suggestion
checkArgument(maxSamples > 0, "Expected positive number of samples, did you mean to disable data sampling?");
checkArgument(sampleEveryN > 0, "Expected positive number for sampling period, did you mean to disable data sampling?");
this.maxSamples = maxSamples;
this.sampleEveryN = sampleEveryN;
```
public DataSampler() {
* @param sampleEveryN Sets how often to sample.
*/
public DataSampler(int maxSamples, int sampleEveryN) {
+ checkArgument(maxSamples > 0, "Expected positive number of samples, did you mean to disable data sampling?");
+ checkArgument(sampleEveryN > 0, "Expected positive number for sampling period, did you mean to disable data sampling?");
+ this.maxSamples = maxSamples;
+ this.sampleEveryN = sampleEveryN;
}
// Maximum number of elements in buffer. |
codereview_new_java_data_8872 | 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)
These blocks should be dedented one level
```suggestion
{
@Override
public String getName(final ItemManager itemManager)
{
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_8873 |
public static final int LION_GUARD = 44584;
public static final int WARP = 44585;
public static final int WARP_44586 = 44586;
- public static final int RUBBLE_44595 = 44595;
public static final int LAVA_POOL = 44601;
public static final int WATERFALL_44602 = 44602;
public static final int PREFORM_STORAGE = 44604;
You should never modify ObjectID; per the comment at the top of the file, it is automatically generated. Reference `NullObjectID.NULL_44595` instead.
public static final int LION_GUARD = 44584;
public static final int WARP = 44585;
public static final int WARP_44586 = 44586;
public static final int LAVA_POOL = 44601;
public static final int WATERFALL_44602 = 44602;
public static final int PREFORM_STORAGE = 44604; |
codereview_new_java_data_8874 |
NECTAR(Type.POTION, "Nectar", "N", ItemID.NECTAR_4, ItemID.NECTAR_3, ItemID.NECTAR_2, ItemID.NECTAR_1),
AMBROSIA(Type.POTION, "Ambros", "A", ItemID.AMBROSIA_2, ItemID.AMBROSIA_1),
LIQUID_ADRENALINE(Type.POTION, "L.Adrn", "L.A", ItemID.LIQUID_ADRENALINE_2, ItemID.LIQUID_ADRENALINE_1),
- TEARS_OF_ELIDINIS(Type.POTION, "TearsOE", "ToE", ItemID.TEARS_OF_ELIDINIS_4, ItemID.TEARS_OF_ELIDINIS_3, ItemID.TEARS_OF_ELIDINIS_2, ItemID.TEARS_OF_ELIDINIS_1),
// Unfinished Potions
GUAM_POTION(Type.POTION, "Guam", "G", ItemID.GUAM_POTION_UNF),
```suggestion
TEARS_OF_ELIDINIS(Type.POTION, "Tears", "ToE", ItemID.TEARS_OF_ELIDINIS_4, ItemID.TEARS_OF_ELIDINIS_3, ItemID.TEARS_OF_ELIDINIS_2, ItemID.TEARS_OF_ELIDINIS_1),
```
NECTAR(Type.POTION, "Nectar", "N", ItemID.NECTAR_4, ItemID.NECTAR_3, ItemID.NECTAR_2, ItemID.NECTAR_1),
AMBROSIA(Type.POTION, "Ambros", "A", ItemID.AMBROSIA_2, ItemID.AMBROSIA_1),
LIQUID_ADRENALINE(Type.POTION, "L.Adrn", "L.A", ItemID.LIQUID_ADRENALINE_2, ItemID.LIQUID_ADRENALINE_1),
+ TEARS_OF_ELIDINIS(Type.POTION, "Tears", "ToE", ItemID.TEARS_OF_ELIDINIS_4, ItemID.TEARS_OF_ELIDINIS_3, ItemID.TEARS_OF_ELIDINIS_2, ItemID.TEARS_OF_ELIDINIS_1),
// Unfinished Potions
GUAM_POTION(Type.POTION, "Guam", "G", ItemID.GUAM_POTION_UNF), |
codereview_new_java_data_8875 |
package io.cdap.cdap.sourcecontrol.operationrunner;
/**
- * Exception thrown when push operation fails in operation runner. Encapsulates all underlying exceptions.
*/
-public class PullFailureException extends Exception {
- public PullFailureException(String message, Exception cause) {
- super(message, cause);
}
}
Not sure why github thinks PullFailureException was changed
package io.cdap.cdap.sourcecontrol.operationrunner;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
/**
+ * Response class encapsulating information about a list of applications found in repository
*/
+public class RepositoryAppsResponse {
+ private final List<RepositoryApp> apps;
+
+ public RepositoryAppsResponse(List<RepositoryApp> apps) {
+ this.apps = Collections.unmodifiableList(new ArrayList<>(apps));
+ }
+
+ public List<RepositoryApp> getApps() {
+ return apps;
}
} |
codereview_new_java_data_8876 | public void run(RunnableTaskContext context) throws Exception {
ProgramRunDispatcherContext dispatcherContext = new ProgramRunDispatcherContext(
GSON.fromJson(context.getParam(), ProgramRunDispatcherContext.class));
context.setCleanupTask(dispatcherContext::executeCleanupTasks);
ProgramRunDispatcher dispatcher = injector.getInstance(InMemoryProgramRunDispatcher.class);
- ProgramController programController = dispatcher.dispatchProgram(dispatcherContext);
if (programController == null) {
- ProgramRunId programRunId =
- dispatcherContext.getProgramDescriptor().getProgramId().run(dispatcherContext.getRunId());
throw new IllegalStateException("Failed to dispatch program run " + programRunId);
}
// Result doesn't matter since we just need to return with 200 status or throw an exception
nit: change to `Failed to dispatch program run`
public void run(RunnableTaskContext context) throws Exception {
ProgramRunDispatcherContext dispatcherContext = new ProgramRunDispatcherContext(
GSON.fromJson(context.getParam(), ProgramRunDispatcherContext.class));
context.setCleanupTask(dispatcherContext::executeCleanupTasks);
+ ProgramRunId programRunId =
+ dispatcherContext.getProgramDescriptor().getProgramId().run(dispatcherContext.getRunId());
ProgramRunDispatcher dispatcher = injector.getInstance(InMemoryProgramRunDispatcher.class);
+ ProgramController programController;
+ try {
+ programController = dispatcher.dispatchProgram(dispatcherContext);
+ } catch (Exception e) {
+ throw new Exception(String.format("Failed to dispatch program run %s", programRunId), e);
+ }
if (programController == null) {
throw new IllegalStateException("Failed to dispatch program run " + programRunId);
}
// Result doesn't matter since we just need to return with 200 status or throw an exception |
codereview_new_java_data_8877 | public void run(RunnableTaskContext context) throws Exception {
ProgramRunDispatcherContext dispatcherContext = new ProgramRunDispatcherContext(
GSON.fromJson(context.getParam(), ProgramRunDispatcherContext.class));
context.setCleanupTask(dispatcherContext::executeCleanupTasks);
ProgramRunDispatcher dispatcher = injector.getInstance(InMemoryProgramRunDispatcher.class);
- ProgramController programController = dispatcher.dispatchProgram(dispatcherContext);
if (programController == null) {
- ProgramRunId programRunId =
- dispatcherContext.getProgramDescriptor().getProgramId().run(dispatcherContext.getRunId());
throw new IllegalStateException("Failed to dispatch program run " + programRunId);
}
// Result doesn't matter since we just need to return with 200 status or throw an exception
We don't need to initialize programRunId here. Can be moved to the catch block.
public void run(RunnableTaskContext context) throws Exception {
ProgramRunDispatcherContext dispatcherContext = new ProgramRunDispatcherContext(
GSON.fromJson(context.getParam(), ProgramRunDispatcherContext.class));
context.setCleanupTask(dispatcherContext::executeCleanupTasks);
+ ProgramRunId programRunId =
+ dispatcherContext.getProgramDescriptor().getProgramId().run(dispatcherContext.getRunId());
ProgramRunDispatcher dispatcher = injector.getInstance(InMemoryProgramRunDispatcher.class);
+ ProgramController programController;
+ try {
+ programController = dispatcher.dispatchProgram(dispatcherContext);
+ } catch (Exception e) {
+ throw new Exception(String.format("Failed to dispatch program run %s", programRunId), e);
+ }
if (programController == null) {
throw new IllegalStateException("Failed to dispatch program run " + programRunId);
}
// Result doesn't matter since we just need to return with 200 status or throw an exception |
codereview_new_java_data_8878 | public Cluster getClusterDetail(ProvisionerContext context, Cluster cluster) {
@Override
public PollingStrategy getPollingStrategy(ProvisionerContext context, Cluster cluster) {
- return PollingStrategies.fixedInterval(0, TimeUnit.SECONDS);
}
}
do you know if we end up using this interval for creation parts? If so, it would be better to check the cluster status like the ephemeral one does, so we don't add a couple seconds to the start up time.
public Cluster getClusterDetail(ProvisionerContext context, Cluster cluster) {
@Override
public PollingStrategy getPollingStrategy(ProvisionerContext context, Cluster cluster) {
+ if (cluster.getStatus() == ClusterStatus.CREATING) {
+ return PollingStrategies.fixedInterval(0, TimeUnit.SECONDS);
+ }
+ DataprocConf conf = DataprocConf.create(createContextProperties(context));
+ return PollingStrategies.fixedInterval(conf.getPollInterval(), TimeUnit.SECONDS);
}
} |
codereview_new_java_data_9795 |
public interface ThemeEditorCommand {
- String OK = "ok";
- String ERROR = "error";
String STATE = "themeEditorState";
Nit: To not confuse these with actual command names, we can prefix them with `CODE_`
public interface ThemeEditorCommand {
+ String CODE_OK = "ok";
+ String CODE_ERROR = "error";
String STATE = "themeEditorState";
|
codereview_new_java_data_9796 | protected void setCssProperty(CascadingStyleSheet styleSheet,
} else {
// rule with given selector, property and value exists -> save
// for undo
- String existingValue = existingDeclaration
- .getExpressionAsCSSString();
existingDeclaration
.setExpression(newDeclaration.getExpression());
}
This is not used
protected void setCssProperty(CascadingStyleSheet styleSheet,
} else {
// rule with given selector, property and value exists -> save
// for undo
existingDeclaration
.setExpression(newDeclaration.getExpression());
} |
codereview_new_java_data_9797 |
-package com.vaadin.base.devserver.themeeditor.messages;
-
-public class ComponentMetadataRequest extends BaseRequest {
-}
Seems a bit weird to keep this. The respective handler could maybe deserialize into a `BaseRequest`, or we add a generic `EmptyRequest`. No strong preferences for changing this though if you prefer to keep them for consistency.
|
codereview_new_java_data_9798 |
-package com.vaadin.base.devserver.themeeditor.messages;
-
-public class LoadPreviewRequest extends BaseRequest {
-}
Same here, also an empty class.
|
codereview_new_java_data_9799 | public class ThemeEditorHistory {
private static class UiHistory
extends LinkedHashMap<String, MessageHandler.ExecuteAndUndo> {
- private static final int LIMIT = 30;
@Override
protected boolean removeEldestEntry(
Since the history is only relevant during development, and history entries are quite small, I'm not too concerned about consuming memory. Having a limit probably makes sense, but 30 seems too restricting. I'd up this to at least a hundred, maybe more. Also we would need to reimplement the limit on the client if we want to have one.
public class ThemeEditorHistory {
private static class UiHistory
extends LinkedHashMap<String, MessageHandler.ExecuteAndUndo> {
+ private static final int LIMIT = 100;
@Override
protected boolean removeEldestEntry( |
codereview_new_java_data_9800 | public interface HasAriaLabel extends HasElement {
* the aria-label text to set or {@code null} to clear
*/
default void setAriaLabel(String ariaLabel) {
- getElement().setAttribute(ElementConstants.ARIA_LABEL_PROPERTY_NAME,
- ariaLabel);
}
/**
The name of this constant is a bit off because it refers to the attribute, not the property. I don't know if a new constant `ARIA_LABEL_ATTRIBUTE_NAME` could be added as part of this bug fix, so for that reason, I didn't add any new constant.
public interface HasAriaLabel extends HasElement {
* the aria-label text to set or {@code null} to clear
*/
default void setAriaLabel(String ariaLabel) {
+ if (ariaLabel != null) {
+ getElement().setAttribute(ElementConstants.ARIA_LABEL_PROPERTY_NAME,
+ ariaLabel);
+ } else {
+ getElement()
+ .removeAttribute(ElementConstants.ARIA_LABEL_PROPERTY_NAME);
+ }
}
/** |
codereview_new_java_data_9801 |
* <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.
```suggestion
* {@link VaadinServiceInitListener} that sets 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_9803 |
*
* @return The push servlet mapping to use
*/
- String getPushServletMapping();
/**
* Gets the properties configured for the deployment, e.g. as init
Could this just be a default returning `""`? Then it would only be overridden/implemented if necessary
```suggestion
default String getPushServletMapping() {
return "";
}
```
*
* @return The push servlet mapping to use
*/
+ default String getPushServletMapping() {
+ return "";
+ }
/**
* Gets the properties configured for the deployment, e.g. as init |
codereview_new_java_data_9804 | public PushMode getPushMode() {
return PushMode.DISABLED;
}
- @Override
- public String getPushServletMapping() {
- return "";
- }
-
@Override
public Properties getInitParameters() {
return allProperties;
not needed if going with default
public PushMode getPushMode() {
return PushMode.DISABLED;
}
@Override
public Properties getInitParameters() {
return allProperties; |
codereview_new_java_data_9805 | public PushMode getPushMode() {
return null;
}
- @Override
- public String getPushServletMapping() {
- return "";
- }
-
@Override
public Properties getInitParameters() {
return null;
not needed if going with default
public PushMode getPushMode() {
return null;
}
@Override
public Properties getInitParameters() {
return null; |
codereview_new_java_data_9806 | 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
* Checks if Hilla is available.
```
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_9807 | 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
static boolean isHillaAvailable() {
```
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_9808 | 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();
}
}
/**
We could even throw a meaningful exception if the route is null / log a meaningful message for the developer why the route could be null - with the normal culprits: used before attached and other variants we've seen by developer, making it easier for them to understand the problem and fix it
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_9809 |
public class ViteWebsocketConnection implements Listener {
private final Consumer<String> onMessage;
- private WebSocket clientWebSocket;
- private Runnable onClose;
private Logger getLogger() {
return LoggerFactory.getLogger(getClass());
nit: can be final
public class ViteWebsocketConnection implements Listener {
private final Consumer<String> onMessage;
+ private final WebSocket clientWebSocket;
+ private final Runnable onClose;
private Logger getLogger() {
return LoggerFactory.getLogger(getClass()); |
codereview_new_java_data_9810 | public static String getJarResourceString(String jarImport) {
}
/**
- * Get the folder the front-end resources from JAR dependencies are copied
- * into.
*
* @param frontendDirectory
* project's frontend directory
```suggestion
* Get the front-end resources folder. This is where the contents of JAR
* dependencies are copied to.
```
Just a bit clearer JDoc comment for the method.
public static String getJarResourceString(String jarImport) {
}
/**
+ * Get the front-end resources folder. This is where the contents of JAR
+ * dependencies are copied to.
*
* @param frontendDirectory
* project's frontend directory |
codereview_new_java_data_9811 | public NodeTasks(Options options) {
commands.add(new TaskUpdateSettingsFile(options, themeName, pwa));
if (options.productionMode || options.isEnableDevServer()
|| options.isDevBundleBuild()) {
- LoggerFactory.getLogger(NodeTasks.class)
- .info("Running Vite update due to prod: "
- + options.productionMode + " devServer: "
- + options.isEnableDevServer() + " devBundle "
- + options.isDevBundleBuild());
commands.add(new TaskUpdateVite(options));
}
```suggestion
+ options.isEnableDevServer() + " devBundle: "
```
public NodeTasks(Options options) {
commands.add(new TaskUpdateSettingsFile(options, themeName, pwa));
if (options.productionMode || options.isEnableDevServer()
|| options.isDevBundleBuild()) {
commands.add(new TaskUpdateVite(options));
}
|
codereview_new_java_data_9812 | 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
// should create a dev-bundle
```
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_9813 | protected Stream<String> getExcludedPatterns() {
"com\\.vaadin\\.flow\\.router\\.RoutePathProvider",
"com\\.vaadin\\.flow\\.router\\.RouteNotFoundError\\$LazyInit",
"com\\.vaadin\\.flow\\.router\\.internal\\.RouteSegment\\$RouteSegmentValue",
- "com\\.vaadin\\.flow\\.component\\.ComponentReference",
// De-facto abstract class
"com\\.vaadin\\.flow\\.component\\.HtmlComponent",
// De-facto abstract class
This should be removed as we do not have the ComponentReference class anymore after all the changes.
protected Stream<String> getExcludedPatterns() {
"com\\.vaadin\\.flow\\.router\\.RoutePathProvider",
"com\\.vaadin\\.flow\\.router\\.RouteNotFoundError\\$LazyInit",
"com\\.vaadin\\.flow\\.router\\.internal\\.RouteSegment\\$RouteSegmentValue",
// De-facto abstract class
"com\\.vaadin\\.flow\\.component\\.HtmlComponent",
// De-facto abstract class |
codereview_new_java_data_9814 |
-package com.vaadin.devbundle;
-
-import com.vaadin.flow.component.dependency.JsModule;
-import com.vaadin.flow.component.dependency.NpmPackage;
-
-@JsModule("@polymer/paper-input/paper-input.js")
-@JsModule("@polymer/paper-checkbox/paper-checkbox.js")
-@NpmPackage(value = "@polymer/paper-input", version = "3.0.2")
-@NpmPackage(value = "@polymer/paper-checkbox", version = "3.0.1")
-@NpmPackage(value = "line-awesome", version = "1.3.0")
-public class Deps {
-
-}
These could be moved to the FakeAppConf so that the dev-bundle (even though only test) wouldn't make the depending application bring in the packages if not needed.
|
codereview_new_java_data_9815 | public static void updateBuildFile(PluginAdapterBuild adapter) {
* @param adapter
* used plugin adapter implementation
*/
- public static void removeBuildFile(PluginAdapterBuild adapter) {
File tokenFile = getTokenFile(adapter);
if (tokenFile.exists()) {
- try {
- FileUtils.delete(tokenFile);
- } catch (IOException e) {
- adapter.logWarn("Unable to delete token file", e);
- }
}
}
}
Should be bundle built be interrupted in this case by throwing an exception?
public static void updateBuildFile(PluginAdapterBuild adapter) {
* @param adapter
* used plugin adapter implementation
*/
+ public static void removeBuildFile(PluginAdapterBuild adapter)
+ throws IOException {
File tokenFile = getTokenFile(adapter);
if (tokenFile.exists()) {
+ FileUtils.delete(tokenFile);
}
}
} |
codereview_new_java_data_9816 | public Document getBootstrapPage(BootstrapContext context) {
document.outputSettings().prettyPrint(false);
- // In V14 legacy bootstrap mode, the theme is initialized in
- // target/frontend/generated-flow-imports.js but not in normal
- // bootstrap mode and for exported webcomponents; set a flag in
- // the DOM only if initialization is needed.
- if (context.isInitTheme()) {
- head.prependElement(SCRIPT_TAG).attr("type", "text/javascript")
- .appendChild(new DataNode(
- "window.Vaadin = window.Vaadin || {}; window.Vaadin.theme = window.Vaadin.theme || {};"
- + "window.Vaadin.theme.flowBootstrap = true;"));
- }
-
BootstrapUtils.getInlineTargets(context)
.ifPresent(targets -> handleInlineTargets(context, head,
document.body(), targets));
Maybe remove this block if it is used only in legacy bootstrapping?
public Document getBootstrapPage(BootstrapContext context) {
document.outputSettings().prettyPrint(false);
BootstrapUtils.getInlineTargets(context)
.ifPresent(targets -> handleInlineTargets(context, head,
document.body(), targets)); |
codereview_new_java_data_9817 |
*
* An instance of this class is available for injection as bean in view and
* layout classes. The class is not {@link java.io.Serializable}, so potential
- * referencing fields in Vaadin view should be defined {@literal transient}.
*
* @author Vaadin Ltd
* @since 23.3
```suggestion
* referencing fields in Vaadin views should be defined {@literal transient}.
```
*
* An instance of this class is available for injection as bean in view and
* layout classes. The class is not {@link java.io.Serializable}, so potential
+ * referencing fields in Vaadin views should be defined {@literal transient}.
*
* @author Vaadin Ltd
* @since 23.3 |
codereview_new_java_data_9818 | public <U> Optional<U> getAuthenticatedUser(Class<U> userType) {
}
/**
- * Gets an {@link Optional} containing of the authenticated principal name
- * as defined in {@link Principal#getName()}, or empty if the user is not
- * authenticated.
*
* The principal name usually refers to a username or an identifier that can
* be used to retrieve additional information for the authenticated user.
Sounds links there's a "name" or something missing here. Also, I'm not sure about mentioning the `Principal` interface at all, since it's not something we return anywhere 🤔
public <U> Optional<U> getAuthenticatedUser(Class<U> userType) {
}
/**
+ * Gets an {@link Optional} containing the authenticated principal name, or
+ * an empty optional if the user is not authenticated.
*
* The principal name usually refers to a username or an identifier that can
* be used to retrieve additional information for the authenticated user. |
codereview_new_java_data_9819 | public <U> Optional<U> getAuthenticatedUser(Class<U> userType) {
}
/**
- * Gets an {@link Optional} containing of the authenticated principal name
- * as defined in {@link Principal#getName()}, or empty if the user is not
- * authenticated.
*
* The principal name usually refers to a username or an identifier that can
* be used to retrieve additional information for the authenticated user.
```suggestion
* as defined by {@link Principal#getName()}, or an empty optional if the user is not
```
public <U> Optional<U> getAuthenticatedUser(Class<U> userType) {
}
/**
+ * Gets an {@link Optional} containing the authenticated principal name, or
+ * an empty optional if the user is not authenticated.
*
* The principal name usually refers to a username or an identifier that can
* be used to retrieve additional information for the authenticated user. |
codereview_new_java_data_9820 |
import com.vaadin.flow.shared.ui.Transport;
import com.vaadin.flow.uitest.servlet.ViewTestLayout;
-/*
- * Note that @Push is generally not supported in this location, but instead
- * explicitly picked up by logic in the BasicPushUI constructor.
- */
@CustomPush(transport = Transport.WEBSOCKET_XHR)
@Route(value = "com.vaadin.flow.uitest.ui.push.BasicPushWebsocketXhrView", layout = ViewTestLayout.class)
public class BasicPushWebsocketXhrView extends BasicPushView {
Comment is talking about `@Push` and `BasicPushUI`.
Could be good to update this so it's not that confusing in the future when making changes.
This comment is on all BasicPush* classes.
import com.vaadin.flow.shared.ui.Transport;
import com.vaadin.flow.uitest.servlet.ViewTestLayout;
@CustomPush(transport = Transport.WEBSOCKET_XHR)
@Route(value = "com.vaadin.flow.uitest.ui.push.BasicPushWebsocketXhrView", layout = ViewTestLayout.class)
public class BasicPushWebsocketXhrView extends BasicPushView { |
codereview_new_java_data_9821 | assert getServerId(valueMap) == -1
} else if (uiState != UIState.TERMINATED) {
registry.getSystemErrorHandler()
.handleSessionExpiredError(null);
}
} else if (meta.containsKey("appError")
&& uiState != UIState.TERMINATED) {
This is still valid for non-embedded applications, right?
assert getServerId(valueMap) == -1
} else if (uiState != UIState.TERMINATED) {
registry.getSystemErrorHandler()
.handleSessionExpiredError(null);
+ registry.getUILifecycle().setState(UIState.TERMINATED);
}
} else if (meta.containsKey("appError")
&& uiState != UIState.TERMINATED) { |
codereview_new_java_data_9822 | public void importFromJson(JsonObject json) {
assert json != null;
for (String key : json.keys()) {
- // assert !constants.has(key);
JsonValue value = json.get(key);
assert value != null && value.getType() != JsonType.NULL;
Would it be better to add something like a `reset()` method to `Registry` so that it could create a new instance of `ConstantPool` and maybe other instances if needed? This code now just changes the constant pool from being immutable to being mutable, which is never needed otherwise
public void importFromJson(JsonObject json) {
assert json != null;
for (String key : json.keys()) {
+ assert !constants.has(key);
JsonValue value = json.get(key);
assert value != null && value.getType() != JsonType.NULL; |
codereview_new_java_data_9823 | protected final <T> void set(Class<T> type, T instance) {
* <p>
* Note that instances by default are considered final, and you are not
* allowed to update an instance of any given type manually. Uses resettable
- * supplier to allow Registry to recreate given instance during session
- * resynchronization.
*
* @param type
* the type to store
I would not mention "session resynchronization" here because the registry knows nothing about the reasons `reset()` will be invoked.
I think it will be enough to say that the singleton will be recreated in case of registry reset
protected final <T> void set(Class<T> type, T instance) {
* <p>
* Note that instances by default are considered final, and you are not
* allowed to update an instance of any given type manually. Uses resettable
+ * supplier to allow Registry to recreate given instances.
*
* @param type
* the type to store |
codereview_new_java_data_9824 | public enum RequestType {
UIDL(ApplicationConstants.REQUEST_TYPE_UIDL),
/**
- * Session resynchronization requests.
*/
- SESSION_RESYNC(ApplicationConstants.REQUEST_TYPE_SESSION_RESYNC),
/**
* Heartbeat requests.
I wonder if we should use a name more related to web components, since it is handled by a `WebcomponentBootstrapHandler`
public enum RequestType {
UIDL(ApplicationConstants.REQUEST_TYPE_UIDL),
/**
+ * WebComponent resynchronization requests.
*/
+ WEBCOMPONENT_RESYNC(
+ ApplicationConstants.REQUEST_TYPE_WEBCOMPONENT_RESYNC),
/**
* Heartbeat requests. |
codereview_new_java_data_9825 |
* the browser.
* <p>
* NOTE: In the case of using JsModule with LitTemplate, the value needs to
- * point to a real file as it will be copied to the stats.json. An exported
- * alias from the package will not work.
*
* @return a JavaScript module identifier
*/
Can we reword the sentence `it will be copied to the stats.json`?
Do you mean the file path is referenced in `stats.json`?
Or are you referring to the fact that we need the real file path because it will be copied in another directory?
* the browser.
* <p>
* NOTE: In the case of using JsModule with LitTemplate, the value needs to
+ * point to a real file as it will be copied to the templates folder under
+ * target folder. An exported alias from the package will not work.
*
* @return a JavaScript module identifier
*/ |
codereview_new_java_data_9826 | public AtmosphereFramework addInitParameter(String name,
findFirstUrlMapping(servletRegistration.get())
+ Constants.PUSH_MAPPING);
} else {
- getLogger().warn(
"Unable to determine servlet registration for {}. "
+ "Using root mapping for push",
vaadinServletConfig.getServletName());
Should this be info? Now every start of an OSGI deployment would log this warning and the developer has no way to fix it 😅
public AtmosphereFramework addInitParameter(String name,
findFirstUrlMapping(servletRegistration.get())
+ Constants.PUSH_MAPPING);
} else {
+ getLogger().debug(
"Unable to determine servlet registration for {}. "
+ "Using root mapping for push",
vaadinServletConfig.getServletName()); |
codereview_new_java_data_9827 | public Options withFeatureFlags(FeatureFlags featureFlags) {
}
protected FeatureFlags getFeatureFlags() {
- if (featureFlags != null) {
- return featureFlags;
- }
-
- final FeatureFlags flags = new FeatureFlags(lookup);
- if (javaResourceFolder != null) {
- flags.setPropertiesLocation(javaResourceFolder);
}
- return flags;
}
public File getJarFrontendResourcesFolder() {
Should we store flags to featureFlags here?
public Options withFeatureFlags(FeatureFlags featureFlags) {
}
protected FeatureFlags getFeatureFlags() {
+ if (featureFlags == null) {
+ featureFlags = new FeatureFlags(lookup);
+ if (javaResourceFolder != null) {
+ featureFlags.setPropertiesLocation(javaResourceFolder);
+ }
}
+ return featureFlags;
}
public File getJarFrontendResourcesFolder() { |
codereview_new_java_data_9828 | public void doInit(VaadinRequest request, int uiId) {
* the initialization request
* @param uiId
* the id of the new ui
*
* @see #getUIId()
*/
missing javadoc for `appId` param
public void doInit(VaadinRequest request, int uiId) {
* the initialization request
* @param uiId
* the id of the new ui
+ * @param appId
+ * the application id
*
* @see #getUIId()
*/ |
codereview_new_java_data_9829 | public void init() throws Exception {
commandsField.setAccessible(true);
commands = (List<FallibleCommand>) commandsField.get(nodeTasks);
- // With Vite we always have two default tasks that cannot be reomve
- // by configuring builder
commands.clear();
Assert.assertEquals("No commands should be added initially, "
Noted that this talks about builder when it should probably say options.
public void init() throws Exception {
commandsField.setAccessible(true);
commands = (List<FallibleCommand>) commandsField.get(nodeTasks);
+ // With Vite we always have two default tasks that cannot be removed
+ // by configuration options
commands.clear();
Assert.assertEquals("No commands should be added initially, " |
codereview_new_java_data_9830 | public final class Constants implements Serializable {
* Internal servlet parameter for push url configuration.
*/
public static final String INTERNAL_SERVLET_PARAMETER_PUSH_URL = "internalPushURL";
/**
* The static build resources folder.
*/
```suggestion
public static final String INTERNAL_SERVLET_PARAMETER_PUSH_URL = "internalPushURL";
/**
```
public final class Constants implements Serializable {
* Internal servlet parameter for push url configuration.
*/
public static final String INTERNAL_SERVLET_PARAMETER_PUSH_URL = "internalPushURL";
+
/**
* The static build resources folder.
*/ |
codereview_new_java_data_9831 | private static String findFirstUrlMapping(ServletConfig config) {
if (name != null) {
ServletRegistration reg = config.getServletContext()
.getServletRegistrations().get(name);
- firstMapping = reg.getMappings().stream().findFirst().orElse("/");
}
return firstMapping.replace("/*", "/");
}
I propose to sort the mappings before taking the first one to make it deterministic and return the same mapping always.
private static String findFirstUrlMapping(ServletConfig config) {
if (name != null) {
ServletRegistration reg = config.getServletContext()
.getServletRegistrations().get(name);
+ firstMapping = reg.getMappings().stream().sorted().findFirst()
+ .orElse("/");
}
return firstMapping.replace("/*", "/");
} |
codereview_new_java_data_9832 | private NodeMap getConfigurationMap() {
/**
* Gets the fixed push URL.
*
- * @return the fixed push URL
*/
public String getPushUrl() {
return Constants.PUSH_MAPPING;
Let's reflect the fixed (constant) push url in the javadoc, so let's mention "/VAADIN/push" explicitly here.
private NodeMap getConfigurationMap() {
/**
* Gets the fixed push URL.
*
+ * @return the fixed push URL (VAADIN/push)
*/
public String getPushUrl() {
return Constants.PUSH_MAPPING; |
codereview_new_java_data_9833 | public AtmospherePushConnection(Registry registry) {
String serviceUrl = registry.getApplicationConfiguration()
.getServiceUrl();
if (!serviceUrl.equals(".")) {
url = serviceUrl + url;
}
runWhenAtmosphereLoaded(
Constants define
```
public static final String VAADIN_MAPPING = "VAADIN/";
/**
* The path used in the vaadin servlet for handling push.
*/
public static final String PUSH_MAPPING = VAADIN_MAPPING + "push";
```
so the PUSH_MAPPING would be `VAADIN/push`.
Can we ensure that `serviceUrl` end with `/` ? If not, let's check it and add "/", if it's not the case.
public AtmospherePushConnection(Registry registry) {
String serviceUrl = registry.getApplicationConfiguration()
.getServiceUrl();
if (!serviceUrl.equals(".")) {
+ if (!serviceUrl.endsWith("/")) {
+ serviceUrl += "/";
+ }
url = serviceUrl + url;
}
runWhenAtmosphereLoaded( |
codereview_new_java_data_9834 |
.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",
```suggestion
LoggerFactory.getLogger(PolymerTemplate.class.getName())
.error("Unable to read the version.properties file.");
throw new ExceptionInInitializerError(e);
```
.getResourceAsStream("version.properties"));
} catch (Exception e) {
LoggerFactory.getLogger(PolymerTemplate.class.getName())
+ .error("Unable to read the version.properties file.");
+ throw new ExceptionInInitializerError(e);
}
LicenseChecker.checkLicenseFromStaticBlock("flow-polymer-template", |
codereview_new_java_data_9836 | public void convertFile(Path filePath, boolean useLit1,
command.add("-disable-optional-chaining");
}
- ProcessBuilder builder = FrontendUtils.createProcessBuilder(command);
- builder.inheritIO();
- Process process = builder.start();
if (process.waitFor() != 0) {
throw new ConversionFailedException(
"An error occurred while the conversion. See logs for more details.");
Would the root cause of the frontend converter's failure be visible in the output for the developer? I see no code which takes the output and logs it.
public void convertFile(Path filePath, boolean useLit1,
command.add("-disable-optional-chaining");
}
+ Process process = FrontendUtils.createProcessBuilder(command)
+ .inheritIO().start();
if (process.waitFor() != 0) {
throw new ConversionFailedException(
"An error occurred while the conversion. See logs for more details."); |
codereview_new_java_data_9837 | public void commandToString_longCommand_resultIsWrapped() {
List<String> command = Arrays.asList("./node/node",
"./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
"--config", "./webpack.config.js", "--port 57799",
-"--env watchDogPort=57798", "-d", "--inline=false", "--progress",
"--colors");
String wrappedCommand = FrontendUtils.commandToString(".", command);
Assert.assertEquals("\n" + "./node/node \\ \n"
+ " ./node_modules/webpack-dev-server/bin/webpack-dev-server.js \\ \n"
- + " --config ./webpack.config.js --port 57799 \\ \n"
- + " --env watchDogPort=57798 -d --inline=false \\ \n"
- + " --progress --colors \n", wrappedCommand);
}
@Test
The test could just drop the watchDogPort all in all as it doesn't work.
public void commandToString_longCommand_resultIsWrapped() {
List<String> command = Arrays.asList("./node/node",
"./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
"--config", "./webpack.config.js", "--port 57799",
+"-d", "--inline=false", "--progress",
"--colors");
String wrappedCommand = FrontendUtils.commandToString(".", command);
Assert.assertEquals("\n" + "./node/node \\ \n"
+ " ./node_modules/webpack-dev-server/bin/webpack-dev-server.js \\ \n"
+ + " --config ./webpack.config.js --port 57799 -d \\ \n"
+ + " --inline=false --progress --colors \n", wrappedCommand);
}
@Test |
codereview_new_java_data_9838 | public void execute() throws MojoFailureException {
}
} catch (Exception e) {
throw new MojoFailureException(
- "Could not execute convert-polymer-to-lit goal.", e);
}
}
}
```suggestion
"Could not execute convert-polymer goal.", e);
```
public void execute() throws MojoFailureException {
}
} catch (Exception e) {
throw new MojoFailureException(
+ "Could not execute convert-polymer goal.", e);
}
}
} |
codereview_new_java_data_9839 |
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.util.Arrays;
-import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
-import org.apache.maven.artifact.DependencyResolutionRequiredException;
-import org.apache.maven.model.Build;
-import org.apache.maven.project.MavenProject;
-import org.codehaus.plexus.util.ReflectionUtils;
-import org.mockito.Mockito;
-
-import com.vaadin.flow.server.frontend.installer.NodeInstaller;
-import com.vaadin.flow.plugin.base.PluginAdapterBase;
-import com.vaadin.flow.plugin.maven.FlowModeAbstractMojo;
-import com.vaadin.flow.server.Constants;
-import com.vaadin.flow.server.frontend.FrontendTools;
-
import elemental.json.Json;
import elemental.json.JsonObject;
All of these imports are not used so can be deleted. Leftovers after development?
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
import elemental.json.Json;
import elemental.json.JsonObject;
|
codereview_new_java_data_9840 |
package com.vaadin.flow.plugin.base;
import java.io.File;
```suggestion
/*
* 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
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.plugin.base;
```
+/*
+ * 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
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
package com.vaadin.flow.plugin.base;
import java.io.File; |
codereview_new_java_data_9841 | 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
*/
```suggestion
* New license checker is only available in npm mode with enabled 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_9842 | 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
*/
```suggestion
* @return {@code true} if old JavaScript license checker is used,
```
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_9843 | public boolean synchronizedHandleRequest(VaadinSession session,
* development mode.
*/
public static void addLicenseChecker(Document indexDocument, DeploymentConfiguration config) {
- if (config.isOldLicenseCheckerEnabled()) {
- addScript(indexDocument,
- "window.Vaadin = window.Vaadin || {};" +
- "window.Vaadin.devTools = window.Vaadin.devTools || {};" +
- "window.Vaadin.devTools.createdCvdlElements = window.Vaadin.devTools.createdCvdlElements || [];"
- );
- } else {
// maybeCheck is invoked by the WC license checker
addScript(indexDocument, "" + //
"window.Vaadin = window.Vaadin || {};" + //
Isn't `createdCvdlElements` related to the new license checker only?
public boolean synchronizedHandleRequest(VaadinSession session,
* development mode.
*/
public static void addLicenseChecker(Document indexDocument, DeploymentConfiguration config) {
+ if (!config.isOldLicenseCheckerEnabled()) {
// maybeCheck is invoked by the WC license checker
addScript(indexDocument, "" + //
"window.Vaadin = window.Vaadin || {};" + // |
codereview_new_java_data_9844 | private void checkCompatibilityMode(boolean loggWarning) {
* Log a warning if new license checker is enabled in compatibility mode
* or while the live reload is off.
*/
- private void checkNewLicenseChecker(boolean loggWarning) {
boolean enableNewLicenseChecker = !getBooleanProperty(
InitParameters.SERVLET_PARAMETER_ENABLE_OLD_LICENSE_CHECKER, false);
if (loggWarning && !isDevModeLiveReloadEnabled() && enableNewLicenseChecker) {
```suggestion
private void checkNewLicenseChecker(boolean logWarning) {
```
private void checkCompatibilityMode(boolean loggWarning) {
* Log a warning if new license checker is enabled in compatibility mode
* or while the live reload is off.
*/
+ private void checkNewLicenseChecker(boolean logWarning) {
boolean enableNewLicenseChecker = !getBooleanProperty(
InitParameters.SERVLET_PARAMETER_ENABLE_OLD_LICENSE_CHECKER, false);
if (loggWarning && !isDevModeLiveReloadEnabled() && enableNewLicenseChecker) { |
codereview_new_java_data_9845 | public class InitParameters implements Serializable {
*
* @since 2.8
*/
- public static final String SERVLET_PARAMETER_ENABLE_OLD_LICENSE_CHECKER = "enableOldLicenseChecker";
}
```suggestion
public static final String SERVLET_PARAMETER_ENABLE_OLD_LICENSE_CHECKER = "oldLicenseChecker";
```
public class InitParameters implements Serializable {
*
* @since 2.8
*/
+ public static final String SERVLET_PARAMETER_ENABLE_OLD_LICENSE_CHECKER = "oldLicenseChecker";
} |
codereview_new_java_data_9846 | public class TaskUpdateImports extends NodeUpdater {
private final boolean disablePnpm;
private final boolean productionMode;
private final List<String> additionalFrontendModules;
- private final boolean enableOldLicenseChecker;
private class UpdateMainImportsFile extends AbstractUpdateImports {
```suggestion
private final boolean oldLicenseChecker;
```
public class TaskUpdateImports extends NodeUpdater {
private final boolean disablePnpm;
private final boolean productionMode;
private final List<String> additionalFrontendModules;
+ private final boolean oldLicenseChecker;
private class UpdateMainImportsFile extends AbstractUpdateImports {
|
codereview_new_java_data_9848 | protected String filterServerResponseHeader(
return prefix + headerValue;
}
} catch (MalformedURLException e) {
- e.printStackTrace();
- return headerValue;
}
}
Can `printStackTrace` be removed or replaced using logger?
protected String filterServerResponseHeader(
return prefix + headerValue;
}
} catch (MalformedURLException e) {
+ throw new IllegalArgumentException("Unable to rewrite header "
+ + headerName + ": " + headerValue);
}
} |
codereview_new_java_data_9849 | private static String getStoredServerNavigation(
if (session == null) {
return null;
}
- return (String) session.getAttribute(
ViewAccessChecker.SESSION_STORED_REDIRECT_ABSOLUTE);
}
static boolean isTypescriptLogin(HttpServletRequest request) {
Does it make sense to also remove the attribute from the session here? Or should it be preserved for other uses?
private static String getStoredServerNavigation(
if (session == null) {
return null;
}
+ String redirectUrl = (String) session.getAttribute(
ViewAccessChecker.SESSION_STORED_REDIRECT_ABSOLUTE);
+ session.removeAttribute(
+ ViewAccessChecker.SESSION_STORED_REDIRECT_ABSOLUTE);
+ return redirectUrl;
}
static boolean isTypescriptLogin(HttpServletRequest request) { |
codereview_new_java_data_9850 | private Map<String, String> readDependencies(String id,
return map;
} catch (IOException e) {
- log().error("Unable to read default dependencies", e);
return new HashMap<>();
}
Adding `id` value to the error message may simplify troubleshooting, in case of exception
private Map<String, String> readDependencies(String id,
return map;
} catch (IOException e) {
+ log().error(
+ "Unable to read " + packageJsonKey + " from '" + id + "'",
+ e);
return new HashMap<>();
}
|
codereview_new_java_data_9851 | private static String getExistingFileContent(File generatedFile)
if (!generatedFile.exists()) {
return null;
}
- return FileUtils.readFileToString(generatedFile,
- StandardCharsets.UTF_8);
}
}
nit: we can maybe use a static import for `UTF_8`, as we do in `writeIfChanged`
```suggestion
return FileUtils.readFileToString(generatedFile, UTF_8);
```
private static String getExistingFileContent(File generatedFile)
if (!generatedFile.exists()) {
return null;
}
+ return FileUtils.readFileToString(generatedFile, UTF_8);
}
} |
codereview_new_java_data_9852 | protected void setupCss(Element head, BootstrapContext context) {
// visible and outside of normal flow
setupErrorDialogs(styles);
- styles = head.appendElement("style").attr("type",
- CSS_TYPE_ATTRIBUTE_VALUE);
setupHiddenElement(styles);
}
Is there a reason we need another style element instead of adding it to the existing one, i.e. the one called "setupErrorDialogs"?
protected void setupCss(Element head, BootstrapContext context) {
// visible and outside of normal flow
setupErrorDialogs(styles);
setupHiddenElement(styles);
}
|
codereview_new_java_data_9853 |
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
-import java.util.HashMap;
-import java.util.Map;
import java.util.Optional;
@Service
public class AccountService {
- private static final Map<String, Account> ACCOUNT_CACHE = new HashMap<>(2);
public AccountService(UserInfoService userInfoService) {
UserInfo user = userInfoService.findByUsername("john");
Account userAccount = new Account();
userAccount.setOwner(user);
- userAccount.setBalance(new BigDecimal("10000"));
UserInfo admin = userInfoService.findByUsername("emma");
Account adminAccount = new Account();
adminAccount.setOwner(admin);
- adminAccount.setBalance(new BigDecimal("200000"));
- ACCOUNT_CACHE.put(user.getUsername(), userAccount);
- ACCOUNT_CACHE.put(admin.getUsername(), adminAccount);
}
public Optional<Account> findByOwner(String username) {
This should be a concurrent map
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
@Service
public class AccountService {
+ private static final ConcurrentMap<String, Account> ACCOUNT_CACHE = new ConcurrentHashMap<>(
+ 2);
public AccountService(UserInfoService userInfoService) {
UserInfo user = userInfoService.findByUsername("john");
Account userAccount = new Account();
userAccount.setOwner(user);
+ userAccount.setBalance(new BigDecimal("10000.00"));
UserInfo admin = userInfoService.findByUsername("emma");
Account adminAccount = new Account();
adminAccount.setOwner(admin);
+ adminAccount.setBalance(new BigDecimal("200000.00"));
+ ACCOUNT_CACHE.putIfAbsent(user.getUsername(), userAccount);
+ ACCOUNT_CACHE.putIfAbsent(admin.getUsername(), adminAccount);
}
public Optional<Account> findByOwner(String username) { |
codereview_new_java_data_9854 | public class UIAccessContextIT extends AbstractIT {
@Test
public void securityContextSetForUIAccess() throws Exception {
- String expectedUserBalance = "Hello John the User, your bank account balance is $10000.";
- String expectedAdminBalance = "Hello Emma the Admin, your bank account balance is $200000.";
WebDriver adminBrowser = getDriver();
try {
Why does this change when you remove the database?
public class UIAccessContextIT extends AbstractIT {
@Test
public void securityContextSetForUIAccess() throws Exception {
+ String expectedUserBalance = "Hello John the User, your bank account balance is $10000.00.";
+ String expectedAdminBalance = "Hello Emma the Admin, your bank account balance is $200000.00.";
WebDriver adminBrowser = getDriver();
try { |
codereview_new_java_data_9855 | public void loadProperties() {
// Allow users to override a feature flag with a system property
for (Feature f : features) {
- var prop = System.getProperty("featureFlag-" + f.getId());
if (prop != null) {
f.setEnabled(Boolean.parseBoolean(prop));
Should the system property be prefixed with `vaadin-` like the name of the property file?
public void loadProperties() {
// Allow users to override a feature flag with a system property
for (Feature f : features) {
+ var prop = System.getProperty("vaadin-" + f.getId());
if (prop != null) {
f.setEnabled(Boolean.parseBoolean(prop)); |
codereview_new_java_data_9856 | public void enabledFeatureFlagsMarkedInStatsWhenToggled()
@Test
public void featureFlagShouldBeOverridableWithSystemProperty()
throws IOException {
- System.setProperty("featureFlag-exampleFeatureFlag", "true");
createFeatureFlagsFile(
"com.vaadin.experimental.exampleFeatureFlag=false\n");
featureFlags.loadProperties();
In general, if we set some system properties during a test, it is highly recommended to hold their pre-change states and restore them after the test ends. The impact of setting this specific property might not be very obvious but in the future, this might mess up some other test results.
public void enabledFeatureFlagsMarkedInStatsWhenToggled()
@Test
public void featureFlagShouldBeOverridableWithSystemProperty()
throws IOException {
+ System.setProperty("vaadin-exampleFeatureFlag", "true");
createFeatureFlagsFile(
"com.vaadin.experimental.exampleFeatureFlag=false\n");
featureFlags.loadProperties(); |
codereview_new_java_data_9857 | Map<String, String> getDefaultDevDependencies() {
defaults.put("rollup-plugin-brotli", "3.1.0");
defaults.put("vite-plugin-checker", "0.4.9");
defaults.put("mkdirp", "1.0.4"); // for application-theme-plugin
- defaults.put("rollup-plugin-workbox", "6.2.0");
// Dependencies of rollup-plugin-postcss-lit-custom
defaults.put("@rollup/pluginutils", "4.1.0");
```suggestion
defaults.put("workbox-build", WORKBOX_VERSION);
```
Map<String, String> getDefaultDevDependencies() {
defaults.put("rollup-plugin-brotli", "3.1.0");
defaults.put("vite-plugin-checker", "0.4.9");
defaults.put("mkdirp", "1.0.4"); // for application-theme-plugin
+ defaults.put("workbox-build", WORKBOX_VERSION);
// Dependencies of rollup-plugin-postcss-lit-custom
defaults.put("@rollup/pluginutils", "4.1.0"); |
codereview_new_java_data_9858 | public String getTranslation(String key, Locale locale, Object... params) {
* @param params
* parameters used in translation string
* @return translation for key if found
- * @deprecated Use {@link #getTranslation(Locale, String, Object...)}
- * instead
*/
public String getTranslation(Object key, Locale locale, Object... params) {
if (getI18NProvider() == null) {
```suggestion
* @deprecated Use {@link #getTranslation(String, Locale, Object...)}
```
public String getTranslation(String key, Locale locale, Object... params) {
* @param params
* parameters used in translation string
* @return translation for key if found
*/
public String getTranslation(Object key, Locale locale, Object... params) {
if (getI18NProvider() == null) { |
codereview_new_java_data_9859 |
/*
- * Copyright 2000-2021 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_9860 | public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
* Typically, subclasses should call super to apply default Vaadin
* configuration in addition to custom rules.
*
- * @param http
- * @throws Exception
*/
protected void configure(HttpSecurity http) throws Exception {
// Use a security context holder that can find the context from Vaadin
Missing javadoc for http and Exception
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
* Typically, subclasses should call super to apply default Vaadin
* configuration in addition to custom rules.
*
+ * @param http the {@link HttpSecurity} to modify
+ * @throws Exception if an error occurs
*/
protected void configure(HttpSecurity http) throws Exception {
// Use a security context holder that can find the context from Vaadin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.