id
stringlengths
23
26
content
stringlengths
182
2.49k
codereview_java_data_7686
activeNotifications.remove(holder); int notificationId = holder.notificationId; - notificationIdsInUse.delete(notificationId); if (!additionalNotifications.isEmpty()) { NotificationContent newContent = additionalNotifications.removeFirst(); All other places that access `notificationIdsInUse` are in methods with descriptive names. We should do the same here. Maybe `markNotificationIdAsFree()`? activeNotifications.remove(holder); int notificationId = holder.notificationId; + markNotificationIdAsFree(notificationId); if (!additionalNotifications.isEmpty()) { NotificationContent newContent = additionalNotifications.removeFirst();
codereview_java_data_7689
package net.fabricmc.yarn.constants; /** - * Constants of World Event IDs.<br> * World Events are used to trigger things on the client from the server side. - * Most commonly, playing sound events or spawning particles.<br> * Some events have an extra data integer sent alongside them.<br> - * Some events are global, meaning they will be sent to every player regardless of their position.<br> * Events are sent from the server to the client using {@link net.minecraft.network.packet.s2c.play.WorldEventS2CPacket WorldEventS2CPacket}, * received on the client by {@link net.minecraft.client.network.ClientPlayNetworkHandler#onWorldEvent(net.minecraft.network.packet.s2c.play.WorldEventS2CPacket) ClientPlayNetworkHandler#onWorldEvent}, * synced by {@link net.minecraft.client.world.ClientWorld#syncWorldEvent(net.minecraft.entity.player.PlayerEntity, int, net.minecraft.util.math.BlockPos, int) ClientWorld#syncWorldEvent} and `<p>` would be better than `<br>` here. (Also possibly when separating the 2nd description line of the individual constants from the "called by" sections) package net.fabricmc.yarn.constants; /** + * Constants of World Event IDs.<p> * World Events are used to trigger things on the client from the server side. + * Most commonly, playing sound events or spawning particles.<p> * Some events have an extra data integer sent alongside them.<br> + * Some events are global, meaning they will be sent to every player regardless of their position.<p> * Events are sent from the server to the client using {@link net.minecraft.network.packet.s2c.play.WorldEventS2CPacket WorldEventS2CPacket}, * received on the client by {@link net.minecraft.client.network.ClientPlayNetworkHandler#onWorldEvent(net.minecraft.network.packet.s2c.play.WorldEventS2CPacket) ClientPlayNetworkHandler#onWorldEvent}, * synced by {@link net.minecraft.client.world.ClientWorld#syncWorldEvent(net.minecraft.entity.player.PlayerEntity, int, net.minecraft.util.math.BlockPos, int) ClientWorld#syncWorldEvent} and
codereview_java_data_7694
BigInteger bi = new BigInteger(sqlCommand.substring(start, i)); if (bi.compareTo(ValueLong.MAX_BI) <= 0) { // parse constants like "10000000L" - if (chars[i] == 'L') { parseIndex++; } currentValue = ValueLong.get(bi.longValue()); did you perhaps not mean to use the same thing here? i.e. skipping substring? BigInteger bi = new BigInteger(sqlCommand.substring(start, i)); if (bi.compareTo(ValueLong.MAX_BI) <= 0) { // parse constants like "10000000L" + c = chars[i]; + if (c == 'L' || c == 'l') { parseIndex++; } currentValue = ValueLong.get(bi.longValue());
codereview_java_data_7702
} /** - * Return the tags associated with the snapshot, or null if no tag is associated with the snapshot. - * @return tags associated with the snapshot, or null if no tag is associated with the snapshot. */ default List<String> tags() { return null; Nit: 'if no tags are' } /** + * Return the tags associated with the snapshot, or null if no tags are associated with the snapshot. + * @return tags associated with the snapshot, or null if no tags are associated with the snapshot. */ default List<String> tags() { return null;
codereview_java_data_7705
import javax.jws.WebService; /** - * A simple example of how to setup a JAX-WS Web Service. - * It can say hello to everyone or to someone in particular. * * @author lnewson@redhat.com */ -@WebService(targetNamespace="http://www.jboss.com/jbossas/quickstarts/wshelloworld/HelloWorld") public interface HelloWorldService { /** This is certainly the wrong namespace to use, jboss.com has been retired. Do we have guidelines about what namespaces should be used for web services? I guess ideally we would use a URN here, or possibly an example domain like acme. import javax.jws.WebService; /** + * A simple example of how to setup a JAX-WS Web Service. It can say hello to everyone or to someone in particular. * * @author lnewson@redhat.com */ +@WebService(targetNamespace = "http://www.jboss.org/jbossas/quickstarts/wshelloworld/HelloWorld") public interface HelloWorldService { /**
codereview_java_data_7711
* @return the current instance * @since 2.0.0 */ - public MiniAccumuloConfig setClasspathItems(String... classpathItems) { impl.setClasspathItems(classpathItems); return this; } Could call this `setClasspath` and drop `Items`. I don't think `Items` adds any useful information. * @return the current instance * @since 2.0.0 */ + public MiniAccumuloConfig setClasspath(String... classpathItems) { impl.setClasspathItems(classpathItems); return this; }
codereview_java_data_7719
* same UUID is found in the settings file.<br> * <strong>Note:</strong> This can have side-effects we currently don't handle, e.g. * changing the account type from IMAP to POP3. So don't use this for now! - * @param outboxName - * localised name of outbox folder - * * @return An {@link ImportResults} instance containing information about errors and * successfully imported accounts. * Passing a localized outbox name feels wrong. Since we never use it anyway, I'd say we use a constant `Account.OUTBOX_NAME` with the value "Outbox". * same UUID is found in the settings file.<br> * <strong>Note:</strong> This can have side-effects we currently don't handle, e.g. * changing the account type from IMAP to POP3. So don't use this for now! * @return An {@link ImportResults} instance containing information about errors and * successfully imported accounts. *
codereview_java_data_7724
} /** - * Returns the bootstrapped {@code JetInstance}. The instance will automatically - * be shutdown once the {@code main()} method of the JAR returns. */ public static JetInstance getInstance() { return SUPPLIER.get().instance; "will be automatically shut down" } /** + * Returns the bootstrapped {@code JetInstance}. The instance will be + * automatically shut down once the {@code main()} method of the JAR returns. */ public static JetInstance getInstance() { return SUPPLIER.get().instance;
codereview_java_data_7727
private NotificationWorkerFragment mNotificationWorkerFragment; private RVRendererAdapter<Notification> adapter; private List<Notification> notificationList; - public static boolean isarchivedvisible = false; MenuItem notificationmenuitem; - Toolbar toolbar; TextView nonotificationtext; @Override Remove this static variable. There should be no need to maintain this here. If you really need this then make it `private`. Do not use it outside of the activity. :) private NotificationWorkerFragment mNotificationWorkerFragment; private RVRendererAdapter<Notification> adapter; private List<Notification> notificationList; + private boolean isarchivedvisible = false; MenuItem notificationmenuitem; TextView nonotificationtext; @Override
codereview_java_data_7740
List<T> parents = new ArrayList<>(); Node parentNode = jjtGetParent(); while (parentNode != null) { - if (parentType.isInstance(parentNode.getClass())) { parents.add((T) parentNode); } parentNode = parentNode.jjtGetParent(); This is the cause for the unit test failures (wouldn't have seen it otherwise): It must be `parentType.isInstance(parentNode)` (without the getClass()) - now all the parent nodes have been matched (since every class is a class...). List<T> parents = new ArrayList<>(); Node parentNode = jjtGetParent(); while (parentNode != null) { + if (parentType.isInstance(parentNode)) { parents.add((T) parentNode); } parentNode = parentNode.jjtGetParent();
codereview_java_data_7748
import com.hazelcast.internal.metrics.ProbeLevel; import com.hazelcast.internal.metrics.ProbeUnit; import com.hazelcast.jet.core.metrics.Metric; import com.hazelcast.jet.core.metrics.Unit; import javax.annotation.Nonnull; we should also maybe add a tag specific for user metrics? import com.hazelcast.internal.metrics.ProbeLevel; import com.hazelcast.internal.metrics.ProbeUnit; import com.hazelcast.jet.core.metrics.Metric; +import com.hazelcast.jet.core.metrics.MetricTags; import com.hazelcast.jet.core.metrics.Unit; import javax.annotation.Nonnull;
codereview_java_data_7757
import android.widget.ScrollView; import android.widget.TextView; import java.util.Date; import static java.lang.System.currentTimeMillis; String comparison using == import android.widget.ScrollView; import android.widget.TextView; +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.Date; +import java.util.Formatter; import static java.lang.System.currentTimeMillis;
codereview_java_data_7759
public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); - mAllergensFromDao = Utils.getAppDaoSession(this.getActivity()).getAllergenDao().loadAll(); api = new OpenFoodAPIClient(getActivity()); mView = view; `Utils.getAppDaoSession(getActivity()).getAllergenDao()` is used four times in this class, so consider create a class field like: ```java AllerhenDao dao; public void onViewCreated() { dao = Utils.getAppDaoSession(getActivity()).getAllergenDao() } public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); + mAllergenDao = Utils.getAppDaoSession(getActivity()).getAllergenDao(); + mAllergensFromDao = mAllergenDao.loadAll(); api = new OpenFoodAPIClient(getActivity()); mView = view;
codereview_java_data_7763
private static final String COPYRIGHT_LINE = "Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved."; private final Node node; private volatile JetService jetService; - private volatile ILogger logger; NodeExtensionCommon(Node node) { this.node = node; } void afterStart() { - logger = node.getLogger(getClass().getName()); jetService().getJobCoordinationService().startScanningForJobs(); } We should check the `logger` is not null when using it. It can happen. private static final String COPYRIGHT_LINE = "Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved."; private final Node node; + private final ILogger logger; private volatile JetService jetService; NodeExtensionCommon(Node node) { this.node = node; + this.logger = node.getLogger(getClass().getName()); } void afterStart() { jetService().getJobCoordinationService().startScanningForJobs(); }
codereview_java_data_7765
import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.google.inject.Inject; import com.hubspot.singularity.executor.config.SingularityExecutorConfiguration; import com.spotify.docker.client.DockerClient; I would only log all of these if you don't control the code that is going to handle the thrown exception - meaning, you need to ensure it gets logged here because you don't know if it will be logged when caught. import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import com.google.inject.Inject; import com.hubspot.singularity.executor.config.SingularityExecutorConfiguration; import com.spotify.docker.client.DockerClient;
codereview_java_data_7766
spec.commandLine().usage(out); } - @FunctionalInterface - public interface KeyLoader { - SECP256K1.KeyPair load(final File keyFile) throws IOException; - } - private Optional<KeyPair> getKeyPair() { try { return Optional.of(keyLoader.load(parentCommand.nodePrivateKeyFile())); (style) Usually internal classes / interfaces go at the bottom of the class spec.commandLine().usage(out); } private Optional<KeyPair> getKeyPair() { try { return Optional.of(keyLoader.load(parentCommand.nodePrivateKeyFile()));
codereview_java_data_7778
import org.apache.iceberg.exceptions.AlreadyExistsException; import org.apache.iceberg.exceptions.CommitFailedException; import org.apache.iceberg.exceptions.NoSuchTableException; -import org.apache.iceberg.io.CloseableGroup; import org.apache.iceberg.relocated.com.google.common.base.MoreObjects; import org.apache.iceberg.relocated.com.google.common.base.Preconditions; import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public abstract class BaseMetastoreCatalog extends CloseableGroup implements Catalog { private static final Logger LOG = LoggerFactory.getLogger(BaseMetastoreCatalog.class); @Override I think closeable should be handled by the concrete impl of a catalog and not by the base class, I don't think all catalogs must implement closeable by design. This should be done via composition rather than inheritance. Additionally, I don't know what the effect of this change is on other catalogs so this feels a bit on the risky side. import org.apache.iceberg.exceptions.AlreadyExistsException; import org.apache.iceberg.exceptions.CommitFailedException; import org.apache.iceberg.exceptions.NoSuchTableException; import org.apache.iceberg.relocated.com.google.common.base.MoreObjects; import org.apache.iceberg.relocated.com.google.common.base.Preconditions; import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +public abstract class BaseMetastoreCatalog implements Catalog { private static final Logger LOG = LoggerFactory.getLogger(BaseMetastoreCatalog.class); @Override
codereview_java_data_7779
*/ package org.kie.kogito; -import org.kie.kogito.rules.KieConfig; - /** * Marker interface to identify a KogitoConfig (i.e. ProcessConfig, ...) */ -public interface KogitoConfig extends KieConfig { } This should be reverted */ package org.kie.kogito; /** * Marker interface to identify a KogitoConfig (i.e. ProcessConfig, ...) */ +public interface KogitoConfig { }
codereview_java_data_7785
private boolean isEligibleForShuffle(SingularityTaskId task, Set<String> requestBlacklist) { Optional<SingularityTaskHistoryUpdate> taskRunning = taskManager.getTaskHistoryUpdate(task, ExtendedTaskState.TASK_RUNNING); - // requestBlacklist = dynamic list from zookeeper - // configuration = constant list from yaml file return ( !requestBlacklist.contains(task.getRequestId()) - && !configuration.getDoNotShuffleRequests().contains(task.getRequestId()) && isLongRunning(task) && ( configuration.getMinutesBeforeNewTaskEligibleForShuffle() == 0 // Shuffle delay is disabled entirely I'm wondering if we should, maybe on startup, load the list from the yaml into zookeeper, making zookeeper the source of truth? Could always do this once as a zk migration, then ignore the yaml from then on (probably mark as deprecated then too) private boolean isEligibleForShuffle(SingularityTaskId task, Set<String> requestBlacklist) { Optional<SingularityTaskHistoryUpdate> taskRunning = taskManager.getTaskHistoryUpdate(task, ExtendedTaskState.TASK_RUNNING); return ( !requestBlacklist.contains(task.getRequestId()) && isLongRunning(task) && ( configuration.getMinutesBeforeNewTaskEligibleForShuffle() == 0 // Shuffle delay is disabled entirely
codereview_java_data_7788
EXPECTED_CHANNEL_QUALIFIER(ERROR, 120, "expected channel reference '':<channel>'' but found ''{0}''"), // EXPECTED_CHANNEL_NAME(ERROR, 121, "expected channel name but found ''{0}''"), // ILLEGAL_STREAM_NAME(ERROR, 122, "illegal name for a stream ''{0}''"), // - ILLEGAL_TASK_NAME(ERROR, 122, "illegal name for a task ''{0}''"), // MISSING_VALUE_FOR_VARIABLE(ERROR, 125, "no value specified for variable ''{0}'' when using substream"), // VARIABLE_NOT_TERMINATED(ERROR, 126, "unable to find variable terminator ''}'' in argument ''{0}''"), // AMBIGUOUS_MODULE_NAME(ERROR, I think the code `122` needs to change as it is already used by `ILLEGAL_STREAM_NAME` EXPECTED_CHANNEL_QUALIFIER(ERROR, 120, "expected channel reference '':<channel>'' but found ''{0}''"), // EXPECTED_CHANNEL_NAME(ERROR, 121, "expected channel name but found ''{0}''"), // ILLEGAL_STREAM_NAME(ERROR, 122, "illegal name for a stream ''{0}''"), // + ILLEGAL_TASK_NAME(ERROR, 123, "illegal name for a task ''{0}''"), // MISSING_VALUE_FOR_VARIABLE(ERROR, 125, "no value specified for variable ''{0}'' when using substream"), // VARIABLE_NOT_TERMINATED(ERROR, 126, "unable to find variable terminator ''}'' in argument ''{0}''"), // AMBIGUOUS_MODULE_NAME(ERROR,
codereview_java_data_7797
// Network private static final String PREF_ENQUEUE_DOWNLOADED = "prefEnqueueDownloaded"; public static final String PREF_UPDATE_INTERVAL = "prefAutoUpdateIntervall"; - public static final String PREF_MOBILE_UPDATE_OLD = "prefMobileUpdate"; public static final String PREF_MOBILE_UPDATE = "prefMobileUpdateAllowed"; public static final String PREF_EPISODE_CLEANUP = "prefEpisodeCleanup"; public static final String PREF_PARALLEL_DOWNLOADS = "prefParallelDownloads"; we can never get rid of this... // Network private static final String PREF_ENQUEUE_DOWNLOADED = "prefEnqueueDownloaded"; public static final String PREF_UPDATE_INTERVAL = "prefAutoUpdateIntervall"; public static final String PREF_MOBILE_UPDATE = "prefMobileUpdateAllowed"; public static final String PREF_EPISODE_CLEANUP = "prefEpisodeCleanup"; public static final String PREF_PARALLEL_DOWNLOADS = "prefParallelDownloads";
codereview_java_data_7807
reason + " ~~~~"; - String logPageString = "\n" + "{{Commons:Deletion requests" + media.getFilename() + "}}\n"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault()); String date = sdf.format(calendar.getTime()); I guess you forgot removing "+" from your previous implementation. This method shouldn't be edited at all if I don't miss any point. reason + " ~~~~"; + String logPageString = "\n{{Commons:Deletion requests" + media.getFilename() + "}}\n"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault()); String date = sdf.format(calendar.getTime());
codereview_java_data_7810
import java.util.List; import java.util.Objects; import java.util.Set; -import java.util.function.Predicate; import java.util.stream.Collectors; import org.junit.Test; Instead of this, wouldn't it be simpler to make `Lz4Substitution` and `SnappySubstitution` implement `Compressor<ByteBuf>`? import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.junit.Test;
codereview_java_data_7814
minerNode1.verify(blockchain.minimumHeight(1)); minerNode1.execute(cliqueTransactions.createAddProposal(minerNode2)); - cluster.verify(blockchain.minimumHeightProgression(minerNode1, 1)); cluster.verify(clique.validatorsAtBlockEqual("0x2", minerNode1, minerNode2)); cluster.verify(clique.validatorsAtBlockEqual(LATEST, minerNode1, minerNode2)); } progression sounds a bit odd here. Is there a consistent phrasing or tense used or meant to be used for the dsl? minerNode1.verify(blockchain.minimumHeight(1)); minerNode1.execute(cliqueTransactions.createAddProposal(minerNode2)); + cluster.verify(blockchain.reachesHeight(minerNode1, 1)); cluster.verify(clique.validatorsAtBlockEqual("0x2", minerNode1, minerNode2)); cluster.verify(clique.validatorsAtBlockEqual(LATEST, minerNode1, minerNode2)); }
codereview_java_data_7817
public void testVerifiedIllegalWidth() { AssertHelpers.assertThrows("Should fail if width is less than or equal to zero", IllegalArgumentException.class, - "The width of truncate must larger than zero", () -> Truncate.get(Types.IntegerType.get(), 0)); } } `must larger` -> `must be larger`, here and in other places with similar message public void testVerifiedIllegalWidth() { AssertHelpers.assertThrows("Should fail if width is less than or equal to zero", IllegalArgumentException.class, + "The width of truncate must be larger than zero", () -> Truncate.get(Types.IntegerType.get(), 0)); } }
codereview_java_data_7823
new ResendConfirmationCodeRequest() .withUsername(userId) .withClientId(clientId) - .withSecretHash(secretHash); final String pinpointEndpointId = pool.getPinpointEndpointId(); resendConfirmationCodeRequest.setUserContextData(getUserContextData()); if (pinpointEndpointId != null) { where is this `clientMetadata` being used in this function? new ResendConfirmationCodeRequest() .withUsername(userId) .withClientId(clientId) + .withSecretHash(secretHash) + .withClientMetadata(clientMetadata); final String pinpointEndpointId = pool.getPinpointEndpointId(); resendConfirmationCodeRequest.setUserContextData(getUserContextData()); if (pinpointEndpointId != null) {
codereview_java_data_7833
private String code; private String clientId; private String redirectUri; - private AuthorizationGrantType grantType; private AuthorizationCodeTokenRequestAttributes() { } The grant type member is not needed here as it's implied based on the class name -> `AuthorizationCodeTokenRequestAttributes`. Can you remove this please. private String code; private String clientId; private String redirectUri; private AuthorizationCodeTokenRequestAttributes() { }
codereview_java_data_7846
* Simple log to print to console. It conforms to the * {@code com.amazonaws.logging.Log} interface. */ -public class ConsoleLog implements com.amazonaws.logging.Log { /** Tag for the log message */ private final String tag; ```suggestion public final class ConsoleLog implements com.amazonaws.logging.Log { ``` * Simple log to print to console. It conforms to the * {@code com.amazonaws.logging.Log} interface. */ +public final class ConsoleLog implements com.amazonaws.logging.Log { /** Tag for the log message */ private final String tag;
codereview_java_data_7852
private final AuthenticationManagerResolver<String> issuerAuthenticationManagerResolver; - private final Converter<HttpServletRequest, String> issuerConverter; /** * Construct a {@link JwtIssuerAuthenticationManagerResolver} using the provided For consistency with other Spring Security classes, let's introduce a setter here instead of adding it to the constructor. private final AuthenticationManagerResolver<String> issuerAuthenticationManagerResolver; + private Converter<HttpServletRequest, String> issuerConverter; /** * Construct a {@link JwtIssuerAuthenticationManagerResolver} using the provided
codereview_java_data_7854
get("/streams/deployments/{timelog}?reuse-deployment-properties=true", "timelog") .contentType(MediaType.APPLICATION_JSON) .content(json)) - .andDo(print()) .andExpect(status().isOk()) .andDo(this.documentationHandler.document( pathParameters(parameterWithName("timelog") We can remove the print() to clean up our logs during testing. get("/streams/deployments/{timelog}?reuse-deployment-properties=true", "timelog") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andDo(this.documentationHandler.document( pathParameters(parameterWithName("timelog")
codereview_java_data_7855
private static final int cqFileSize = 10; private static final int cqExtFileSize = 10 * (ConsumeQueueExt.CqExtUnit.MIN_EXT_UNIT_SIZE + 64); - private static SocketAddress BornHost; - private static SocketAddress StoreHost; DefaultMessageStore messageStore; MessageStoreConfig messageStoreConfig; BrokerConfig brokerConfig; Variables should begin with lowercase letter. private static final int cqFileSize = 10; private static final int cqExtFileSize = 10 * (ConsumeQueueExt.CqExtUnit.MIN_EXT_UNIT_SIZE + 64); + private static SocketAddress bornHost; + private static SocketAddress storeHost; DefaultMessageStore messageStore; MessageStoreConfig messageStoreConfig; BrokerConfig brokerConfig;
codereview_java_data_7865
Keyword.getVisibleKeywords(mMessage.getFlags())); fragment.show(getFragmentManager(), "tag_choice"); } catch (Exception e) { - e.printStackTrace(); } } Use logging instead of this. Keyword.getVisibleKeywords(mMessage.getFlags())); fragment.show(getFragmentManager(), "tag_choice"); } catch (Exception e) { + Timber.e(e, "Cannot show TagChoiceDialogFragment"); } }
codereview_java_data_7867
private XMLStreamWriter xmlWriter; private OutputStream stream; - private byte[] lineSeparator = new byte[0]; public XMLRenderer() { super(NAME, "XML format."); this initialization seems moot, right? ```suggestion private byte[] lineSeparator; ``` private XMLStreamWriter xmlWriter; private OutputStream stream; + private byte[] lineSeparator; public XMLRenderer() { super(NAME, "XML format.");
codereview_java_data_7874
@Test public void testNotFilterForm() { String sql = "select count(distinct \"the_month\") from " + "\"foodmart\" where \"the_month\" <> \'October\'"; sql(sql, FOODMART) .returnsOrdered("EXPR$0=11"); } } can you add the expected druid filter and/or plan to make sure that druid is actually doing the filter and not calcite ? @Test public void testNotFilterForm() { String sql = "select count(distinct \"the_month\") from " + "\"foodmart\" where \"the_month\" <> \'October\'"; + String druidFilter = "'filter':{'type':'not'," + + "'field':{'type':'selector','dimension':'the_month','value':'October'}}"; + // Check that the filter actually worked, and that druid was responsible for the filter sql(sql, FOODMART) + .queryContains(druidChecker(druidFilter)) .returnsOrdered("EXPR$0=11"); } }
codereview_java_data_7877
void scheduleSnapshot(MasterContext mc, long executionId) { long snapshotInterval = mc.jobConfig().getSnapshotIntervalMillis(); ExecutionService executionService = nodeEngine.getExecutionService(); - logFine(logger, "%s snapshot is scheduled in %d ms", mc.jobIdString(), snapshotInterval); executionService.schedule(COORDINATOR_EXECUTOR_NAME, () -> mc.snapshotContext().startScheduledSnapshot(executionId), snapshotInterval, MILLISECONDS); This was done this way because `mc.jobIdString()` isn't a simple getter. Users mostly have this logging off. Again below, multiple times. void scheduleSnapshot(MasterContext mc, long executionId) { long snapshotInterval = mc.jobConfig().getSnapshotIntervalMillis(); ExecutionService executionService = nodeEngine.getExecutionService(); + if (logger.isFineEnabled()) { + logger.fine(mc.jobIdString() + " snapshot is scheduled in " + snapshotInterval + "ms"); + } executionService.schedule(COORDINATOR_EXECUTOR_NAME, () -> mc.snapshotContext().startScheduledSnapshot(executionId), snapshotInterval, MILLISECONDS);
codereview_java_data_7878
package tech.pegasys.pantheon.ethereum.p2p.peers; import static java.nio.charset.StandardCharsets.UTF_8; import tech.pegasys.pantheon.util.enode.EnodeURL; be nicer to use the jsonArray.stream instead of populating a set package tech.pegasys.pantheon.ethereum.p2p.peers; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Collections.emptySet; import tech.pegasys.pantheon.util.enode.EnodeURL;
codereview_java_data_7880
if (isInternetOn(context)) { return true; } else - Toast.makeText(context,R.string.internet_is_off,Toast.LENGTH_SHORT).show(); return false; } public static void promptSpeechInput(Activity activity, int requestCode, View parentView, String promtMsg) { Why was this SnackBar changed to a toast? if (isInternetOn(context)) { return true; } else + Snackbar.make(view,R.string.internet_is_off,Snackbar.LENGTH_SHORT).show(); return false; } public static void promptSpeechInput(Activity activity, int requestCode, View parentView, String promtMsg) {
codereview_java_data_7881
DefaultCompactionPlanner.class.getName(), PropertyType.CLASSNAME, "Planner for default compaction service."), TSERV_COMPACTION_SERVICE_DEFAULT_MAX_OPEN( - "tserver.compaction.service.default.planner.opts.maxOpen", "30", PropertyType.COUNT, "The maximum number of files a compaction will open"), TSERV_COMPACTION_SERVICE_DEFAULT_EXECUTORS( "tserver.compaction.service.default.planner.opts.executors", Presumably, these new properties are for major compactions only. The property prefix could be made consistent with other `tserver.compaction.major` properties. DefaultCompactionPlanner.class.getName(), PropertyType.CLASSNAME, "Planner for default compaction service."), TSERV_COMPACTION_SERVICE_DEFAULT_MAX_OPEN( + "tserver.compaction.service.default.planner.opts.maxOpen", "10", PropertyType.COUNT, "The maximum number of files a compaction will open"), TSERV_COMPACTION_SERVICE_DEFAULT_EXECUTORS( "tserver.compaction.service.default.planner.opts.executors",
codereview_java_data_7883
import org.vividus.steps.ui.model.SequenceAction; import org.vividus.steps.ui.model.SequenceActionType; -public class AbstractParametersToSequenceActionConverter<T extends SequenceActionType<?>> extends AbstractParameterConverter<Parameters, SequenceAction<T>> { private final StringToLocatorConverter stringToLocatorConverter; Looks confusing Abstract... class that is not an abstract one, are there antPMD violations? import org.vividus.steps.ui.model.SequenceAction; import org.vividus.steps.ui.model.SequenceActionType; +public abstract class AbstractParametersToSequenceActionConverter<T extends SequenceActionType<?>> extends AbstractParameterConverter<Parameters, SequenceAction<T>> { private final StringToLocatorConverter stringToLocatorConverter;
codereview_java_data_7893
* Request mapping information. to find the matched method by request * * @author horizonzy - * @since 1.3.1 */ public class RequestMappingInfo { 1.3.1 has released, so the since should be upper 1.3.1 * Request mapping information. to find the matched method by request * * @author horizonzy + * @since 1.3.2 */ public class RequestMappingInfo {
codereview_java_data_7910
if (this.blockCacheManager != null) { this.blockCacheManager.stop(); } - } catch (RuntimeException e1) { - throw new RuntimeException(e1); } } } This catch block could probably be removed. if (this.blockCacheManager != null) { this.blockCacheManager.stop(); } + } catch (UnsupportedOperationException e1) { + throw new UnsupportedOperationException(e1); } } }
codereview_java_data_7917
package com.hazelcast.jet.function; import java.util.function.Predicate; /** * Represents a predicate which accepts three arguments. This * is the three-arity specialization of {@link Predicate}. `TriPredicate` is now lacking the composition methods. package com.hazelcast.jet.function; +import javax.annotation.Nonnull; import java.util.function.Predicate; +import static com.hazelcast.util.Preconditions.checkNotNull; + /** * Represents a predicate which accepts three arguments. This * is the three-arity specialization of {@link Predicate}.
codereview_java_data_7919
// grab this outside of tablet lock. @SuppressWarnings("deprecation") - int maxLogs = tableConfiguration.getCount(tableConfiguration - .resolve(Property.TSERV_WAL_MAX_REFERENCED, Property.TSERV_WALOG_MAX_REFERENCED)); String reason = null; synchronized (this) { It looks like `TABLE_MINC_LOGS_MAX` was deprecated in 2.0.0. There should be two resolves here to ensure we use the right one: ```suggestion .resolve(Property.TSERV_WAL_MAX_REFERENCED, tableConfiguration.resolve(Property.TSERV_WALOG_MAX_REFERENCED, Property.TABLE_MINC_LOGS_MAX)); ``` (this suggestion isn't formatted) If we have to do this a lot, it might make sense to modify the `resolve` command to take more than one argument, but probably not worth it if there's only one or two. // grab this outside of tablet lock. @SuppressWarnings("deprecation") + int maxLogs = tableConfiguration + .getCount(tableConfiguration.resolve(Property.TSERV_WAL_MAX_REFERENCED, tableConfiguration + .resolve(Property.TSERV_WALOG_MAX_REFERENCED, Property.TABLE_MINC_LOGS_MAX))); String reason = null; synchronized (this) {
codereview_java_data_7926
modelBuilder.addRow().addValue("Security").addValue(securityInfo); rowIndex++; - if (securityInfo.isAuthenticated() && securityInfo.isAuthorizationEnabled()) { - final List<String> roles = securityInfo.getRoles(); - if (roles.isEmpty()) { - roles.add("No roles assigned"); - } - modelBuilder.addRow().addValue("Roles").addValue(roles); rowsWithThinSeparators.add(rowIndex++); } I am not sure whether this part of the code will ever be invoked without at least a `single` role as the user requires at least `VIEW` role to access with `/about` endpoint. modelBuilder.addRow().addValue("Security").addValue(securityInfo); rowIndex++; + if (securityInfo.isAuthorizationEnabled()) { + modelBuilder.addRow().addValue("Roles").addValue(securityInfo.getRoles()); rowsWithThinSeparators.add(rowIndex++); }
codereview_java_data_7930
return "enode://" + keyPair.getPublicKey().toString() + "@" + LOCALHOST + ":" + p2pPort; } - KeyPair keyPair() { - return keyPair; - } - private Optional<String> jsonRpcBaseUrl() { if (jsonRpcEnabled) { return Optional.of( I don't think we need this method. It looks like we're taking the KeyPair, then in `PantheonNodeConfig` extracting the private key and throwing away the public key, then in `CliqueExtraData` recalculating the public key from the private one, then converting to an address. Maybe we could just use `getAddress()`? return "enode://" + keyPair.getPublicKey().toString() + "@" + LOCALHOST + ":" + p2pPort; } private Optional<String> jsonRpcBaseUrl() { if (jsonRpcEnabled) { return Optional.of(
codereview_java_data_7940
@Override public void heartbeat(Event event) { long now = System.currentTimeMillis(); - LOG.debug("Heartbeat from mesos. Delta since last heartbeat is {}ms", now - lastHeartbeatTime.getAndSet(now)); } @Override seems like a weird thing to have the getAndSet inside the debug line. I know it gets evaluated the same, but I had to read this a few times to convince myself it would always be hit @Override public void heartbeat(Event event) { long now = System.currentTimeMillis(); + long delta = (now - lastHeartbeatTime.getAndSet(now)); + LOG.debug("Heartbeat from mesos. Delta since last heartbeat is {}ms", delta); } @Override
codereview_java_data_7967
* Base class for processor wrappers. Delegates all calls to the wrapped * processor. */ -public class ProcessorWrapper implements Processor { private final Processor wrapped; should also be abstract class * Base class for processor wrappers. Delegates all calls to the wrapped * processor. */ +public abstract class ProcessorWrapper implements Processor { private final Processor wrapped;
codereview_java_data_7981
@Override public Capabilities getCanonicalCapabilities() { - return new ImmutableCapabilities(BROWSER_NAME, BrowserType.EDGE, PLATFORM_NAME, System.getProperty("os.name")); } @Override Also not needed. @Override public Capabilities getCanonicalCapabilities() { + return new ImmutableCapabilities(BROWSER_NAME, BrowserType.EDGE); } @Override
codereview_java_data_8008
private int index; - private AtomicInteger dataSize = new AtomicInteger(0); private long lastDispatchTime = 0L; There is no need, the task dispatcher is a singleton. private int index; + private int dataSize = 0; private long lastDispatchTime = 0L;
codereview_java_data_8010
@Test public void testQueryByEmptyDeploymentIds() { - assertThrows(FlowableIllegalArgumentException.class, () -> { - appRepositoryService.createAppDefinitionQuery().deploymentIds(new HashSet<>()).list(); - }); } @Test If we are going for AssertJ fluent I say we go all in. So use: ``` assertThatThrownBy(() -> appRepositoryService.createAppDefinitionQuery().deploymentIds(new HashSet<>())) .isInstanceOf(FlowableIllegalArgumentException.class); ``` @Test public void testQueryByEmptyDeploymentIds() { + assertThatThrownBy(() -> appRepositoryService.createAppDefinitionQuery().deploymentIds(new HashSet<>()).list()) + .isInstanceOf(FlowableIllegalArgumentException.class); } @Test
codereview_java_data_8015
var compactingFiles = compacting.stream().flatMap(job -> job.getFiles().stream()).collect(Collectors.toSet()); Preconditions.checkArgument(this.allFiles.containsAll(compactingFiles), - "Compacting not in set of all files: %s, compacting files: %s", this.allFiles, - compactingFiles); Preconditions.checkArgument(Collections.disjoint(compactingFiles, this.candidates), "Compacting and candidates overlap %s %s", compactingFiles, this.candidates); The message itself is still confusing to me. How about this? ```suggestion "Compacting files %s not in set of all files: %s", compactingFiles, this.allFiles); ``` var compactingFiles = compacting.stream().flatMap(job -> job.getFiles().stream()).collect(Collectors.toSet()); Preconditions.checkArgument(this.allFiles.containsAll(compactingFiles), + "Compacting files %s not in set of all files: %s", compactingFiles, + this.allFiles); Preconditions.checkArgument(Collections.disjoint(compactingFiles, this.candidates), "Compacting and candidates overlap %s %s", compactingFiles, this.candidates);
codereview_java_data_8016
throws IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException; } - private static class ConcurrentKeyExtentCache implements KeyExtentCache { private static final Text MAX = new Text(); KeyExtentCache, or more specifically ConcurrentKeyExtentCache, could probably use a unit test. throws IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException; } + @VisibleForTesting + static class ConcurrentKeyExtentCache implements KeyExtentCache { private static final Text MAX = new Text();
codereview_java_data_8023
public class ImageUtils { /** * Resize an image to the given width and height considering the preserveAspectRatio flag. * @param bitmap Will this be a breaking change? You've added a new parameter to this public method in the Android platform. Will calls such as `ImageUtils.resize(bitmap, 100, 100)` continue to work? You can mitigate this by adding the following method: ```java public static Bitmap resize(Bitmap bitmap, final int width, final int height) { resize(bitmap, width, height, false); } ``` public class ImageUtils { + /** + * Resize an image to the given width and height. + * @param bitmap + * @param width + * @param height + * @return a new, scaled Bitmap + */ + public static Bitmap resize(Bitmap bitmap, final int width, final int height) { + ImageUtils.resize(bitmap, width, height, false) + } + /** * Resize an image to the given width and height considering the preserveAspectRatio flag. * @param bitmap
codereview_java_data_8024
import javax.enterprise.event.Observes; import javax.inject.Singleton; -import io.quarkus.arc.config.ConfigProperties; -import io.quarkus.runtime.Startup; import io.quarkus.runtime.StartupEvent; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.kie.kogito.monitoring.elastic.common.ElasticConfigFactory; I think this is not necessary because you are already observing `StartupEvent` in `config` method import javax.enterprise.event.Observes; import javax.inject.Singleton; import io.quarkus.runtime.StartupEvent; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.kie.kogito.monitoring.elastic.common.ElasticConfigFactory;
codereview_java_data_8029
return cpuUsageForRequest/memUsageForRequest; } - private double getEstimatedCpuUsageForRequest(RequestUtilization requestUtilization) { // To account for cpu bursts, tend towards max usage if the app is consistently over-utilizing cpu, tend towards avg if it is over-utilized in short bursts return (requestUtilization.getMaxCpuUsed() - requestUtilization.getAvgCpuUsed()) * requestUtilization.getCpuBurstRating() + requestUtilization.getAvgCpuUsed(); } if this was copied from the other offers class, can we make sure we don't duplicate it? Maybe give it a new home in another class return cpuUsageForRequest/memUsageForRequest; } + public double getEstimatedCpuUsageForRequest(RequestUtilization requestUtilization) { // To account for cpu bursts, tend towards max usage if the app is consistently over-utilizing cpu, tend towards avg if it is over-utilized in short bursts return (requestUtilization.getMaxCpuUsed() - requestUtilization.getAvgCpuUsed()) * requestUtilization.getCpuBurstRating() + requestUtilization.getAvgCpuUsed(); }
codereview_java_data_8034
} private String genGroupNameForTrace() { - return TraceConstants.GROUP_NAME_PREFIX + "-" + this.group; } @Override if it can trace when the multi consumers or producers with the same group name? } private String genGroupNameForTrace() { + return TraceConstants.GROUP_NAME_PREFIX + "-" + this.group + "-" + this.type ; } @Override
codereview_java_data_8035
testScript("testScript.sql"); testScript("derived-column-names.sql"); testScript("information_schema.sql"); - if (!config.mvStore) { // we get slightly different explain plan stuff here in PageStore mode testScript("joins.sql"); } This condition should be reversed. testScript("testScript.sql"); testScript("derived-column-names.sql"); testScript("information_schema.sql"); + if (config.mvStore) { // we get slightly different explain plan stuff here in PageStore mode testScript("joins.sql"); }
codereview_java_data_8038
public CompilationUnit parse() throws ParseException { try { return astParser.CompilationUnit(); - }finally { closeProvider(); } } Nitpicking, level master: we could add a space before finally public CompilationUnit parse() throws ParseException { try { return astParser.CompilationUnit(); + } finally { closeProvider(); } }
codereview_java_data_8040
/** * Converts this collection to a {@link SortedMap}. * - * @param comparator A comparator that induces an order of the Map keys. * @param keyMapper A function that maps an element to a key * @param valueMapper A function that maps an element to a value * @param merge A function that merges values that are associated with the same key Please add a shortcut for the empty case: ```java if (isEmpty()) { return TreeMap.empty(comparator); } else { ... } ``` We could do the same for the other PRs, `toMap` and `toLinkedMap`. /** * Converts this collection to a {@link SortedMap}. * + * @param keyComparator A comparator that induces an order of the Map keys. * @param keyMapper A function that maps an element to a key * @param valueMapper A function that maps an element to a value * @param merge A function that merges values that are associated with the same key
codereview_java_data_8045
mChooseIdentityButton = (TextView) findViewById(R.id.identity); mChooseIdentityButton.setOnClickListener(this); - /* - if (mAccount.getIdentities().size() == 1 && - Preferences.getPreferences(this).getAvailableAccounts().size() == 1) { - mChooseIdentityButton.setVisibility(View.GONE); - } - */ - RecipientView recipientView = new RecipientView(this); recipientPresenter = new RecipientPresenter(this, recipientView, mAccount); If the code is not needed anymore, please remove it. mChooseIdentityButton = (TextView) findViewById(R.id.identity); mChooseIdentityButton.setOnClickListener(this); RecipientView recipientView = new RecipientView(this); recipientPresenter = new RecipientPresenter(this, recipientView, mAccount);
codereview_java_data_8051
public String toStringShort() { if (isAbsolute) { - if(SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false)){ Profile profile = MainApp.getConfigBuilder().getProfile(); if(profile != null) { double basal = profile.getBasal(System.currentTimeMillis()); if you turn off 200%+ this may be still valid public String toStringShort() { if (isAbsolute) { + if(SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)){ Profile profile = MainApp.getConfigBuilder().getProfile(); if(profile != null) { double basal = profile.getBasal(System.currentTimeMillis());
codereview_java_data_8055
.commit(); } - public void setActionBarNotificationBarColor(MaterialColor color) { getSupportActionBar().setBackgroundDrawable(new ColorDrawable(color.toActionBarColor(this))); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { why is this public? .commit(); } + private void setActionBarNotificationBarColor(MaterialColor color) { getSupportActionBar().setBackgroundDrawable(new ColorDrawable(color.toActionBarColor(this))); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
codereview_java_data_8057
* Delete segment path */ public static boolean deleteSegmentParquetStoragePath(CubeInstance cube, String segmentName, String identifier) throws IOException { - if (cube == null) { return false; } String path = getSegmentParquetStoragePath(cube, segmentName, identifier); it'd better check whether these two parameters 'segmentName' and 'identifier' are valid * Delete segment path */ public static boolean deleteSegmentParquetStoragePath(CubeInstance cube, String segmentName, String identifier) throws IOException { + if (cube == null || StringUtils.isNoneBlank(segmentName)|| StringUtils.isNoneBlank(identifier)) { return false; } String path = getSegmentParquetStoragePath(cube, segmentName, identifier);
codereview_java_data_8088
iconTintManager.updateTint(); if (feed != null) { MenuItemUtils.setupSearchItem(menu, (MainActivity) getActivity(), feedID, feed.getTitle()); } if (feed == null || feed.getLink() == null) { menu.findItem(R.id.share_link_item).setVisible(false); If the feed is null, the menu items should still be setup. Just the feed title can be left out. That prevents possible flickering when menu items are displayed/hidden for some feeds. iconTintManager.updateTint(); if (feed != null) { MenuItemUtils.setupSearchItem(menu, (MainActivity) getActivity(), feedID, feed.getTitle()); + } else { + MenuItemUtils.setupSearchItem(menu, (MainActivity) getActivity(), feedID, ""); } if (feed == null || feed.getLink() == null) { menu.findItem(R.id.share_link_item).setVisible(false);
codereview_java_data_8094
import net.sourceforge.pmd.cpd.internal.JavaCCTokenizer; import net.sourceforge.pmd.lang.TokenManager; import net.sourceforge.pmd.lang.jsp.ast.JspTokenManager; public class JSPTokenizer extends JavaCCTokenizer { @Override protected TokenManager getLexerForSource(SourceCode sourceCode) { - return new JspTokenManager(new CharSequenceReader(sourceCode.getCodeBuffer())); } } Hm... seems we lost the feature to skip the BOM... The simplest way would be probably: ```java StringBuilder buffer = sourceCode.getCodeBuffer(); Reader reader; if (buffer.charAt(0) == '\uFEFF') { // skip BOM if present reader = new CharSequenceReader(buffer.substring(1)); } else { reader = new CharSequenceReader(buffer); } return new JspTokenManager(reader); ``` import net.sourceforge.pmd.cpd.internal.JavaCCTokenizer; import net.sourceforge.pmd.lang.TokenManager; import net.sourceforge.pmd.lang.jsp.ast.JspTokenManager; +import net.sourceforge.pmd.util.IOUtil; public class JSPTokenizer extends JavaCCTokenizer { @Override protected TokenManager getLexerForSource(SourceCode sourceCode) { + return new JspTokenManager(IOUtil.skipBOM(new CharSequenceReader(sourceCode.getCodeBuffer()))); } }
codereview_java_data_8095
if (isNotBlank(product.getImageIngredientsUrl())) { if (!Locale.getDefault().getLanguage().equals(product.getLang())) { - addPhotoLabel.setText("Take a photo of the ingredients in "+Locale.getDefault().getDisplayLanguage()); mUrlImage = null; } else { addPhotoLabel.setVisibility(View.GONE); This text needs to be in the strings.xml, so that it can be translated. if (isNotBlank(product.getImageIngredientsUrl())) { if (!Locale.getDefault().getLanguage().equals(product.getLang())) { + addPhotoLabel.setText(getString(R.string.image_prompt_language)+Locale.getDefault().getDisplayLanguage()); mUrlImage = null; } else { addPhotoLabel.setVisibility(View.GONE);
codereview_java_data_8103
/** * Specify the number of rows fetched by the linked table command - * - * @param fetchSize */ - public void setFetchSize(Expression fetchSize){ - this.fetchSize =fetchSize; } @Override In H2's sources binary operators are formatted with spaces around them. /** * Specify the number of rows fetched by the linked table command + * + * @param fetchSize */ + public void setFetchSize(Expression fetchSize) { + this.fetchSize = fetchSize; } @Override
codereview_java_data_8111
protected Optional<BigInteger> chainId = Optional.empty(); - public Builder chainId(final Optional<BigInteger> chainId) { - this.chainId = chainId; - return this; - } - public Builder chainId(final BigInteger chainId) { this.chainId = Optional.of(chainId); return this; did you end up with 2 'chainId' setters on purpose? protected Optional<BigInteger> chainId = Optional.empty(); public Builder chainId(final BigInteger chainId) { this.chainId = Optional.of(chainId); return this;
codereview_java_data_8116
throw e; } catch (Exception e) { if (e.getCause().getClass().equals(ThriftTableOperationException.class) - && e.getMessage().equals("Table is being deleted")) { // acceptable } else { throw new RuntimeException(e); It might be useful to make `Table is being deleted` a static variable in `CompactionDriver` or `TableOperationsImpl`, then reference it from here `CompactionDriverTest` and `TableOperationsImpl`. throw e; } catch (Exception e) { if (e.getCause().getClass().equals(ThriftTableOperationException.class) + && (e.getMessage().equals(TableOperationsImpl.compCanceledMsg) + || e.getMessage().equals(TableOperationsImpl.tableDeletedMsg))) { // acceptable } else { throw new RuntimeException(e);
codereview_java_data_8117
private void authenticate() throws MessagingException, IOException { switch (settings.getAuthType()) { case XOAUTH2: - if (hasCapability(Capabilities.AUTH_XOAUTH2) && hasCapability(Capabilities.SASL_IR) - && oauthTokenProvider != null) { authXoauth2withSASLIR(); } else { throw new MessagingException("Server doesn't support SASL XOAUTH2."); Is there a case where `oauthTokenProvider` is null here and it's not a bug? Either way it should probably be handled in an exception of its own, since the error message below is wrong in this case. private void authenticate() throws MessagingException, IOException { switch (settings.getAuthType()) { case XOAUTH2: + if (oauthTokenProvider == null) { + throw new MessagingException("No OAuthToken Provider available."); + } + if (hasCapability(Capabilities.AUTH_XOAUTH2) + && hasCapability(Capabilities.SASL_IR)) { authXoauth2withSASLIR(); } else { throw new MessagingException("Server doesn't support SASL XOAUTH2.");
codereview_java_data_8121
@Test public void testQueryByAssignedOr() { TaskQuery query = taskService.createTaskQuery().or().taskId("invalid").taskAssigned(); - assertThat(query.count()).isEqualTo(0); - assertThat(query.list()).hasSize(0); } @Test It seems like the `or` is not working correctly. This should have a count of `1` since there is 1 assigned task. @Test public void testQueryByAssignedOr() { TaskQuery query = taskService.createTaskQuery().or().taskId("invalid").taskAssigned(); + assertThat(query.count()).isEqualTo(1); + assertThat(query.list()).hasSize(1); } @Test
codereview_java_data_8126
return false; } - if (ommerValidationMode != HeaderValidationMode.LIGHT - && ommerValidationMode != HeaderValidationMode.LIGHT_SKIP_DETACHED - && ommerValidationMode != HeaderValidationMode.LIGHT_DETACHED_ONLY) { return isOmmerSiblingOfAncestor(context, current, ommer); } else { return true; Could this be clarified with something like: `!HeaderValidationMode.isLight(ommerValidationMode)` ? return false; } + if (!ommerValidationMode.isFormOfLightValidation()) { return isOmmerSiblingOfAncestor(context, current, ommer); } else { return true;
codereview_java_data_8127
paramLabel = MANDATORY_DOUBLE_FORMAT_HELP, description = "Percentage of remote wire connections that can be established. Must be between 0 and 100 inclusive. (default: ${DEFAULT-VALUE})", - arity = "1") private final Percentage remoteConnectionsPercentage = Fraction.fromDouble(DEFAULT_FRACTION_REMOTE_WIRE_CONNECTIONS_ALLOWED).toPercentage(); Question - why did we end up with 2 options here (enabled + percentage), instead of 1 (just percentage)? If the percentage is at 1, the limit is effectively disabled. paramLabel = MANDATORY_DOUBLE_FORMAT_HELP, description = "Percentage of remote wire connections that can be established. Must be between 0 and 100 inclusive. (default: ${DEFAULT-VALUE})", + arity = "1", + converter = PercentageConverter.class) private final Percentage remoteConnectionsPercentage = Fraction.fromDouble(DEFAULT_FRACTION_REMOTE_WIRE_CONNECTIONS_ALLOWED).toPercentage();
codereview_java_data_8132
public void startReloader() { if (isEnabled) { reloadingFuture = executor.scheduleAtFixedRate(this::reloadZkValues, 0, cacheTtl, TimeUnit.SECONDS); } should this also synchronously perform the first fetch I wonder? Would avoid the case where getAll was incorrectly empty or get(K key) was null public void startReloader() { if (isEnabled) { + reloadZkValues(); reloadingFuture = executor.scheduleAtFixedRate(this::reloadZkValues, 0, cacheTtl, TimeUnit.SECONDS); }
codereview_java_data_8138
public void handleNewBlockEvent(final NewChainHead newChainHead) { final BlockHeader newBlockHeader = newChainHead.getNewChainHeadHeader(); final BlockHeader currentMiningParent = currentHeightManager.getParentBlockHeader(); - LOG.debug("Handling New Chain head event, chain length = {}", currentMiningParent.getNumber()); if (newBlockHeader.getNumber() < currentMiningParent.getNumber()) { LOG.trace( "Discarding NewChainHead event, was for previous block height. chainHeight={} eventHeight={}", isn't this the chain height not chain length? elsewhere is logs I think block is just used to infer block number. public void handleNewBlockEvent(final NewChainHead newChainHead) { final BlockHeader newBlockHeader = newChainHead.getNewChainHeadHeader(); final BlockHeader currentMiningParent = currentHeightManager.getParentBlockHeader(); + LOG.debug("Handling New Chain head event, chain height = {}", currentMiningParent.getNumber()); if (newBlockHeader.getNumber() < currentMiningParent.getNumber()) { LOG.trace( "Discarding NewChainHead event, was for previous block height. chainHeight={} eventHeight={}",
codereview_java_data_8139
@Test public void testDeprecatedAttributeXPathQuery() throws JaxenException { - final StringWriter writer = new StringWriter(); - class MyRootNode extends DummyNode implements RootNode { private MyRootNode(int id) { within the pmd test codebase there is a `JavaUtilLoggingRule` junit `@Rule` just to help you doing this. Several tests, such as the `RuleSetFactoryTest` use it to check that proper warnings are logged. @Test public void testDeprecatedAttributeXPathQuery() throws JaxenException { class MyRootNode extends DummyNode implements RootNode { private MyRootNode(int id) {
codereview_java_data_8140
// ./gradlew test -Drecreate=true String shouldRecreate = System.getProperty("recreate", "false"); task.systemProperty("recreate", shouldRecreate); - task.getInputs().property("recreate", shouldRecreate); }); project.getPlugins().withType(JavaPlugin.class, unusedPlugin -> { Should be be defensive and disable caching when shouldRecreate=true? // ./gradlew test -Drecreate=true String shouldRecreate = System.getProperty("recreate", "false"); task.systemProperty("recreate", shouldRecreate); + if (Boolean.valueOf(shouldRecreate)) { + task.getOutputs().cacheIf(t -> false); + } }); project.getPlugins().withType(JavaPlugin.class, unusedPlugin -> {
codereview_java_data_8141
return getInt("partitioner.finalizer.delay.seconds"); } - public TimeZone getTimeZone(){ - return Strings.isNullOrEmpty(getString("secor.parser.timezone")) ? TimeZone.getTimeZone("UTC") : TimeZone.getTimeZone(getString("secor.parser.timezone")); } public boolean getBoolean(String name, boolean defaultValue) { This line is a bit too long, can you break it into two? I think most of the coding style has 100 chars line width. return getInt("partitioner.finalizer.delay.seconds"); } + public TimeZone getTimeZone() { + String timezone = getString("secor.parser.timezone"); + return Strings.isNullOrEmpty(timezone) ? TimeZone.getTimeZone("UTC") : TimeZone.getTimeZone(timezone); } public boolean getBoolean(String name, boolean defaultValue) {
codereview_java_data_8147
// accumulo garbage collector properties GC_PREFIX("gc.", null, PropertyType.PREFIX, "Properties in this category affect the behavior of the accumulo garbage collector."), - GC_CANDIDATE_BATCH_SIZE("gc.candidate.batch.size", "8m", PropertyType.BYTES, "The batch size used for garbage collection."), GC_CYCLE_START("gc.cycle.start", "30s", PropertyType.TIMEDURATION, "Time to wait before attempting to garbage collect any old RFiles or write-ahead logs."), Although our type engine is case-insensitive, it is better to use upper-case, so it looks like MegaBytes, and not milliBytes. :smiley_cat: ```suggestion GC_CANDIDATE_BATCH_SIZE("gc.candidate.batch.size", "8M", PropertyType.BYTES, ``` // accumulo garbage collector properties GC_PREFIX("gc.", null, PropertyType.PREFIX, "Properties in this category affect the behavior of the accumulo garbage collector."), + GC_CANDIDATE_BATCH_SIZE("gc.candidate.batch.size", "8M", PropertyType.BYTES, "The batch size used for garbage collection."), GC_CYCLE_START("gc.cycle.start", "30s", PropertyType.TIMEDURATION, "Time to wait before attempting to garbage collect any old RFiles or write-ahead logs."),
codereview_java_data_8154
public TabletMutator putCompactionId(long compactionId); - public TabletMutator putLocation(TServer tsi, LocationType type); - public TabletMutator deleteLocation(TServer tsi, LocationType type); public TabletMutator putZooLock(ZooLock zooLock); Maybe name this tsInstance. public TabletMutator putCompactionId(long compactionId); + public TabletMutator putLocation(TServer tserver, LocationType type); + public TabletMutator deleteLocation(TServer tserver, LocationType type); public TabletMutator putZooLock(ZooLock zooLock);
codereview_java_data_8169
import org.apache.arrow.vector.ValueVector; -public class ArrowVectorAccessor<DecimalT, Utf8StringT, ArrayT, ChildVectorT extends AutoCloseable> { private final ValueVector vector; private final ChildVectorT[] childColumns; how come final? Does that still make sense now that we are using thsi as a base class? import org.apache.arrow.vector.ValueVector; +public class ArrowVectorAccessor<DecimalT, Utf8StringT, ArrayT, ChildVectorT extends AutoCloseable> + implements AutoCloseable { private final ValueVector vector; private final ChildVectorT[] childColumns;
codereview_java_data_8171
updatePossiblyUnderProvisionedAndOverProvisionedIds(requestWithState, numInstances, overProvisionedRequestIds, possiblyUnderProvisionedRequestIds); } - removePendingRequestIds(possiblyUnderProvisionedRequestIds); final List<String> underProvisionedRequestIds = getUnderProvisionedRequestIds(possiblyUnderProvisionedRequestIds); final int pendingRequests = requestManager.getSizeOfPendingQueue(); can we give this a better name? Like `filterForPendingRequests` or something more descriptive like that? updatePossiblyUnderProvisionedAndOverProvisionedIds(requestWithState, numInstances, overProvisionedRequestIds, possiblyUnderProvisionedRequestIds); } + filterForPendingRequests(possiblyUnderProvisionedRequestIds); final List<String> underProvisionedRequestIds = getUnderProvisionedRequestIds(possiblyUnderProvisionedRequestIds); final int pendingRequests = requestManager.getSizeOfPendingQueue();
codereview_java_data_8173
} private Optional<String> determineKind(String optionContext) { - return Arrays.stream(optionContext.split(" ")) .filter(s -> s.startsWith("existing")) .map(s -> s.substring("existing-".length())) .findFirst(); Should it actually be `split("\\s+")`? } private Optional<String> determineKind(String optionContext) { + return Arrays.stream(optionContext.split("\\s+")) .filter(s -> s.startsWith("existing")) .map(s -> s.substring("existing-".length())) .findFirst();
codereview_java_data_8179
MASTER_REPLICATION_COORDINATOR_THREADCHECK("master.replication.coordinator.threadcheck.time", "5s", PropertyType.TIMEDURATION, "The time between adjustments of the coordinator thread pool"), @Deprecated MASTER_STATUS_THREAD_POOL_SIZE("master.status.threadpool.size", "1", PropertyType.COUNT, "The number of threads to use when fetching the tablet server status for balancing."), Description should be updated to reflect when it was deprecated. I noticed while reviewing deprecated items that we hadn't been doing this for configuration properties, and it's very useful. MASTER_REPLICATION_COORDINATOR_THREADCHECK("master.replication.coordinator.threadcheck.time", "5s", PropertyType.TIMEDURATION, "The time between adjustments of the coordinator thread pool"), + /** + * @deprecated since 1.9.1 + */ @Deprecated MASTER_STATUS_THREAD_POOL_SIZE("master.status.threadpool.size", "1", PropertyType.COUNT, "The number of threads to use when fetching the tablet server status for balancing."),
codereview_java_data_8192
JAVA_7(new Java7Validator(), null), JAVA_8(new Java8Validator(), null), JAVA_9(new Java9Validator(), null), - JAVA_10(null, new Java10PostProcessor()); final Validator validator; final ParseResult.PostProcessor postProcessor; Maybe we could call it JAVA_10_preview and tell that we are going to remove it later, when Java_10 is actually released JAVA_7(new Java7Validator(), null), JAVA_8(new Java8Validator(), null), JAVA_9(new Java9Validator(), null), + JAVA_10_PREVIEW(null, new Java10PostProcessor()); final Validator validator; final ParseResult.PostProcessor postProcessor;
codereview_java_data_8201
* @return ConditionalWriter object for writing ConditionalMutations * @throws TableNotFoundException * when the specified table doesn't exist */ ConditionalWriter createConditionalWriter(String tableName) throws TableNotFoundException; ```suggestion * when the specified table doesn't exist * * @since 2.1.0 ``` * @return ConditionalWriter object for writing ConditionalMutations * @throws TableNotFoundException * when the specified table doesn't exist + * + * @since 2.1.0 */ ConditionalWriter createConditionalWriter(String tableName) throws TableNotFoundException;
codereview_java_data_8205
public static final RpcApi ADMIN = new RpcApi("ADMIN"); public static final RpcApi EEA = new RpcApi("EEA"); - public static final Collection<RpcApi> DEFAULT_JSON_RPC_APIS = Arrays.asList(ETH, NET, WEB3, EEA); public static Optional<RpcApi> valueOf(final String name) { if (name.equals(ETH.getCliValue())) { Should EEA be a part of the default APIs? @arash009 public static final RpcApi ADMIN = new RpcApi("ADMIN"); public static final RpcApi EEA = new RpcApi("EEA"); + public static final Collection<RpcApi> DEFAULT_JSON_RPC_APIS = Arrays.asList(ETH, NET, WEB3); public static Optional<RpcApi> valueOf(final String name) { if (name.equals(ETH.getCliValue())) {
codereview_java_data_8215
} /** - * Sets the resolver used for resolving {@link OAuth2AuthorizationRequest}'s. * * @since 5.1 * @param authorizationRequestResolver the resolver used for resolving authorization requests */ - public final void setAuthorizationRequestResolver(OAuth2AuthorizationRequestResolver authorizationRequestResolver) { Assert.notNull(authorizationRequestResolver, "authorizationRequestResolver cannot be null"); this.authorizationRequestResolver = authorizationRequestResolver; } This should be a separate constructor. The reason is that with a custom OAuth2AuthorizationRequestResolver implementation, the ClientRegistrationRepository should not be required for this class. However, it is required to construct the class at the moment. } /** + * Constructs an {@code OAuth2AuthorizationRequestRedirectFilter} using the provided parameters. * * @since 5.1 * @param authorizationRequestResolver the resolver used for resolving authorization requests */ + public OAuth2AuthorizationRequestRedirectFilter(OAuth2AuthorizationRequestResolver authorizationRequestResolver) { Assert.notNull(authorizationRequestResolver, "authorizationRequestResolver cannot be null"); this.authorizationRequestResolver = authorizationRequestResolver; }
codereview_java_data_8218
public static final String COUNTER_PREFIX = "counter."; - private MetricRepository metricRepository; private final ResourceAssembler<Metric<Double>, CounterResource> counterResourceAssembler = new DeepCounterResourceAssembler(); How is the repository injected now? public static final String COUNTER_PREFIX = "counter."; + private final MetricRepository metricRepository; private final ResourceAssembler<Metric<Double>, CounterResource> counterResourceAssembler = new DeepCounterResourceAssembler();
codereview_java_data_8224
Text defaultTabletRow = TabletsSection.getRow(prevTablet.getTableId(), null); if (range.contains(new Key(defaultTabletRow))) { throw new IllegalStateException( - "Read all tablets but did not see default tablet. Last tablet seen : " + prevTablet.getExtent()); } } Not necessarily true that all tablets were read. Maybe "scanned range included default tablet, but default tablet not seen". Text defaultTabletRow = TabletsSection.getRow(prevTablet.getTableId(), null); if (range.contains(new Key(defaultTabletRow))) { throw new IllegalStateException( + "Scan range incudled default tablet, but did not see default tablet. Last tablet seen : " + prevTablet.getExtent()); } }
codereview_java_data_8234
else switchedPath = le.filename; - String switchedLog = switchVolume(le.filename, FileType.WAL, replacements); - if (switchedLog != null) { numSwitched++; } This doesn't even need to be assigned to a variable... can just check if method return is null. else switchedPath = le.filename; + if (switchVolume(le.filename, FileType.WAL, replacements) != null) { numSwitched++; }
codereview_java_data_8237
return Arrays.stream(validators).map(PantheonNode::getAddress).sorted().toArray(Address[]::new); } - public Condition proposerAtChainHeadEqual(final PantheonNode proposer) { return new ExpectBlockHasProposer(eth, proposer.getAddress()); } maybe not a clique thing? return Arrays.stream(validators).map(PantheonNode::getAddress).sorted().toArray(Address[]::new); } + public Condition aBlockIsCreatedByProposer(final PantheonNode proposer) { return new ExpectBlockHasProposer(eth, proposer.getAddress()); }
codereview_java_data_8243
} public void setAutoCommitIntervalMillis(long autoCommitIntervalMillis) { - if (autoCommitIntervalMillis >= 1000) { this.autoCommitIntervalMillis = autoCommitIntervalMillis; } } It would be better if you can replace this magic number(1000) with a constant variable. } public void setAutoCommitIntervalMillis(long autoCommitIntervalMillis) { + if (autoCommitIntervalMillis >= MIN_AUTOCOMMIT_INTERVAL_MILLIS) { this.autoCommitIntervalMillis = autoCommitIntervalMillis; } }
codereview_java_data_8258
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.util.stream.Collectors.toList; import static org.kie.kogito.codegen.rules.KogitoPackageSources.getReflectConfigFile; import static org.kie.pmml.commons.utils.KiePMMLModelUtils.getSanitizedClassName; Please compile locally to fix import sorting import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.databind.ObjectMapper; + import static java.util.stream.Collectors.toList; import static org.kie.kogito.codegen.rules.KogitoPackageSources.getReflectConfigFile; import static org.kie.pmml.commons.utils.KiePMMLModelUtils.getSanitizedClassName;
codereview_java_data_8259
for (Entry<String,Long> entry : totalBlocks.entrySet()) { final String host = entry.getKey(); final Long blocksForHost = entry.getValue(); - System.out.printf("%15s %5.1f %8d%n", host, - (localBlocks.get(host) * 100.) / blocksForHost, blocksForHost); } } return 0; ```suggestion localBlocks.get(host) * 100. / blocksForHost, blocksForHost); ``` for (Entry<String,Long> entry : totalBlocks.entrySet()) { final String host = entry.getKey(); final Long blocksForHost = entry.getValue(); + System.out.printf("%15s %5.1f %8d%n", host, localBlocks.get(host) * 100.0 / blocksForHost, + blocksForHost); } } return 0;
codereview_java_data_8260
* @param properties the properties * @see #OPTION_SKIP_BLOCKS * @see #OPTION_SKIP_BLOCKS_PATTERN */ public void setProperties(Properties properties) { skipBlocks = Boolean.parseBoolean(properties.getProperty(OPTION_SKIP_BLOCKS, Boolean.TRUE.toString())); let's add `@see #OPTION_IGNORE_LITERAL_SEQUENCES` here as well.... * @param properties the properties * @see #OPTION_SKIP_BLOCKS * @see #OPTION_SKIP_BLOCKS_PATTERN + * @see #OPTION_IGNORE_LITERAL_SEQUENCES */ public void setProperties(Properties properties) { skipBlocks = Boolean.parseBoolean(properties.getProperty(OPTION_SKIP_BLOCKS, Boolean.TRUE.toString()));
codereview_java_data_8265
authorLayout.setVisibility(GONE); } - if(applicationKvStore.getBoolean("login_skipped") == true){ delete.setVisibility(GONE); } Please remove `== true`. Shorter and easier to read :-) authorLayout.setVisibility(GONE); } + if(applicationKvStore.getBoolean("login_skipped")){ delete.setVisibility(GONE); }
codereview_java_data_8268
if (closed) return; - Span span = TraceUtil.getTracer().spanBuilder("TabletServerBatchWriter::close").startSpan(); try (Scope scope = span.makeCurrent()) { closed = true; Since we have `TraceUtil` anyway, it might be useful to just make a method in `TraceUtil.java` that does: ```java Span newSpan(String name) { return getTracer().spanBuilder(name).startSpan(); } ``` This would help clean up some boilerplate verbosity, and keep the `Tracer` management code in `TraceUtil`. if (closed) return; + Span span = TraceUtil.createSpan(this.getClass(), "close", SpanKind.CLIENT); try (Scope scope = span.makeCurrent()) { closed = true;
codereview_java_data_8272
private static final int PERSON_COUNT = 100; - private static String DB_CONNECTION_URL; @BeforeClass public static void setupClass() throws SQLException, IOException { String dbName = ReadJdbcPTest.class.getSimpleName(); String tempDirectory = Files.createTempDirectory(dbName).toString(); - DB_CONNECTION_URL = "jdbc:h2:" + tempDirectory + "/" + dbName; createAndFillTable(); } Should not be all caps if it's not final private static final int PERSON_COUNT = 100; + private static String dbConnectionUrl; @BeforeClass public static void setupClass() throws SQLException, IOException { String dbName = ReadJdbcPTest.class.getSimpleName(); String tempDirectory = Files.createTempDirectory(dbName).toString(); + dbConnectionUrl = "jdbc:h2:" + tempDirectory + "/" + dbName; createAndFillTable(); }
codereview_java_data_8279
import javax.annotation.PostConstruct; import javax.inject.Inject; import io.quarkus.runtime.Startup; import org.kie.kogito.eventdriven.rules.AbstractEventDrivenQueryExecutor; import org.kie.kogito.rules.RuleUnit; Why startup? Isn't `@ApplicationScoped` enough? import javax.annotation.PostConstruct; import javax.inject.Inject; +import com.fasterxml.jackson.databind.ObjectMapper; import io.quarkus.runtime.Startup; import org.kie.kogito.eventdriven.rules.AbstractEventDrivenQueryExecutor; import org.kie.kogito.rules.RuleUnit;