id
stringlengths 29
30
| content
stringlengths 152
2.6k
|
|---|---|
codereview_new_java_data_9861
|
public void setLabel() {
assertEquals("test label", component.getLabel());
}
-}
\ No newline at end of file
Needs line break.
public void setLabel() {
assertEquals("test label", component.getLabel());
}
\ No newline at end of file
+}
|
codereview_new_java_data_9862
|
Logger log() {
FrontendUtils.deleteNodeModules(new File(npmFolder, "node_modules"));
Assert.assertTrue(
- "File from linked folder was removed, even if only link folder should be touched.",
linkFolderFile.exists());
}
Minor: Couldn't understand what is the message implying exactly.
Logger log() {
FrontendUtils.deleteNodeModules(new File(npmFolder, "node_modules"));
Assert.assertTrue(
+ "Linked folder contents should not be removed.",
linkFolderFile.exists());
}
|
codereview_new_java_data_9863
|
private NodeTasks(Builder builder) {
if (hillaTask != null) {
hillaTask.configure(builder.getNpmFolder(),
builder.getBuildDirectory());
} else {
if (builder.endpointSourceFolder != null
&& builder.endpointSourceFolder.exists()
Shouldn't 'hillaTask` be added to commands? I think task are not meant to be execute eagerly
private NodeTasks(Builder builder) {
if (hillaTask != null) {
hillaTask.configure(builder.getNpmFolder(),
builder.getBuildDirectory());
+ commands.add(hillaTask);
} else {
if (builder.endpointSourceFolder != null
&& builder.endpointSourceFolder.exists()
|
codereview_new_java_data_9864
|
* For internal use only. May be renamed or removed in a future release.
*/
public interface TaskGenerateHilla extends FallibleCommand {
- void configure(File projectDirectory, String buildDirectoryName);
}
Could it be a default method with empty body if the logic is in `execute` method?
* For internal use only. May be renamed or removed in a future release.
*/
public interface TaskGenerateHilla extends FallibleCommand {
+ default void configure(File projectDirectory, String buildDirectoryName) {
+ }
}
|
codereview_new_java_data_9865
|
* For internal use only. May be renamed or removed in a future release.
*/
public interface TaskGenerateHilla extends FallibleCommand {
default void configure(File projectDirectory, String buildDirectoryName) {
}
}
Being a public API we should perhaps add Javadocs. For example we can make it explicit that this method will always be invoked once and before `execute`
* For internal use only. May be renamed or removed in a future release.
*/
public interface TaskGenerateHilla extends FallibleCommand {
+ /**
+ * Configures the task by passing it some parameters.
+ *
+ * @param projectDirectory
+ * 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_9866
|
protected 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) {
-> "A collection with all registered listeners for a given event type"
protected 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.
*/
protected Collection<?> getListeners(
Class<? extends ComponentEvent> eventType) {
|
codereview_new_java_data_9867
|
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");
-> "A collection with all registered listeners for a given event type"
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_9868
|
public void addListenerToComponent_getListeners_returnsCollection() {
Assert.assertEquals(1, listeners.size());
listener.remove();
- Assert.assertFalse(
- ComponentUtil.hasEventListener(component, PollEvent.class));
}
}
Should this line check that `ComponentUtil.getListeners` returns empty collection, not `ComponentUtil.hasEventListener` (since you want to test exactly `getListeners`)?
public void addListenerToComponent_getListeners_returnsCollection() {
Assert.assertEquals(1, listeners.size());
listener.remove();
+ Assert.assertTrue(ComponentUtil.getListeners(component, PollEvent.class)
+ .isEmpty());
}
}
|
codereview_new_java_data_9869
|
default void add(Component... components) {
default void add(Collection<Component> components) {
Objects.requireNonNull(components, "Components should not be null");
components.stream()
- .map(c -> Objects.requireNonNull(c,
"Component to add cannot be null"))
.map(Component::getElement).forEach(getElement()::appendChild);
}
```suggestion
.map(component -> Objects.requireNonNull(component,
```
default void add(Component... components) {
default void add(Collection<Component> components) {
Objects.requireNonNull(components, "Components should not be null");
components.stream()
+ .map(component -> Objects.requireNonNull(component,
"Component to add cannot be null"))
.map(Component::getElement).forEach(getElement()::appendChild);
}
|
codereview_new_java_data_9870
|
protected Stream<T> fetchFromProvider(int offset, int limit) {
}
private String getInvalidContractMessage(String method) {
- return String.format("The data provider hasn't ever called %s() " + "method on the provided query. "
+ "It means that the the data provider breaks the contract "
+ "and the returned stream contains unxpected data.", method);
}
```suggestion
return String.format("The data provider hasn't ever called %s() method on the provided query. "
```
protected Stream<T> fetchFromProvider(int offset, int limit) {
}
private String getInvalidContractMessage(String method) {
+ return String.format("The data provider hasn't ever called %s() method on the provided query. "
+ "It means that the the data provider breaks the contract "
+ "and the returned stream contains unxpected data.", method);
}
|
codereview_new_java_data_9871
|
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);
Should we deprecate this constructor that accepts a custom `frontendGeneratedFolder`?
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_9872
|
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_9873
|
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_9874
|
public void documentCssImport_externalAddedToHeadAsLink() {
checkLogsForErrors();
final WebElement documentHead = getDriver()
- .findElement(By.xpath("/html/head"));
final List<WebElement> links = documentHead
.findElements(By.tagName("link"));
**nit:**
```suggestion
.findElement(By.tagName("head"));
```
public void documentCssImport_externalAddedToHeadAsLink() {
checkLogsForErrors();
final WebElement documentHead = getDriver()
+ .findElement(By.tagName("head"));
final List<WebElement> links = documentHead
.findElements(By.tagName("link"));
|
codereview_new_java_data_9875
|
private static String decode(String parameter) {
@Override
public String toString() {
- return getQueryString();
}
@Override
nit: I'm personally not a big fan of toString methods without object identifier like class names, e.g. `QueryParameters(foo=bar)` instead of `foo=bar`.
The other part of the implementation looks good to me! (Not sure if you need to add unit-test for the new methods in UI tho)
private static String decode(String parameter) {
@Override
public String toString() {
+ return "QueryParameters(" + getQueryString() + ")";
}
@Override
|
codereview_new_java_data_9876
|
public <T, C extends Component & HasUrlParameter<T>> Optional<C> navigate(
/**
* Updates this UI to show the view corresponding to the given navigation
- * target with the specified parameter. The parameter needs to be the same
- * as defined in the route target HasUrlParameter.
* <p>
* Besides the navigation to the {@code location} this method also updates
* the browser location (and page history).
```suggestion
* Updates this UI to show the view corresponding to the given navigation
* target and query parameters.
```
public <T, C extends Component & HasUrlParameter<T>> Optional<C> navigate(
/**
* Updates this UI to show the view corresponding to the given navigation
+ * target and query parameters.
* <p>
* Besides the navigation to the {@code location} this method also updates
* the browser location (and page history).
|
codereview_new_java_data_9877
|
public class FeatureFlags implements Serializable {
"com.vaadin.flow.server.frontend.NodeTestComponents$ExampleExperimentalComponent");
public static final Feature WEBPACK = new Feature(
"Use Webpack for front-end builds (Deprecated)",
- "webpackForFrontendBuild", "", true, null);
public static final Feature MAP_COMPONENT = new Feature(
"Map component (Pro)", "mapComponent",
"https://vaadin.com/docs/latest/ds/components/map", true,
```suggestion
"webpackForFrontendBuild", "https://github.com/vaadin/flow/issues/13852", true, null);
```
public class FeatureFlags implements Serializable {
"com.vaadin.flow.server.frontend.NodeTestComponents$ExampleExperimentalComponent");
public static final Feature WEBPACK = new Feature(
"Use Webpack for front-end builds (Deprecated)",
+ "webpackForFrontendBuild",
+ "https://github.com/vaadin/flow/issues/13852", true, null);
public static final Feature MAP_COMPONENT = new Feature(
"Map component (Pro)", "mapComponent",
"https://vaadin.com/docs/latest/ds/components/map", true,
|
codereview_new_java_data_9878
|
protected String getTestPath() {
return Constants.PAGE_CONTEXT + "/index.html";
}
- @Ignore("Vite handles web components differently. verify if #7005 affects also Vite")
// test for #7005
@Test
public void globalStylesAreUnderTheWebComponent() {
```suggestion
@Ignore("Vite handles web components differently. Verify if #7005 affects also Vite. See https://github.com/vaadin/flow/issues/14256")
```
protected String getTestPath() {
return Constants.PAGE_CONTEXT + "/index.html";
}
+ @Ignore("Vite handles web components differently. Verify if #7005 affects also Vite. See https://github.com/vaadin/flow/issues/14256")
// test for #7005
@Test
public void globalStylesAreUnderTheWebComponent() {
|
codereview_new_java_data_9879
|
public void setup() throws Exception {
.isPresent());
createStubNode(false, true, baseDir);
- createStubViteServer("ready in 500ms", 500, baseDir, true);
// Prevent TaskRunNpmInstall#cleanUp from deleting node_modules
new File(baseDir, "node_modules/.modules.yaml").createNewFile();
```suggestion
createStubViteServer("ready in 500 ms", 500, baseDir, true);
```
public void setup() throws Exception {
.isPresent());
createStubNode(false, true, baseDir);
+ createStubViteServer("ready in 500 ms", 500, baseDir, true);
// Prevent TaskRunNpmInstall#cleanUp from deleting node_modules
new File(baseDir, "node_modules/.modules.yaml").createNewFile();
|
codereview_new_java_data_9880
|
public static <T> T getData(Component component, Class<T> type) {
* Falls back to the router for the currently active VaadinService if the
* component is not attached.
*
* @return a router instance
* @throws IllegalStateException
* if no router instance is available
```suggestion
* @param component component for which the requested router instance serves navigation
* @return a router instance
```
public static <T> T getData(Component component, Class<T> type) {
* Falls back to the router for the currently active VaadinService if the
* component is not attached.
*
+ * @param component component for which the requested router instance serves navigation
* @return a router instance
* @throws IllegalStateException
* if no router instance is available
|
codereview_new_java_data_9881
|
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_9882
|
* {@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_9883
|
* 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_9884
|
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_9885
|
* 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_9886
|
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_9887
|
* {@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_9888
|
private void forceMessageHandling() {
}
// Call resynchronize to make sure a resynchronize request is sent
- // in
- // case endRequest did not already do this.
registry.getMessageSender().resynchronize();
}
}
```suggestion
// Call resynchronize to make sure a resynchronize request is sent
// in case endRequest did not already do this.
```
private void forceMessageHandling() {
}
// Call resynchronize to make sure a resynchronize request is sent
+ // in case endRequest did not already do this.
registry.getMessageSender().resynchronize();
}
}
|
codereview_new_java_data_9889
|
/**
* The listener interface for receiving {@link ValidationStatusChangeEvent}
- * events. The classes that are interested in processing a Validation status
- * changed event of field components e.g.
- * {@link com.vaadin.flow.data.binder.Binder.BindingBuilderImpl}, register
- * implementation of this interface via
* {@link HasValidator#addValidationStatusChangeListener(ValidationStatusChangeListener)}
- * which are called whenever such event is fired by the component class, e.g.
- * {@code datePicker}.
*
* @since 23.2
*
Do you expect if any other classes, rather than a `Binder`, would use this API to react to validation status change listener? For example, if someone would want to modify the view/page according to a validation status of the field, e.g. put a banner, disable buttons etc. ? If we expect such a use cases, then maybe worth to describe them here.
/**
* The listener interface for receiving {@link ValidationStatusChangeEvent}
+ * events. The classes that are interested in processing validation status
+ * changed events of field components e.g. {@code BindingBuilder}, should
+ * register implementation of this interface via
* {@link HasValidator#addValidationStatusChangeListener(ValidationStatusChangeListener)}
+ * which are called whenever such event is fired by the component.
*
* @since 23.2
*
|
codereview_new_java_data_9890
|
default Validator<V> getDefaultValidator() {
* Enables the implementing components to notify changes in their validation
* status to the observers. This method is
* <p>
- * <strong>Note:</strong> This method should be overridden by the
* implementing classes e.g. components, to enable the associated
* {@link Binder.Binding} instance subscribing for their validation change
* events and revalidate itself.
```suggestion
* status to the observers.
```
default Validator<V> getDefaultValidator() {
* Enables the implementing components to notify changes in their validation
* status to the observers. This method is
* <p>
+ * <strong>Note:</strong> This method can be overridden by the
* implementing classes e.g. components, to enable the associated
* {@link Binder.Binding} instance subscribing for their validation change
* events and revalidate itself.
|
codereview_new_java_data_9891
|
default Validator<V> getDefaultValidator() {
* Enables the implementing components to notify changes in their validation
* status to the observers. This method is
* <p>
- * <strong>Note:</strong> This method should be overridden by the
* implementing classes e.g. components, to enable the associated
* {@link Binder.Binding} instance subscribing for their validation change
* events and revalidate itself.
```suggestion
* <strong>Note:</strong> This method can be overridden by the
```
default Validator<V> getDefaultValidator() {
* Enables the implementing components to notify changes in their validation
* status to the observers. This method is
* <p>
+ * <strong>Note:</strong> This method can be overridden by the
* implementing classes e.g. components, to enable the associated
* {@link Binder.Binding} instance subscribing for their validation change
* events and revalidate itself.
|
codereview_new_java_data_9892
|
public void navigateWithParameters_afterServerNavigation()
UI ui = new UI();
initUI(ui, "", null);
- Optional<FooBarParamNavigationTarget> newView = ui.navigate(FooBarParamNavigationTarget.class,
new RouteParameters(new RouteParam("fooParam", "flu"),
new RouteParam("barParam", "beer")));
-
- assertEquals(FooBarParamNavigationTarget.class, newView.get().getClass());
assertEquals("foo/flu/beer/bar",
ui.getInternals().getActiveViewLocation().getPath());
I still don't see a test showing the use case.
I propose to create an IT test similar to that one you have in your project, `AnotherView `, set the object to the view and check that the corresponding UI component appears on the page.
Without it, IMO almost no chance to understand why this feature is needed.
public void navigateWithParameters_afterServerNavigation()
UI ui = new UI();
initUI(ui, "", null);
+ Optional<FooBarParamNavigationTarget> newView = ui.navigate(
+ FooBarParamNavigationTarget.class,
new RouteParameters(new RouteParam("fooParam", "flu"),
new RouteParam("barParam", "beer")));
+
+ assertEquals(FooBarParamNavigationTarget.class,
+ newView.get().getClass());
assertEquals("foo/flu/beer/bar",
ui.getInternals().getActiveViewLocation().getPath());
|
codereview_new_java_data_9947
|
default void registerObservationRegistry(ObservationRegistry observationRegistry
}
/**
- * True if this implementation is going to dela with not {@link ObservationRegistry#NOOP} instance.
- * @return true if this implementation is going to dela with not {@link ObservationRegistry#NOOP} instance.
* @since 6.0.1
*/
default boolean isObserved() {
```suggestion
* True if this implementation is going to deal with a registry other than the {@link ObservationRegistry#NOOP} instance.
* @return true if this implementation is going to deal with a registry other than the {@link ObservationRegistry#NOOP} instance.
```
default void registerObservationRegistry(ObservationRegistry observationRegistry
}
/**
+ * True if this implementation is going to deal with a registry other than the {@link ObservationRegistry#NOOP} instance.
+ * @return true if this implementation is going to deal with a registry other than the {@link ObservationRegistry#NOOP} instance.
* @since 6.0.1
*/
default boolean isObserved() {
|
codereview_new_java_data_9948
|
public RouterSpec<K, R> subFlowMapping(K key, IntegrationFlow subFlow) {
* Use the next, after router, parent flow {@link MessageChannel} as a
* {@link AbstractMessageRouter#setDefaultOutputChannel(MessageChannel)} of this router.
* This option also disables {@link AbstractMappingMessageRouter#setChannelKeyFallback(boolean)},
- * if not called explicitly, to skip an attempt to resolve channel name.
* @return the router spec.
* @since 6.0
*/
```suggestion
* if not called explicitly afterwards, to skip an attempt to resolve the channel name.
```
public RouterSpec<K, R> subFlowMapping(K key, IntegrationFlow subFlow) {
* Use the next, after router, parent flow {@link MessageChannel} as a
* {@link AbstractMessageRouter#setDefaultOutputChannel(MessageChannel)} of this router.
* This option also disables {@link AbstractMappingMessageRouter#setChannelKeyFallback(boolean)},
+ * if not called explicitly afterwards, to skip an attempt to resolve the channel name.
* @return the router spec.
* @since 6.0
*/
|
codereview_new_java_data_9949
|
else if (this.metricsCaptor != null) {
private boolean sendWithObservation(Message<?> message, long timeout) {
MutableMessage<?> messageToSend = MutableMessage.of(message);
- MessageSenderContext context = new MessageSenderContext(messageToSend, getComponentName());
return IntegrationObservation.PRODUCER.observation(
this.observationConvention,
DefaultMessageSenderObservationConvention.INSTANCE,
- () -> context,
this.observationRegistry)
.observe(() -> sendInternal(messageToSend, timeout));
}
Unnecessary local variable.
else if (this.metricsCaptor != null) {
private boolean sendWithObservation(Message<?> message, long timeout) {
MutableMessage<?> messageToSend = MutableMessage.of(message);
return IntegrationObservation.PRODUCER.observation(
this.observationConvention,
DefaultMessageSenderObservationConvention.INSTANCE,
+ () -> new MessageSenderContext(messageToSend, getComponentName()),
this.observationRegistry)
.observe(() -> sendInternal(messageToSend, timeout));
}
|
codereview_new_java_data_9950
|
private void registerGatewayProxyInstantiationPostProcessor(BeanDefinitionRegist
if (!registry.containsBeanDefinition("gatewayProxyBeanDefinitionPostProcessor")) {
BeanDefinitionBuilder builder =
BeanDefinitionBuilder.genericBeanDefinition(GatewayProxyInstantiationPostProcessor.class,
- () -> new GatewayProxyInstantiationPostProcessor(registry))
.addConstructorArgValue(registry)
.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
You don't need both of these (instance supplier + constructor arg).
```suggestion
.addConstructorArgValue(registry)
```
private void registerGatewayProxyInstantiationPostProcessor(BeanDefinitionRegist
if (!registry.containsBeanDefinition("gatewayProxyBeanDefinitionPostProcessor")) {
BeanDefinitionBuilder builder =
BeanDefinitionBuilder.genericBeanDefinition(GatewayProxyInstantiationPostProcessor.class,
.addConstructorArgValue(registry)
.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
|
codereview_new_java_data_9951
|
private Object processInternal(ParametersWrapper parameters) {
private synchronized void initialize() {
if (isProvidedMessageHandlerFactoryBean()) {
- LOGGER.trace("Overriding default instance of MessageHandlerMethodFactory with provided one.");
this.messageHandlerMethodFactory =
getBeanFactory()
.getBean(
```suggestion
LOGGER.trace("Overriding default instance of MessageHandlerMethodFactory with the one provided.");
```
private Object processInternal(ParametersWrapper parameters) {
private synchronized void initialize() {
if (isProvidedMessageHandlerFactoryBean()) {
+ LOGGER.trace("Overriding default instance of MessageHandlerMethodFactory with the one provided.");
this.messageHandlerMethodFactory =
getBeanFactory()
.getBean(
|
codereview_new_java_data_9952
|
public void futureVoidReply() throws Exception {
reply.complete(null);
}
catch (InterruptedException ex) {
ReflectionUtils.rethrowRuntimeException(ex);
}
}).start();
`Thread.currentThread.interrupt()` before rethrow.
public void futureVoidReply() throws Exception {
reply.complete(null);
}
catch (InterruptedException ex) {
+ Thread.currentThread.interrupt();
ReflectionUtils.rethrowRuntimeException(ex);
}
}).start();
|
codereview_new_java_data_9953
|
public void destroy() {
if (this.redisMessageListenerContainer != null) {
try {
this.redisMessageListenerContainer.destroy();
}
catch (Exception ex) {
throw new IllegalStateException(ex);
Shouldnt we also set it to null here?
public void destroy() {
if (this.redisMessageListenerContainer != null) {
try {
this.redisMessageListenerContainer.destroy();
+ this.redisMessageListenerContainer = null;
+ this.isRunningRedisMessageListenerContainer = false;
}
catch (Exception ex) {
throw new IllegalStateException(ex);
|
codereview_new_java_data_9954
|
public void processBeanDefinition(String beanName, AnnotatedBeanDefinition beanD
Poller poller = MessagingAnnotationUtils.resolveAttribute(annotations, "poller", Poller.class);
Reactive reactive = MessagingAnnotationUtils.resolveAttribute(annotations, "reactive", Reactive.class);
- Assert.state(reactive == null || poller == null, "The 'poller' and 'reactive' are mutually exclusive.");
if (poller != null) {
applyPollerForEndpoint(endpointBeanDefinition, poller);
}
Either `"'poller' and 'reactive' are mutually exclusive."` or `"The 'poller' and 'reactive' attributes are mutually exclusive."` Also should include the bean name.
public void processBeanDefinition(String beanName, AnnotatedBeanDefinition beanD
Poller poller = MessagingAnnotationUtils.resolveAttribute(annotations, "poller", Poller.class);
Reactive reactive = MessagingAnnotationUtils.resolveAttribute(annotations, "reactive", Reactive.class);
+ Assert.state(reactive == null || poller == null,
+ () -> "The 'poller' and 'reactive' attributes are mutually exclusive." +
+ "The bean definition with the problem is: " + beanName);
if (poller != null) {
applyPollerForEndpoint(endpointBeanDefinition, poller);
}
|
codereview_new_java_data_9955
|
public final class TestingUtilities {
// Non-instantiable utility class
private TestingUtilities() {
- throw new AssertionError();
}
/**
This is `private`, so it cannot be instantiate from the outside of the class.
Even if you do some hardcore via reflection, it still does not harm since there is no any state in these classes to break something.
I'm not sure that is going to be mistake in the framework code to call this ctor directly in this class: we always review changes, so such a code won't pass it to the mainstream.
Please, elaborate on the purpose of this change.
Thanks
public final class TestingUtilities {
// Non-instantiable utility class
private TestingUtilities() {
+ throw new AssertionError(""Class Instantiation not allowed."");
}
/**
|
codereview_new_java_data_9956
|
public void setInterceptorFactoryChain(TcpConnectionInterceptorFactoryChain inte
/**
* 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 setInterceptorFactoryChain(TcpConnectionInterceptorFactoryChain inte
/**
* 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_10110
|
public ScanBuilder caseInsensitive() {
}
public ScanBuilder select(String... selectedColumns) {
- this.tableScan = tableScan.select(ImmutableList.copyOf(selectedColumns));
return this;
}
public ScanBuilder select(Collection<String> columns) {
- this.tableScan = tableScan.select(ImmutableList.copyOf(columns));
return this;
}
Just wondering do we really need a copy of the collection again? Can't we pass the collection directly as the below interface supports it?
https://github.com/apache/iceberg/blob/master/api/src/main/java/org/apache/iceberg/Scan.java#L87
public ScanBuilder caseInsensitive() {
}
public ScanBuilder select(String... selectedColumns) {
+ this.tableScan = tableScan.select(selectedColumns);
return this;
}
public ScanBuilder select(Collection<String> columns) {
+ this.tableScan = tableScan.select(columns);
return this;
}
|
codereview_new_java_data_10111
|
public void testDropBranchDoesNotExist() {
}
@Test
- public void testDropBranchFailesForTag() throws NoSuchTableException {
String tagName = "b1";
Table table = insertRows();
table.manageSnapshots().createTag(tagName, table.currentSnapshot().snapshotId()).commit();
Just noticed typo: Should be `testDropBranchFailsForTag`
public void testDropBranchDoesNotExist() {
}
@Test
+ public void testDropBranchFailsForTag() throws NoSuchTableException {
String tagName = "b1";
Table table = insertRows();
table.manageSnapshots().createTag(tagName, table.currentSnapshot().snapshotId()).commit();
|
codereview_new_java_data_10112
|
public void filter(Filter[] filters) {
.collect(Collectors.toList());
LOG.info(
- "{}/{} tasks for table {} matched runtime file filter",
filteredTasks.size(),
tasks().size(),
- table().name());
resetTasks(filteredTasks);
}
What do you think put filter in this log as well?
public void filter(Filter[] filters) {
.collect(Collectors.toList());
LOG.info(
+ "{} of {} task(s) for table {} matched runtime file filter with {} location(s)",
filteredTasks.size(),
tasks().size(),
+ table().name(),
+ fileLocations.size());
resetTasks(filteredTasks);
}
|
codereview_new_java_data_10113
|
protected Statistics estimateStatistics(Snapshot snapshot) {
// estimate stats using snapshot summary only for partitioned tables
// (metadata tables are unpartitioned)
if (!table.spec().isUnpartitioned() && filterExpressions.isEmpty()) {
- LOG.debug("Using snapshot metadata to estimate statistics for table {}", table.name());
long totalRecords = totalRecords(snapshot);
return new Stats(SparkSchemaUtil.estimateSize(readSchema(), totalRecords), totalRecords);
}
Should we also log snapshot id?
protected Statistics estimateStatistics(Snapshot snapshot) {
// estimate stats using snapshot summary only for partitioned tables
// (metadata tables are unpartitioned)
if (!table.spec().isUnpartitioned() && filterExpressions.isEmpty()) {
+ LOG.debug(
+ "Using snapshot {} metadata to estimate statistics for table {}",
+ snapshot.snapshotId(),
+ table.name());
long totalRecords = totalRecords(snapshot);
return new Stats(SparkSchemaUtil.estimateSize(readSchema(), totalRecords), totalRecords);
}
|
codereview_new_java_data_10114
|
private static CaseInsensitiveStringMap addSnapshotId(
scanOptions.putAll(options.asCaseSensitiveMap());
scanOptions.put(SparkReadOptions.SNAPSHOT_ID, value);
scanOptions.remove(SparkReadOptions.AS_OF_TIMESTAMP);
scanOptions.remove(SparkReadOptions.BRANCH);
return new CaseInsensitiveStringMap(scanOptions);
}
Please revert the whitespace change.
private static CaseInsensitiveStringMap addSnapshotId(
scanOptions.putAll(options.asCaseSensitiveMap());
scanOptions.put(SparkReadOptions.SNAPSHOT_ID, value);
scanOptions.remove(SparkReadOptions.AS_OF_TIMESTAMP);
+
scanOptions.remove(SparkReadOptions.BRANCH);
+ scanOptions.remove(SparkReadOptions.TAG);
return new CaseInsensitiveStringMap(scanOptions);
}
|
codereview_new_java_data_10115
|
private Pair<Table, Long> load(Identifier ident) throws NoSuchTableException {
Preconditions.checkArgument(
Stream.of(snapshotId, asOfTimestamp, branch, tag).filter(Objects::nonNull).count() <= 1,
- "Can specify at most one of snapshot-id (%s), as-of-timestamp (%s), and snapshot-ref (%s)",
snapshotId,
asOfTimestamp,
- branch);
Table table = TABLE_CACHE.get(key);
This can be misleading. It always prints branch, but could be triggered by tag.
private Pair<Table, Long> load(Identifier ident) throws NoSuchTableException {
Preconditions.checkArgument(
Stream.of(snapshotId, asOfTimestamp, branch, tag).filter(Objects::nonNull).count() <= 1,
+ "Can specify only one of snapshot-id (%s), as-of-timestamp (%s), branch (%s), tag (%s)",
snapshotId,
asOfTimestamp,
+ branch,
+ tag);
Table table = TABLE_CACHE.get(key);
|
codereview_new_java_data_10129
|
public void performAction(FeedItem item, Fragment fragment, FeedItemFilter filte
@Override
public boolean willRemove(FeedItemFilter filter, FeedItem item) {
- return filter.showNew;
}
}
\ No newline at end of file
This should be `true`, as the action is only shown on the playback history page and it always removes the episode
public void performAction(FeedItem item, Fragment fragment, FeedItemFilter filte
@Override
public boolean willRemove(FeedItemFilter filter, FeedItem item) {
+ return true;
}
}
\ No newline at end of file
|
codereview_new_java_data_10130
|
public boolean localFileAvailable() {
public long getItemId() {
return itemID;
}
-
@Override
public void onPlaybackStart() {
startPosition = Math.max(position, 0);
Unrelated change, please revert
public boolean localFileAvailable() {
public long getItemId() {
return itemID;
}
@Override
public void onPlaybackStart() {
startPosition = Math.max(position, 0);
|
codereview_new_java_data_10131
|
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
.setTitle(getString(R.string.chapters_label))
.setView(onCreateView(getLayoutInflater()))
.setPositiveButton(getString(R.string.close_label), null) //dismisses
- .setNeutralButton("Reset", null)
- .show();
dialog.show();
dialog.getButton(DialogInterface.BUTTON_NEUTRAL).setOnClickListener(v -> {
controller = new PlaybackController(getActivity()) {
Please use a String resource that can be translated instead of hard-coding a String. I'm pretty sure we already have some `R.string` resource that says "Refresh".
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
.setTitle(getString(R.string.chapters_label))
.setView(onCreateView(getLayoutInflater()))
.setPositiveButton(getString(R.string.close_label), null) //dismisses
+ .setNeutralButton(getString(R.string.refresh_label), null)
+ .create();
dialog.show();
dialog.getButton(DialogInterface.BUTTON_NEUTRAL).setOnClickListener(v -> {
controller = new PlaybackController(getActivity()) {
|
codereview_new_java_data_10132
|
private static void upgrade(int oldVersion, Context context) {
if (feedCounterSetting.equals("0")) {
prefs.edit().putString(UserPreferences.PREF_DRAWER_FEED_COUNTER, "2").apply();
}
- }
- if (oldVersion < 2070095) {
- long value = Long.parseLong(SleepTimerPreferences.lastTimerValue());
- TimeUnit unit = SleepTimerPreferences.UNITS[SleepTimerPreferences.lastTimerTimeUnit()];
- SleepTimerPreferences.setLastTimer(
- String.valueOf(unit.toMinutes(value))
- );
}
}
}
No line breaks needed
```suggestion
SleepTimerPreferences.setLastTimer(String.valueOf(unit.toMinutes(value)));
```
private static void upgrade(int oldVersion, Context context) {
if (feedCounterSetting.equals("0")) {
prefs.edit().putString(UserPreferences.PREF_DRAWER_FEED_COUNTER, "2").apply();
}
+ SharedPreferences sleepTimerPreferences = context.getSharedPreferences(SleepTimerPreferences.PREF_NAME, Context.MODE_PRIVATE);
+ String PREF_TIME_UNIT = "LastTimeUnit";
+ int DEFAULT_TIME_UNIT = 1;
+ TimeUnit[] UNITS = { TimeUnit.SECONDS, TimeUnit.MINUTES, TimeUnit.HOURS };
+ long value = Long.parseLong(SleepTimerPreferences.lastTimerValue());
+ TimeUnit unit = UNITS[sleepTimerPreferences.getInt(PREF_TIME_UNIT, DEFAULT_TIME_UNIT)];
+ SleepTimerPreferences.setLastTimer(String.valueOf(unit.toMinutes(value)));
}
}
}
|
codereview_new_java_data_10133
|
private static void upgrade(int oldVersion, Context context) {
if (oldVersion < 2050000) {
prefs.edit().putBoolean(UserPreferences.PREF_PAUSE_PLAYBACK_FOR_FOCUS_LOSS, true).apply();
}
- if (oldVersion < 2070000) {
// Migrate drawer feed counter setting to reflect removal of
// "unplayed and in inbox" (0), by changing it to "unplayed" (2)
- if (UserPreferences.getFeedCounterSetting().id == 0) {
- UserPreferences.setFeedCounterSetting("2");
}
}
}
I would do the migration manually here, e.g., writing to the SharedPreferences like above. That way, we don't need to keep setters in the "main" code for things that are only ever used when upgrading. When accessing the SharedPreferences directly, you can also remove the enum because you can check the value here without having to "parse" it.
private static void upgrade(int oldVersion, Context context) {
if (oldVersion < 2050000) {
prefs.edit().putBoolean(UserPreferences.PREF_PAUSE_PLAYBACK_FOR_FOCUS_LOSS, true).apply();
}
+ if (oldVersion < 2080000) {
// Migrate drawer feed counter setting to reflect removal of
// "unplayed and in inbox" (0), by changing it to "unplayed" (2)
+ String feedCounterSetting = prefs.getString("prefDrawerFeedIndicator", "1");
+ if (feedCounterSetting.equals("0")) {
+ prefs.edit().putString("prefDrawerFeedIndicator", "2").apply();
}
}
}
|
codereview_new_java_data_10134
|
public void checkImmutableAcl() throws Exception {
}
}
- /**
- * Copied from ZooKeeper 3.8.1,(ZooKeeper.validateACL())[] for stand-alone testing,
- *
- * @see <a
- * href="https://github.com/apache/zookeeper/blob/2e9c3f3ceda90aeb9380acc87b253bf7661b7794/zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeper.java#L3075/>
- */
- boolean validateACL(List<ACL> acl) throws KeeperException.InvalidACLException {
if (acl == null || acl.isEmpty() || acl.contains((Object) null)) {
throw new KeeperException.InvalidACLException();
}
You know, we don't actually need the comments to be javadoc comments for tests. We're not generating javadocs for test code, so you're only going to see these comments looking at the source code. And, in that case, it's easier to omit the HTML and javadoc tags. Also, this method can be private, even if the original wasn't.
```suggestion
// Copied from ZooKeeper 3.8.1 for stand-alone testing here
// https://github.com/apache/zookeeper/blob/2e9c3f3ceda90aeb9380acc87b253bf7661b7794/zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeper.java#L3075/
private boolean validateACL(List<ACL> acl) throws KeeperException.InvalidACLException {
```
Also, the HTML was malformed in yours anyway... you forgot the closing double quote around the URL.
public void checkImmutableAcl() throws Exception {
}
}
+ // Copied from ZooKeeper 3.8.1 for stand-alone testing here
+ // https://github.com/apache/zookeeper/blob/2e9c3f3ceda90aeb9380acc87b253bf7661b7794/zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeper.java#L3075/
+ private boolean validateACL(List<ACL> acl) throws KeeperException.InvalidACLException {
if (acl == null || acl.isEmpty() || acl.contains((Object) null)) {
throw new KeeperException.InvalidACLException();
}
|
codereview_new_java_data_10135
|
public enum Property {
+ " a comma or other reserved characters in a URI use standard URI hex"
+ " encoding. For example replace commas with %2C.",
"1.6.0"),
- INSTANCE_VOLUMES_CONFIG("instance.volumes.config.", null, PropertyType.PREFIX,
"Properties in this category are used to provide volume specific overrides to "
+ "the general filesystem client configuration. Properties using this prefix "
+ "should be in the form "
- + "'instance.volumes.config.<volume-uri>.<property-name>=<property-value>. An "
+ "example: "
+ "'instance.volume.config.hdfs://namespace-a:8020/accumulo.dfs.client.hedged.read.threadpool.size=10'. "
+ "Note that when specifying property names that contain colons in the properties "
Throughout this PR, you are inconsistently switching between `instance.volumes.config` and `instance.volume.config`. Is this singular or plural? Is it intended to apply to one volume only or more than one? I think this needs to be cleaned up throughout.
public enum Property {
+ " a comma or other reserved characters in a URI use standard URI hex"
+ " encoding. For example replace commas with %2C.",
"1.6.0"),
+ INSTANCE_VOLUMES_CONFIG("instance.volume.config.", null, PropertyType.PREFIX,
"Properties in this category are used to provide volume specific overrides to "
+ "the general filesystem client configuration. Properties using this prefix "
+ "should be in the form "
+ + "'instance.volume.config.<volume-uri>.<property-name>=<property-value>. An "
+ "example: "
+ "'instance.volume.config.hdfs://namespace-a:8020/accumulo.dfs.client.hedged.read.threadpool.size=10'. "
+ "Note that when specifying property names that contain colons in the properties "
|
codereview_new_java_data_10136
|
private void compactLocalityGroup(String lgName, Set<ByteSequence> columnFamilie
try {
Thread.sleep(500);
} catch (InterruptedException e) {
- Thread.interrupted();
throw new IllegalStateException(
- "Interrupted while waiting for low memory condition to resolve");
}
})) {}
Why `Thread.interrupted();` to clear the interrupt status flag? I think just catching the InterruptException has the same effect.
The interrupt flag can be (re)set to show the interrupt occurred with `Thread.currentThread().interrupt()`
private void compactLocalityGroup(String lgName, Set<ByteSequence> columnFamilie
try {
Thread.sleep(500);
} catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
throw new IllegalStateException(
+ "Interrupted while waiting for low memory condition to resolve", e);
}
})) {}
|
codereview_new_java_data_10137
|
public synchronized void upgradeZookeeper(ServerContext context,
int oldestVersion = ROOT_TABLET_META_CHANGES;
if (cv < oldestVersion) {
String oldRelease = dataVersionToReleaseName(oldestVersion);
- throw new UnsupportedOperationException("Upgrading from a version before " + oldRelease
+ " data version (" + oldestVersion + ") is not supported. Upgrade to at least "
+ oldRelease + " before upgrading to " + Constants.VERSION);
}
I think "less than" makes more sense here than "before", since "before" could mean chronologically, and we might release a bugfix for an earlier release line after the `.0` version we're expecting. But that bugfix's version would still be "less than" the `.0` version release.
```suggestion
throw new UnsupportedOperationException("Upgrading from a version less than " + oldRelease
```
public synchronized void upgradeZookeeper(ServerContext context,
int oldestVersion = ROOT_TABLET_META_CHANGES;
if (cv < oldestVersion) {
String oldRelease = dataVersionToReleaseName(oldestVersion);
+ throw new UnsupportedOperationException("Upgrading from a version less than " + oldRelease
+ " data version (" + oldestVersion + ") is not supported. Upgrade to at least "
+ oldRelease + " before upgrading to " + Constants.VERSION);
}
|
codereview_new_java_data_10138
|
List<String> readReplFilesFromMetadata(final ServerContext context) {
}
void deleteReplTableFiles(final ServerContext context, final List<String> replTableFiles) {
// write delete mutations
boolean haveFailures = false;
try (BatchWriter writer = context.createBatchWriter(MetadataTable.NAME)) {
you could short-circuit here if `replTableFiles` is empty
List<String> readReplFilesFromMetadata(final ServerContext context) {
}
void deleteReplTableFiles(final ServerContext context, final List<String> replTableFiles) {
+ // short circuit if there are no files
+ if (replTableFiles.isEmpty()) {
+ return;
+ }
// write delete mutations
boolean haveFailures = false;
try (BatchWriter writer = context.createBatchWriter(MetadataTable.NAME)) {
|
codereview_new_java_data_10139
|
public int numArgs() {
}
public static void printClassPath(PrintWriter writer) {
- try {
- writer.print("Accumulo Shell Classpath: \n");
- final String javaClassPath = System.getProperty("java.class.path");
- if (javaClassPath == null) {
- throw new IllegalStateException("java.class.path is not set");
- }
- Arrays.stream(javaClassPath.split(File.pathSeparator)).forEach(classPathUri -> {
- writer.print(classPathUri + "\n");
- });
-
- writer.print("\n");
- } catch (Exception t) {
- throw new RuntimeException(t);
}
}
}
```suggestion
writer.println();
```
public int numArgs() {
}
public static void printClassPath(PrintWriter writer) {
+ writer.println("Accumulo Shell Classpath:");
+ final String javaClassPath = System.getProperty("java.class.path");
+ if (javaClassPath == null) {
+ throw new IllegalStateException("java.class.path is not set");
}
+ Arrays.stream(javaClassPath.split(File.pathSeparator)).forEach(writer::println);
+
+ writer.println();
}
}
|
codereview_new_java_data_10140
|
import org.apache.accumulo.core.tabletingest.thrift.TabletIngestClientService.Client;
public class TabletIngestClientServiceThriftClient extends ThriftClientTypes<Client> {
public TabletIngestClientServiceThriftClient(String serviceName) {
These names are not intuitive on their own. It would be helpful to add a javadoc to explain the scope of these services.
import org.apache.accumulo.core.tabletingest.thrift.TabletIngestClientService.Client;
+/**
+ * Client side object that can be used to interact with services that support ingest operations
+ * against tablets. See {@link TabletIngestClientService$Iface} for a list of supported operations.
+ */
public class TabletIngestClientServiceThriftClient extends ThriftClientTypes<Client> {
public TabletIngestClientServiceThriftClient(String serviceName) {
|
codereview_new_java_data_10141
|
public boolean recoverLogs(KeyExtent extent, Collection<Collection<String>> walo
if (!closeTasksQueued.contains(sortId) && !sortsQueued.contains(sortId)) {
AccumuloConfiguration aconf = manager.getConfiguration();
LogCloser closer = Property.createInstanceFromPropertyName(aconf,
- aconf.resolve(Property.MANAGER_WAL_CLOSER_IMPLEMENTATION), LogCloser.class,
- new HadoopLogCloser());
Long delay = recoveryDelay.get(sortId);
if (delay == null) {
delay = aconf.getTimeInMillis(Property.MANAGER_RECOVERY_DELAY);
another resolve on single property can be simplified; there's a bunch more, but I'll stop mentioning it.
public boolean recoverLogs(KeyExtent extent, Collection<Collection<String>> walo
if (!closeTasksQueued.contains(sortId) && !sortsQueued.contains(sortId)) {
AccumuloConfiguration aconf = manager.getConfiguration();
LogCloser closer = Property.createInstanceFromPropertyName(aconf,
+ Property.MANAGER_WAL_CLOSER_IMPLEMENTATION, LogCloser.class, new HadoopLogCloser());
Long delay = recoveryDelay.get(sortId);
if (delay == null) {
delay = aconf.getTimeInMillis(Property.MANAGER_RECOVERY_DELAY);
|
codereview_new_java_data_10142
|
private ServerContext createMockContext() {
public void test() {
final ServerContext context = createMockContext();
TableConfiguration conf = createMock(TableConfiguration.class);
- // Eclipse might show @SuppressWarnings("removal") as unnecessary.
- // Eclipse is wrong. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=565271
expect(conf.get(Property.TABLE_CLASSLOADER_CONTEXT)).andReturn("").anyTimes();
expect(context.getTableConfiguration(EasyMock.anyObject())).andReturn(conf).anyTimes();
replay(context, conf);
Can we get rid of these comments also?
private ServerContext createMockContext() {
public void test() {
final ServerContext context = createMockContext();
TableConfiguration conf = createMock(TableConfiguration.class);
expect(conf.get(Property.TABLE_CLASSLOADER_CONTEXT)).andReturn("").anyTimes();
expect(context.getTableConfiguration(EasyMock.anyObject())).andReturn(conf).anyTimes();
replay(context, conf);
|
codereview_new_java_data_10143
|
protected FileSKVWriter openWriter(FileOptions options) throws IOException {
if (options.dropCacheBehind) {
EnumSet<CreateFlag> set = EnumSet.of(CreateFlag.SYNC_BLOCK, CreateFlag.CREATE);
outputStream = fs.create(new Path(file), FsPermission.getDefault(), set, bufferSize,
- (short) rep, blockSize, null);
try {
// Tell the DataNode that the file does not need to be cached in the OS page cache
outputStream.setDropBehind(Boolean.TRUE);
`block` is passed to the other call of fs.create(), but not this one. Is there a method that supports that and the perms?
protected FileSKVWriter openWriter(FileOptions options) throws IOException {
if (options.dropCacheBehind) {
EnumSet<CreateFlag> set = EnumSet.of(CreateFlag.SYNC_BLOCK, CreateFlag.CREATE);
outputStream = fs.create(new Path(file), FsPermission.getDefault(), set, bufferSize,
+ (short) rep, block, null);
try {
// Tell the DataNode that the file does not need to be cached in the OS page cache
outputStream.setDropBehind(Boolean.TRUE);
|
codereview_new_java_data_10144
|
public CachableBuilder fsPath(FileSystem fs, Path dataFile, boolean dropCacheBeh
// cache
try {
is.setDropBehind(Boolean.TRUE);
} catch (UnsupportedOperationException e) {
log.debug("setDropBehind not enabled for wal file: {}", dataFile);
} catch (IOException e) {
I was wondering how I could know if this changes was working as intended, thought adding some trace logging that could be flipped on might be useful.
```suggestion
is.setDropBehind(Boolean.TRUE);
log.trace("Called setDropBehind(TRUE) for stream reading file {}", dataFile);
```
public CachableBuilder fsPath(FileSystem fs, Path dataFile, boolean dropCacheBeh
// cache
try {
is.setDropBehind(Boolean.TRUE);
+ log.trace("Called setDropBehind(TRUE) for stream reading file {}", dataFile);
} catch (UnsupportedOperationException e) {
log.debug("setDropBehind not enabled for wal file: {}", dataFile);
} catch (IOException e) {
|
codereview_new_java_data_10145
|
public CompactionStats call() throws IOException, CompactionCanceledException {
// If compaction was cancelled then this may happen due to an
// InterruptedException etc so suppress logging
if (!env.isCompactionEnabled()) {
- log.warn("{}", e.getMessage(), e);
- } else {
log.debug("{}", e.getMessage(), e);
}
}
}
I think you have this backward.
public CompactionStats call() throws IOException, CompactionCanceledException {
// If compaction was cancelled then this may happen due to an
// InterruptedException etc so suppress logging
if (!env.isCompactionEnabled()) {
log.debug("{}", e.getMessage(), e);
+ } else {
+ log.warn("{}", e.getMessage(), e);
}
}
}
|
codereview_new_java_data_10146
|
public void setProperty(String tableName, String property, String value) {
public Map<String,String> modifyProperties(String tableName,
Consumer<Map<String,String>> mapMutator)
throws IllegalArgumentException, ConcurrentModificationException {
- settings.putIfAbsent(tableName, new TreeMap<>());
var map = settings.get(tableName);
mapMutator.accept(map);
return Map.copyOf(map);
```suggestion
settings.computeIfAbsent(tableName, k -> new TreeMap<>());
```
public void setProperty(String tableName, String property, String value) {
public Map<String,String> modifyProperties(String tableName,
Consumer<Map<String,String>> mapMutator)
throws IllegalArgumentException, ConcurrentModificationException {
+ settings.computeIfAbsent(tableName, k -> new TreeMap<>());
var map = settings.get(tableName);
mapMutator.accept(map);
return Map.copyOf(map);
|
codereview_new_java_data_10147
|
public void upgradeZookeeper(ServerContext context) {
createScanServerNodes(context);
}
- private static final AtomicBoolean aclErrorOccurred = new AtomicBoolean(false);
private void validateACLs(ServerContext context) {
final ZooReaderWriter zrw = context.getZooReaderWriter();
final ZooKeeper zk = zrw.getZooKeeper();
final String rootPath = context.getZooKeeperRoot();
```suggestion
private void validateACLs(ServerContext context) {
final AtomicBoolean aclErrorOccurred = new AtomicBoolean(false);
```
Seems like this only used in the method. Wondering if could be declared in the method.
public void upgradeZookeeper(ServerContext context) {
createScanServerNodes(context);
}
private void validateACLs(ServerContext context) {
+ final AtomicBoolean aclErrorOccurred = new AtomicBoolean(false);
final ZooReaderWriter zrw = context.getZooReaderWriter();
final ZooKeeper zk = zrw.getZooKeeper();
final String rootPath = context.getZooKeeperRoot();
|
codereview_new_java_data_10148
|
public ImportDestinationArguments importDirectory(String directory) {
@Override
public TimeType getTimeType(final String tableName) throws TableNotFoundException {
- String tableId = tableIdMap().get(tableName);
- if (tableId == null) {
- throw new TableNotFoundException(null, tableName, "specified table does not exist");
- }
Optional<TabletMetadata> tabletMetadata =
- context.getAmple().readTablets().forTable(TableId.of(tableId))
.fetch(TabletMetadata.ColumnType.TIME).checkConsistency().build().stream().findFirst();
TabletMetadata timeData =
tabletMetadata.orElseThrow(() -> new RuntimeException("Failed to retrieve TimeType"));
May be able to use this function to get the table id and it throws a table not found exception.
```suggestion
TableId tableId = context.getTableId(tableName);
Optional<TabletMetadata> tabletMetadata =
context.getAmple().readTablets().forTable(tableId)
```
public ImportDestinationArguments importDirectory(String directory) {
@Override
public TimeType getTimeType(final String tableName) throws TableNotFoundException {
+ TableId tableId = context.getTableId(tableName);
Optional<TabletMetadata> tabletMetadata =
+ context.getAmple().readTablets().forTable(tableId)
.fetch(TabletMetadata.ColumnType.TIME).checkConsistency().build().stream().findFirst();
TabletMetadata timeData =
tabletMetadata.orElseThrow(() -> new RuntimeException("Failed to retrieve TimeType"));
|
codereview_new_java_data_10149
|
public void report(ScanAttempt.Result result) {
};
}
Map<TabletId,Collection<ScanAttemptImpl>> snapshot() {
final long mutationCounterSnapshot;
Suggest turning the comment you removed at line 114 into a method javadoc. Just so we now the top level goal of the method. This gives a little more context to the comments inside the method.
public void report(ScanAttempt.Result result) {
};
}
+ /**
+ * Creates and returns a snapshot of ScanAttempt objects that were added before this call
+ *
+ * @return a map of TabletId to a collection ScanAttempt objects associated with that TabletId
+ */
Map<TabletId,Collection<ScanAttemptImpl>> snapshot() {
final long mutationCounterSnapshot;
|
codereview_new_java_data_10150
|
private static boolean zookeeperAvailable(ZooReaderWriter zoo) {
/**
* Create the version directory and the instance id path and file. The method tries to create the
* directories and instance id file for all base directories provided unless an IOException is
- * thrown. The IOException is not rethrown, but the method not try to create additional entries
- * and will return false.
*
* @return false if an IOException occurred, true otherwise.
*/
```suggestion
* thrown. If an IOException occurs, this method won't retry and will return false.
*
```
private static boolean zookeeperAvailable(ZooReaderWriter zoo) {
/**
* Create the version directory and the instance id path and file. The method tries to create the
* directories and instance id file for all base directories provided unless an IOException is
+ * thrown. If an IOException occurs, this method won't retry and will return false.
*
* @return false if an IOException occurred, true otherwise.
*/
|
codereview_new_java_data_10151
|
public final void printRecords(Iterable<Entry<Key,Value>> scanner, FormatterConf
}
public static String repeat(String s, int c) {
- return String.valueOf(s).repeat(Math.max(0, c));
}
public void checkTableState() {
```suggestion
return s.repeat(Math.max(0, c));
```
public final void printRecords(Iterable<Entry<Key,Value>> scanner, FormatterConf
}
public static String repeat(String s, int c) {
+ return s.repeat(Math.max(0, c));
}
public void checkTableState() {
|
codereview_new_java_data_10152
|
private final AtomicBoolean keepRunning = new AtomicBoolean(true);
public enum TxInfo {
- REPO_TARGET, AUTO_CLEAN, EXCEPTION, RETURN_VALUE;
}
private class TransactionRunner implements Runnable {
```suggestion
REPO_TARGET, AUTO_CLEAN, EXCEPTION, RETURN_VALUE
```
private final AtomicBoolean keepRunning = new AtomicBoolean(true);
public enum TxInfo {
+ REPO_TARGET, AUTO_CLEAN, EXCEPTION, RETURN_VALUE
}
private class TransactionRunner implements Runnable {
|
codereview_new_java_data_10153
|
private static Set<ByteSequence> getCfSet(Collection<ByteSequence> columnFamilie
if (columnFamilies instanceof Set<?>) {
cfSet = (Set<ByteSequence>) columnFamilies;
} else {
- cfSet = new HashSet<>(columnFamilies);
}
}
return cfSet;
Could do the following, might be better since its a fixed size set that is not later mutated.
```suggestion
cfSet = Set.copyOf(columnFamilies);
```
private static Set<ByteSequence> getCfSet(Collection<ByteSequence> columnFamilie
if (columnFamilies instanceof Set<?>) {
cfSet = (Set<ByteSequence>) columnFamilies;
} else {
+ cfSet = Set.copyOf(columnFamilies);
}
}
return cfSet;
|
codereview_new_java_data_10154
|
private long removeBlipCandidates(GarbageCollectionEnvironment gce,
@VisibleForTesting
/**
- *
*/
protected void ensureAllTablesChecked(Set<TableId> tableIdsBefore, Set<TableId> tableIdsSeen,
Set<TableId> tableIdsAfter) {
// if a table was added or deleted during this run, it is acceptable to not
// have seen those tables ids when scanning the metadata table. So get the intersection
- Set<TableId> tableIdsMustHaveSeen = new HashSet<>(tableIdsBefore);
tableIdsMustHaveSeen.retainAll(tableIdsAfter);
if (tableIdsMustHaveSeen.isEmpty() && !tableIdsSeen.isEmpty()) {
Should put something here...
```suggestion
/**
* Double check no tables were missed during GC.
*/
```
private long removeBlipCandidates(GarbageCollectionEnvironment gce,
@VisibleForTesting
/**
+ * Double check no tables were missed during GC
*/
protected void ensureAllTablesChecked(Set<TableId> tableIdsBefore, Set<TableId> tableIdsSeen,
Set<TableId> tableIdsAfter) {
// if a table was added or deleted during this run, it is acceptable to not
// have seen those tables ids when scanning the metadata table. So get the intersection
+ final Set<TableId> tableIdsMustHaveSeen = new HashSet<>(tableIdsBefore);
tableIdsMustHaveSeen.retainAll(tableIdsAfter);
if (tableIdsMustHaveSeen.isEmpty() && !tableIdsSeen.isEmpty()) {
|
codereview_new_java_data_10155
|
public long getCandidatesStat() {
return candidates;
}
- @Override
- public boolean isRootTable() {
- return level == DataLevel.ROOT;
- }
-
- @Override
- public boolean isMetadataTable() {
- return level == DataLevel.METADATA;
- }
-
@Override
public Set<TableId> getCandidateTableIDs() {
- if (isRootTable()) {
return Collections.singleton(MetadataTable.ID);
- } else if (isMetadataTable()) {
Set<TableId> tableIds = new HashSet<>(getTableIDs());
tableIds.remove(MetadataTable.ID);
tableIds.remove(RootTable.ID);
It would be nice to remove these if possible, seems like they are only used in test. Could just make test override/implement the method to get table ids. If it is needed for test I would suggest adding a getDataLevel() method.
```suggestion
```
public long getCandidatesStat() {
return candidates;
}
@Override
public Set<TableId> getCandidateTableIDs() {
+ if (level == DataLevel.ROOT) {
return Collections.singleton(MetadataTable.ID);
+ } else if (level == DataLevel.METADATA) {
Set<TableId> tableIds = new HashSet<>(getTableIDs());
tableIds.remove(MetadataTable.ID);
tableIds.remove(RootTable.ID);
|
codereview_new_java_data_10156
|
import static org.apache.accumulo.server.gc.GcVolumeUtil.ALL_VOLUMES_PREFIX;
-import java.util.Objects;
-
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.data.TableId;
-import org.apache.accumulo.core.gc.ReferenceDirectory;
import org.apache.accumulo.core.metadata.schema.MetadataSchema;
import org.apache.hadoop.fs.Path;
/**
* A specially encoded GC Reference to a directory with the {@link GcVolumeUtil#ALL_VOLUMES_PREFIX}
*/
-public class AllVolumesDirectory extends ReferenceDirectory {
public AllVolumesDirectory(TableId tableId, String dirName) {
- super(tableId, dirName);
- this.metadataEntry = getDeleteTabletOnAllVolumesUri(tableId, dirName);
}
- private String getDeleteTabletOnAllVolumesUri(TableId tableId, String dirName) {
MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(dirName);
- String metadataEntry = ALL_VOLUMES_PREFIX + Constants.TABLE_DIR + Path.SEPARATOR + tableId
- + Path.SEPARATOR + dirName;
- return Objects.requireNonNull(metadataEntry);
}
@Override
I am trying to figure out why this extends reference. Does not seem it is used as a reference in the GC algorithm. Seems that `GCRun.getReferences()` will never return this type. Conceptually I think the ALL_VOLUMES_PREFIX type is a special type of GC candidate, but not a reference. I am still poking around in the code trying to understand the larger context, will circle back to it in the morning.
import static org.apache.accumulo.server.gc.GcVolumeUtil.ALL_VOLUMES_PREFIX;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.data.TableId;
+import org.apache.accumulo.core.gc.ReferenceFile;
import org.apache.accumulo.core.metadata.schema.MetadataSchema;
import org.apache.hadoop.fs.Path;
/**
* A specially encoded GC Reference to a directory with the {@link GcVolumeUtil#ALL_VOLUMES_PREFIX}
*/
+public class AllVolumesDirectory extends ReferenceFile {
public AllVolumesDirectory(TableId tableId, String dirName) {
+ super(tableId, getDeleteTabletOnAllVolumesUri(tableId, dirName));
}
+ private static String getDeleteTabletOnAllVolumesUri(TableId tableId, String dirName) {
MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(dirName);
+ return ALL_VOLUMES_PREFIX + Constants.TABLE_DIR + Path.SEPARATOR + tableId + Path.SEPARATOR
+ + dirName;
}
@Override
|
codereview_new_java_data_10217
|
import com.nawforce.apexparser.ApexLexer;
-@Deprecated
@InternalApi
-public final class ApexCommentBuilder {
private final SourceCodePositioner sourceCodePositioner;
private final CommentInformation commentInfo;
Since this is a new class, we can directly create this in an "internal" package, e.g. `net.sourceforge.pmd.lang.apex.ast.internal`.
The `@InternalApi` annotation is correct. If it is in the internal package, I think, we don't need the `@Deprecated` annotation - IIRC we used that to mark existing classes as internal (which could have been used before we marked it as internal).
import com.nawforce.apexparser.ApexLexer;
@InternalApi
+final class ApexCommentBuilder {
private final SourceCodePositioner sourceCodePositioner;
private final CommentInformation commentInfo;
|
codereview_new_java_data_10218
|
public List<JFieldSymbol> getDeclaredFields() {
@Override
public PSet<SymAnnot> getDeclaredAnnotations() {
- return SymbolResolutionPass.getSymbolicAnnotations(node);
}
@Override
todo maybe make the modifierList cache them.
public List<JFieldSymbol> getDeclaredFields() {
@Override
public PSet<SymAnnot> getDeclaredAnnotations() {
+ return node.getSymbolicAnnotations();
}
@Override
|
codereview_new_java_data_10219
|
final class BoxedPrimitive extends ClassTypeImpl {
@Override
public JClassType withAnnotations(PSet<SymAnnot> newTypeAnnots) {
- if (newTypeAnnots.equals(this.getTypeAnnotations())) {
return this;
}
return new BoxedPrimitive(
```suggestion
if (newTypeAnnots.isEmpty() && this.getTypeAnnotations().isEmpty()) {
```
final class BoxedPrimitive extends ClassTypeImpl {
@Override
public JClassType withAnnotations(PSet<SymAnnot> newTypeAnnots) {
+ if (newTypeAnnots.isEmpty() && this.getTypeAnnotations().isEmpty()) {
return this;
}
return new BoxedPrimitive(
|
codereview_new_java_data_10220
|
private boolean validateCRUDCheckPresent(final ApexNode<?> node, final Object da
addViolation(data, node);
return true;
}
- if (isImproperDMLCheck && userMode) {
- addViolation(data, node);
- return true;
- }
- if (isImproperDMLCheck && systemMode) {
addViolation(data, node);
return true;
}
```suggestion
addViolationWithMessage(data, node, "This CRUD statement uses explicit system mode");
```
private boolean validateCRUDCheckPresent(final ApexNode<?> node, final Object da
addViolation(data, node);
return true;
}
+ if (isImproperDMLCheck && !userMode && !systemMode) {
addViolation(data, node);
return true;
}
|
codereview_new_java_data_10221
|
private boolean validateCRUDCheckPresent(final ApexNode<?> node, final Object da
addViolation(data, node);
return true;
}
- if (isImproperDMLCheck && userMode) {
- addViolation(data, node);
- return true;
- }
- if (isImproperDMLCheck && systemMode) {
addViolation(data, node);
return true;
}
```suggestion
if (isImproperDMLCheck && !userMode && !systemMode) {
```
If I understand it correctly, using "User Mode" is good and should not be flagged. So, only if it is neither user mode nor system mode specified, then Apex uses the defaults, which is elevated system mode, which is bad.
private boolean validateCRUDCheckPresent(final ApexNode<?> node, final Object da
addViolation(data, node);
return true;
}
+ if (isImproperDMLCheck && !userMode && !systemMode) {
addViolation(data, node);
return true;
}
|
codereview_new_java_data_10222
|
public enum CliExitCode {
* This is exit code {@code 1}.
*/
ERROR(1),
- // Todo
USAGE_ERROR(2),
/**
* No errors, but PMD found violations. This is exit code {@code 4}.
```suggestion
/*
* Indicates a problem with the CLI parameters: either a required
* parameter is missing or an invalid parameter was provided.
*/
```
public enum CliExitCode {
* This is exit code {@code 1}.
*/
ERROR(1),
+ /**
+ * Indicates a problem with the CLI parameters: either a required
+ * parameter is missing or an invalid parameter was provided.
+ */
USAGE_ERROR(2),
/**
* No errors, but PMD found violations. This is exit code {@code 4}.
|
codereview_new_java_data_10223
|
public class ClassNamingConventionsRule extends AbstractNamingConventionRule<AST
private final PropertyDescriptor<Pattern> utilityClassRegex = defaultProp("utility class").build();
private final PropertyDescriptor<Pattern> testClassRegex = defaultProp("test class")
.desc("Regex which applies to test class names. Since PMD 6.52.0.")
- .defaultValue("[A-Z][a-zA-Z0-9]*Test").build();
public ClassNamingConventionsRule() {
We probably should change the pattern:
> The class name 'AfterAdviceFirstTests' doesn't match '[A-Z][a-zA-Z0-9]*Test'
```suggestion
.defaultValue("[A-Z][a-zA-Z0-9]*Tests?").build();
```
public class ClassNamingConventionsRule extends AbstractNamingConventionRule<AST
private final PropertyDescriptor<Pattern> utilityClassRegex = defaultProp("utility class").build();
private final PropertyDescriptor<Pattern> testClassRegex = defaultProp("test class")
.desc("Regex which applies to test class names. Since PMD 6.52.0.")
+ .defaultValue("[A-Z][a-zA-Z0-9]*Tests?").build();
public ClassNamingConventionsRule() {
|
codereview_new_java_data_10224
|
public class ASTArrayLoadExpression extends AbstractApexNode.Single<ArrayExpression> {
- @Deprecated
- @InternalApi
- public ASTArrayLoadExpression(ArrayExpression arrayExpression) {
super(arrayExpression);
}
Just FYI: The constructor is deprecated+internal API because it should have been actually package private - only be called by the tree builder.
Since we are changing here the API anyway, anyone who currently creates manually AST nodes would need to adapt their code when switching to summit.
Maybe we can clean this up at the end and make this constructors package private (a task for the doc)? I'm not entirely clear about the consequences yet...
public class ASTArrayLoadExpression extends AbstractApexNode.Single<ArrayExpression> {
+ ASTArrayLoadExpression(ArrayExpression arrayExpression) {
super(arrayExpression);
}
|
codereview_new_java_data_10225
|
public Object visit(ASTMethod node, Object data) {
}
private Object checkForRunAsStatements(ApexNode<?> node, Object data) {
- final List<ASTBlockStatement> blockStatements = node.findDescendantsOfType(ASTBlockStatement.class);
- final List<ASTRunAsBlockStatement> runAsStatements = new ArrayList<>();
-
- for (ASTBlockStatement blockStatement : blockStatements) {
- runAsStatements.addAll(blockStatement.findDescendantsOfType(ASTRunAsBlockStatement.class));
- }
if (!!runAsStatements.isEmpty()) {
addViolation(data, node);
```suggestion
if (runAsStatements.isEmpty()) {
```
This actually causes the build to fail:
> [INFO] PMD Failure: net.sourceforge.pmd.lang.apex.rule.bestpractices.ApexUnitTestClassShouldHaveRunAsRule:40 Rule:AvoidMultipleUnaryOperators Priority:1 Using multiple unary operators may be a bug, and/or is confusing..
public Object visit(ASTMethod node, Object data) {
}
private Object checkForRunAsStatements(ApexNode<?> node, Object data) {
+ final List<ASTRunAsBlockStatement> runAsStatements = node.findDescendantsOfType(ASTRunAsBlockStatement.class);
if (!!runAsStatements.isEmpty()) {
addViolation(data, node);
|
codereview_new_java_data_10226
|
private static String getUnixExample() {
return "For example on *nix: " + PMD.EOL
+ launchCmd + " -dir /home/workspace/src/main/java/code -f html -rulesets rulesets/java/quickstart.xml,category/java/codestyle.xml" + PMD.EOL
+ launchCmd + " -d ./src/main/java/code -R rulesets/java/quickstart.xml -f xslt -property xsltFilename=my-own.xsl" + PMD.EOL
- + launchCmd + " -d ./src/main/java/code -R rulesets/java/quickstart.xml -f xslt -property xsltFilename=pmd-report-v2.xslt" + PMD.EOL
- + " - pmd-report-v2.xslt is at https://github.com/pmd/pmd/tree/master/pmd-core/etc/xslt/pmd-report-v2.xslt"
+ launchCmd + " -d ./src/main/java/code -f html -R rulesets/java/quickstart.xml -auxclasspath commons-collections.jar:derby.jar" + PMD.EOL;
}
```suggestion
+ launchCmd + " -d ./src/main/java/code -R rulesets/java/quickstart.xml -f xslt -property xsltFilename=html-report-v2.xslt" + PMD.EOL
+ " - html-report-v2.xslt is at https://github.com/pmd/pmd/tree/master/pmd-core/etc/xslt/html-report-v2.xslt"
```
private static String getUnixExample() {
return "For example on *nix: " + PMD.EOL
+ launchCmd + " -dir /home/workspace/src/main/java/code -f html -rulesets rulesets/java/quickstart.xml,category/java/codestyle.xml" + PMD.EOL
+ launchCmd + " -d ./src/main/java/code -R rulesets/java/quickstart.xml -f xslt -property xsltFilename=my-own.xsl" + PMD.EOL
+ + launchCmd + " -d ./src/main/java/code -R rulesets/java/quickstart.xml -f xslt -property xsltFilename=html-report-v2.xslt" + PMD.EOL
+ + " - html-report-v2.xslt is at https://github.com/pmd/pmd/tree/master/pmd-core/etc/xslt/html-report-v2.xslt"
+ launchCmd + " -d ./src/main/java/code -f html -R rulesets/java/quickstart.xml -auxclasspath commons-collections.jar:derby.jar" + PMD.EOL;
}
|
codereview_new_java_data_10227
|
private void report(CPD cpd) throws ReportException {
log("No duplicates over " + minimumTokenCount + " tokens found", Project.MSG_INFO);
}
CPDReportRenderer renderer = createRenderer();
- CPDReport report = new CPDReport(cpd.getMatches(), cpd.getNumberOfTokensPerFile());
try {
// will be closed via BufferedWriter/OutputStreamWriter chain down below
I think it would be nicer to make a method on `CPD` that encapsulates that:
```suggestion
CPDReport report = cpd.toReport();
```
private void report(CPD cpd) throws ReportException {
log("No duplicates over " + minimumTokenCount + " tokens found", Project.MSG_INFO);
}
CPDReportRenderer renderer = createRenderer();
+ CPDReport report = cpd.toReport();
try {
// will be closed via BufferedWriter/OutputStreamWriter chain down below
|
codereview_new_java_data_10228
|
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
public class CPDReport {
private final Iterator<Match> matches;
private final Map<String, Integer> numberOfTokensPerFile;
CPDReport(final Iterator<Match> matches, final Map<String, Integer> numberOfTokensPerFile) {
this.matches = matches;
- this.numberOfTokensPerFile = numberOfTokensPerFile;
}
public Iterator<Match> getMatches() {
return matches;
}
public Map<String, Integer> getNumberOfTokensPerFile() {
- return Collections.unmodifiableMap(numberOfTokensPerFile);
}
}
The unmodifiable map can be created once in the constructor, then we have a simple getter here.
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
+import java.util.TreeMap;
public class CPDReport {
private final Iterator<Match> matches;
private final Map<String, Integer> numberOfTokensPerFile;
CPDReport(final Iterator<Match> matches, final Map<String, Integer> numberOfTokensPerFile) {
this.matches = matches;
+ this.numberOfTokensPerFile = Collections.unmodifiableMap(new TreeMap<>(numberOfTokensPerFile));
}
public Iterator<Match> getMatches() {
return matches;
}
public Map<String, Integer> getNumberOfTokensPerFile() {
+ return numberOfTokensPerFile;
}
}
|
codereview_new_java_data_10229
|
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
public class CPDReport {
private final Iterator<Match> matches;
private final Map<String, Integer> numberOfTokensPerFile;
CPDReport(final Iterator<Match> matches, final Map<String, Integer> numberOfTokensPerFile) {
this.matches = matches;
- this.numberOfTokensPerFile = numberOfTokensPerFile;
}
public Iterator<Match> getMatches() {
return matches;
}
public Map<String, Integer> getNumberOfTokensPerFile() {
- return Collections.unmodifiableMap(numberOfTokensPerFile);
}
}
Since we are defining this new useful class: I find it rather unusual, to return an Iterator (I know, that's what CPD used to do)
Should we rather return a List here? In order to not change more files (CPD, MatchAlgorithm, ...), we could simply iterate through the matches in the constructor for now and create a new (unmodifiable) list in this class...
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
+import java.util.TreeMap;
public class CPDReport {
private final Iterator<Match> matches;
private final Map<String, Integer> numberOfTokensPerFile;
CPDReport(final Iterator<Match> matches, final Map<String, Integer> numberOfTokensPerFile) {
this.matches = matches;
+ this.numberOfTokensPerFile = Collections.unmodifiableMap(new TreeMap<>(numberOfTokensPerFile));
}
public Iterator<Match> getMatches() {
return matches;
}
public Map<String, Integer> getNumberOfTokensPerFile() {
+ return numberOfTokensPerFile;
}
}
|
codereview_new_java_data_10230
|
import java.io.IOException;
import java.io.Writer;
import net.sourceforge.pmd.cpd.CPDReport;
public class CPDRendererAdapter implements CPDReportRenderer {
private final CPDRenderer renderer;
I'll mark this as internal API, since this is just a utility for us to avoid changing all renderers now (which we eventually have to do anyway).
import java.io.IOException;
import java.io.Writer;
+import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.cpd.CPDReport;
+/**
+ * Adapter to convert an old {@link CPDRenderer} into a {@link CPDReportRenderer}.
+ *
+ * @deprecated This is internal API. If you want to write your own renderer, directly implement
+ * {@link CPDReportRenderer}.
+ */
+@Deprecated
+@InternalApi
public class CPDRendererAdapter implements CPDReportRenderer {
private final CPDRenderer renderer;
|
codereview_new_java_data_10364
|
public FilamentTask() {
}
@Internal
- public FilamentExtension getExtension() {
return FilamentExtension.get(getProject());
}
}
```suggestion
protected FilamentExtension getExtension() {
```
(Assuming it compiles ofc)
public FilamentTask() {
}
@Internal
+ protected FilamentExtension getExtension() {
return FilamentExtension.get(getProject());
}
}
|
codereview_new_java_data_10541
|
public void onCatalystInstanceDestroy() {
}
private static boolean isRunningOnEmulator() {
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
Can you add a comment explaining where this code comes from? I think it would be good to find a way to derive this from `react-native-device-info`, but I realize that may not be so practically done.
public void onCatalystInstanceDestroy() {
}
private static boolean isRunningOnEmulator() {
+ // This list matched the list in package 'react-native-device-info' (see RNDeviceInfo/RNDeviceModule.java@isEmulatorSync)
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|
codereview_new_java_data_10587
|
public static void main(String[] args) {
propertyStringList.setValue(0, "Output0");
System.out.println(propertyStringList.toString());
System.out.println("Test finished!");
System.exit(0);
}
catch(IOException ex){
It doesn't look like there's an output named "Output0". What is the expected result here: should it throw?
public static void main(String[] args) {
propertyStringList.setValue(0, "Output0");
System.out.println(propertyStringList.toString());
System.out.println("Test finished!");
+ assert propertyStringList.getValue(0).equals("Output0");
System.exit(0);
}
catch(IOException ex){
|
codereview_new_java_data_10920
|
public class OutputSchema implements Extension {
public static final String OUTPUT_SCHEMA = "workflow-output-schema";
// this data structure will be removed when migrating to 0.9, but for now it makes sense to reuse it rather than creating a new one
// see https://github.com/serverlessworkflow/specification/pull/696
private DataInputSchema outputSchema;
// this is a bug in workflow sdk, see https://github.com/serverlessworkflow/sdk-java/pull/207
@JsonProperty("extensionid")
Can you add your issue link on SW side?
public class OutputSchema implements Extension {
public static final String OUTPUT_SCHEMA = "workflow-output-schema";
// this data structure will be removed when migrating to 0.9, but for now it makes sense to reuse it rather than creating a new one
// see https://github.com/serverlessworkflow/specification/pull/696
+ @SuppressWarnings("squid:S1700")
private DataInputSchema outputSchema;
// this is a bug in workflow sdk, see https://github.com/serverlessworkflow/sdk-java/pull/207
@JsonProperty("extensionid")
|
codereview_new_java_data_10921
|
<T extends Model> ProcessInstance<T> createProcessInstance(Process<T> process, S
<T extends MappableToModel<R>, R> Optional<R> delete(Process<T> process, String id);
- <T extends MappableToModel<P>, P extends MappableToModel<R>, R> Optional<R> update(Process<P> process, String id, T resource);
- <T extends MappableToModel<P>, P extends MappableToModel<R>, R> Optional<R> updatePartial(Process<P> process, String id, T resource);
<T extends Model> Optional<List<WorkItem>> getTasks(Process<T> process, String id, SecurityPolicy policy);
With this change, we are removing from swagger generation JsonNodeModel
<T extends Model> ProcessInstance<T> createProcessInstance(Process<T> process, S
<T extends MappableToModel<R>, R> Optional<R> delete(Process<T> process, String id);
+ <T extends MappableToModel<R>, R> Optional<R> update(Process<T> process, String id, T resource);
+ <T extends MappableToModel<R>, R> Optional<R> updatePartial(Process<T> process, String id, T resource);
<T extends Model> Optional<List<WorkItem>> getTasks(Process<T> process, String id, SecurityPolicy policy);
|
codereview_new_java_data_10922
|
public static void mergeSchemas(OpenAPI targetSchema, Collection<OpenAPI> srcSch
}
}
- private static final Optional<SwaggerSchemaProvider> getSchemaSupplier(Optional<WorkflowModelValidator> validator) {
return validator.filter(SwaggerSchemaProvider.class::isInstance).map(SwaggerSchemaProvider.class::cast);
}
```suggestion
private static Optional<SwaggerSchemaProvider> getSchemaSupplier(Optional<WorkflowModelValidator> validator) {
```
public static void mergeSchemas(OpenAPI targetSchema, Collection<OpenAPI> srcSch
}
}
+ private static Optional<SwaggerSchemaProvider> getSchemaSupplier(Optional<WorkflowModelValidator> validator) {
return validator.filter(SwaggerSchemaProvider.class::isInstance).map(SwaggerSchemaProvider.class::cast);
}
|
codereview_new_java_data_10923
|
public final class ServerlessWorkflowOASFilter implements OASFilter {
- private Collection<OpenAPI> schemasInfo;
public ServerlessWorkflowOASFilter(Collection<OpenAPI> schemasInfo) {
this.schemasInfo = schemasInfo;
```suggestion
private final Collection<OpenAPI> schemasInfo;
```
public final class ServerlessWorkflowOASFilter implements OASFilter {
+ private final Collection<OpenAPI> schemasInfo;
public ServerlessWorkflowOASFilter(Collection<OpenAPI> schemasInfo) {
this.schemasInfo = schemasInfo;
|
codereview_new_java_data_10924
|
private String addNashornJavaScriptEngineIfNecessary(String cp) {
}
private boolean requiresNashornJavaScriptEngine() {
- String version = System.getProperty("java.specification.version");
- if (version.startsWith("1.")) {
- version = version.substring(2);
- }
- return Integer.parseInt(version) >= 15; // Nashorn was removed in Java 15
}
}
You can use `getJavaVersion()` here.
private String addNashornJavaScriptEngineIfNecessary(String cp) {
}
private boolean requiresNashornJavaScriptEngine() {
+ return getJavaVersion() >= 15; // Nashorn was removed in Java 15
}
}
|
codereview_new_java_data_10925
|
public final Index addIndex(SessionLocal session, String indexName, int indexId,
@Override
public final boolean isView() {
- return false;
}
@Override
This method should return `true`, otherwise this view with its definition will not be listed in `INFORMATION_SCHEMA.VIEWS`.
public final Index addIndex(SessionLocal session, String indexName, int indexId,
@Override
public final boolean isView() {
+ return true;
}
@Override
|
codereview_new_java_data_10926
|
public Database(ConnectionInfo ci, String cipher) {
this.filePasswordHash = ci.getFilePasswordHash();
this.databaseName = databaseName;
this.databaseShortName = parseDatabaseShortName();
- this.maxLengthInplaceLob = persistent ? Constants.DEFAULT_MAX_LENGTH_INPLACE_LOB : Integer.MAX_VALUE;
this.cipher = cipher;
this.autoServerMode = ci.getProperty("AUTO_SERVER", false);
this.autoServerPort = ci.getProperty("AUTO_SERVER_PORT", 0);
`new byte[Integer.MAX_VALUE` throws `java.lang.OutOfMemoryError: Requested array size exceeds VM limit`.
At least in some JVMs maximum length of `byte[]` is `Integer.MAX_VALUE - 2`, but in sources of Java `Integer.MAX_VALUE - 8 ` is used in `ByteArrayOutputStream` and other places, because actual limit may differ between JVMs.
public Database(ConnectionInfo ci, String cipher) {
this.filePasswordHash = ci.getFilePasswordHash();
this.databaseName = databaseName;
this.databaseShortName = parseDatabaseShortName();
+ this.maxLengthInplaceLob = persistent ? Constants.DEFAULT_MAX_LENGTH_INPLACE_LOB : Integer.MAX_VALUE - 8;
this.cipher = cipher;
this.autoServerMode = ci.getProperty("AUTO_SERVER", false);
this.autoServerPort = ci.getProperty("AUTO_SERVER_PORT", 0);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.