id
stringlengths
23
26
content
stringlengths
182
2.49k
codereview_java_data_10082
.region(region) .build(); - getActivites(sfnClient); sfnClient.close(); } // snippet-start:[stepfunctions.java2.list_activities.main] - public static void getActivites(SfnClient sfnClient) { try { ListActivitiesRequest activitiesRequest = ListActivitiesRequest.builder() Can we change the method name to listActivities? GET and LIST operations have different expected behaviors. .region(region) .build(); + listAllActivites(sfnClient); sfnClient.close(); } // snippet-start:[stepfunctions.java2.list_activities.main] + public static void listAllActivites(SfnClient sfnClient) { try { ListActivitiesRequest activitiesRequest = ListActivitiesRequest.builder()
codereview_java_data_10085
update(getQueryMetrics(projectName), sqlResponse); String cube = sqlResponse.getCube(); - if (cube == null) { return; } String cubeName = cube.replace("=", "->"); It's better use `StringUtils.isEmpty(cube)` to check. update(getQueryMetrics(projectName), sqlResponse); String cube = sqlResponse.getCube(); + if (StringUtils.isEmpty(cube)) { return; } String cubeName = cube.replace("=", "->");
codereview_java_data_10098
public String getMessage() { return message; } - - public String registrationSecret() { - return registrationSecret; - } } -} \ No newline at end of file Why is this in the result? It seems like it shouldn't be needed there, as the value will already have been used. public String getMessage() { return message; } } \ No newline at end of file +}
codereview_java_data_10100
types.add(Proxy.Type.DIRECT.name()); types.add(Proxy.Type.HTTP.name()); - if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) types.add(Proxy.Type.SOCKS.name()); ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, types); Please add brackets, even if this is only one line types.add(Proxy.Type.DIRECT.name()); types.add(Proxy.Type.HTTP.name()); + if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){ types.add(Proxy.Type.SOCKS.name()); + } ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, types);
codereview_java_data_10102
@SuppressWarnings("unchecked") static <T> Bucket<T> get(Type type, int numBuckets) { Preconditions.checkArgument(numBuckets > 0, - "The number of bucket(s) must be larger than zero, but is %s", numBuckets); switch (type.typeId()) { case DATE: Same here. What about "Invalid number of buckets: %s (must be > 0)"? @SuppressWarnings("unchecked") static <T> Bucket<T> get(Type type, int numBuckets) { Preconditions.checkArgument(numBuckets > 0, + "Invalid number of buckets: %s (must be > 0)", numBuckets); switch (type.typeId()) { case DATE:
codereview_java_data_10105
DEPLOYED_TO_UNPAUSE, BOUNCED, SCALED, - SCALE_REVERTED, - PRIORITIZED, - PRIORITY_REVERTED } @JsonCreator are we able to maybe fold these into UPDATED instead somehow? these fields come through on things that a lot of other systems pull in and the roll out can be a pain with the deployer/etc having to know about all the new fields first. If the purpose is just to indicate the action more easily, we can always have the messge text reflect that, which will also show in the UI DEPLOYED_TO_UNPAUSE, BOUNCED, SCALED, + SCALE_REVERTED } @JsonCreator
codereview_java_data_10110
boolean authFailure = true; if (error instanceof AllNodesFailedException) { Collection<Throwable> errors = ((AllNodesFailedException) error).getErrors().values(); for (Throwable nodeError : errors) { if (!(nodeError instanceof AuthenticationException)) { authFailure = false; if `getErrors()` will return empty connection we will treat it as the `AuthFailure`. Is it ok for us? Is it possible? boolean authFailure = true; if (error instanceof AllNodesFailedException) { Collection<Throwable> errors = ((AllNodesFailedException) error).getErrors().values(); + if (errors.size() == 0) { + return false; + } for (Throwable nodeError : errors) { if (!(nodeError instanceof AuthenticationException)) { authFailure = false;
codereview_java_data_10112
private final EnumSet<MetricCategory> enabledCategories = EnumSet.allOf(MetricCategory.class); - public PrometheusMetricsSystem() {} public static MetricsSystem init(final MetricsConfiguration metricsConfiguration) { if (!metricsConfiguration.isEnabled()) { This is deliberately not public. use `init()` ```suggestion PrometheusMetricsSystem() {} ``` private final EnumSet<MetricCategory> enabledCategories = EnumSet.allOf(MetricCategory.class); + PrometheusMetricsSystem() {} public static MetricsSystem init(final MetricsConfiguration metricsConfiguration) { if (!metricsConfiguration.isEnabled()) {
codereview_java_data_10116
.withCreateContextFn(ctx -> channelFn.get().build()) .withCreateServiceFn((ctx, channel) -> new UnaryService<>(channel, callStubFn)) .withDestroyServiceFn(UnaryService::destroy) - .withDestroyContextFn(channel -> channel.shutdown().awaitTermination(5, TimeUnit.SECONDS)); } /** what happens if times out 5 seconds? .withCreateContextFn(ctx -> channelFn.get().build()) .withCreateServiceFn((ctx, channel) -> new UnaryService<>(channel, callStubFn)) .withDestroyServiceFn(UnaryService::destroy) + .withDestroyContextFn(channel -> GrpcUtil.shutdownChannel(channel, logger)); } /**
codereview_java_data_10125
.add(newBatchedWriteBehindConfiguration(5, SECONDS, 2).build()) .buildConfig(String.class, String.class)); - testCache.put("key1", "value"); assertThat(writeBehindProvider.getWriteBehind().getQueueSize(), is(1L)); } finally { cacheManager.close(); This test will run for 5 seconds+ if left like that, do complete the batch after your assertion to make it finish faster .add(newBatchedWriteBehindConfiguration(5, SECONDS, 2).build()) .buildConfig(String.class, String.class)); + testCache.put("key1", "value1"); assertThat(writeBehindProvider.getWriteBehind().getQueueSize(), is(1L)); + testCache.put("key2", "value2"); } finally { cacheManager.close();
codereview_java_data_10127
String message = t.getMessage(); - if ( - message != null && - message.equals( - "Error while trying to send request. Status: 403 Message: \'Framework is not subscribed\'" - ) - ) { return CompletableFuture.runAsync( () -> scheduler.onUncaughtException(new PrematureChannelClosureException()), executorService I think we can make this a bit more flexible so we aren't at the mercy of the exception message. I think this is a valid flow for any time we get a `Mesos4xxException` exception with a 403 in the message (or if the exception itself has a status code in it that would be even better to compare to the int vs a string.contains) String message = t.getMessage(); + if (t instanceof MesosException && message.contains("403")) { return CompletableFuture.runAsync( () -> scheduler.onUncaughtException(new PrematureChannelClosureException()), executorService
codereview_java_data_10130
* necessary so that such topics can't clash with regular topics used * for other purposes. */ - private static final String JET_OBSERVABLE_NAME_PREFIX = INTERNAL_JET_OBJECTS_PREFIX + "observable."; private ObservableUtil() { } I meant the prefix should be `observables.`, also this should be moved to JobRepository where all the other prefixes are * necessary so that such topics can't clash with regular topics used * for other purposes. */ + private static final String JET_OBSERVABLE_NAME_PREFIX = INTERNAL_JET_OBJECTS_PREFIX + "observables."; private ObservableUtil() { }
codereview_java_data_10137
return tabletFile; } - @Test - public void testEquivalence() { - TabletFile newFile = new TabletFile( - new Path("hdfs://localhost:8020/accumulo/tables/2a/default_tablet/F0000070.rf")); - TabletFile tmpFile = new TabletFile(new Path(newFile.getMetaInsert() + "_tmp")); - TabletFile newFile2 = new TabletFile( - new Path(tmpFile.getMetaInsert().substring(0, tmpFile.getMetaInsert().indexOf("_tmp")))); - assertEquals(newFile, newFile2); - } - @Test public void testValidPaths() { test("hdfs://localhost:8020/accumulo/tables/2a/default_tablet/F0000070.rf", Could have a static function in DataFileManager that does the conversion and then have a unit test call that function and verify the result. return tabletFile; } @Test public void testValidPaths() { test("hdfs://localhost:8020/accumulo/tables/2a/default_tablet/F0000070.rf",
codereview_java_data_10139
return batchWriterConfig; } - public ConditionalWriterConfig getConditionalWriterConfig() { ensureOpen(); if (conditionalWriterConfig == null) { Properties props = info.getProperties(); Should probably make this method synchronized. Could have one thread getting this object while another is setting it up. May need to do the same for the batchwriter method. return batchWriterConfig; } + public synchronized ConditionalWriterConfig getConditionalWriterConfig() { ensureOpen(); if (conditionalWriterConfig == null) { Properties props = info.getProperties();
codereview_java_data_10142
} else { jetInstance.shutdown(); } - }); } } would be good to give the thread a name } else { jetInstance.shutdown(); } + }, "jet.ShutdownThread"); } }
codereview_java_data_10148
*/ package org.apache.accumulo.server.conf.store.impl; import java.util.HashMap; import java.util.HashSet; import java.util.Map; Some options to get rid of the read/write locks: ConcurrentHashMap or Collections.synchronizedMap */ package org.apache.accumulo.server.conf.store.impl; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map;
codereview_java_data_10150
} @Override - public List<DMLResponseHandler> getMerges() { return this.merges; } why remove final } @Override + public final List<DMLResponseHandler> getMerges() { return this.merges; }
codereview_java_data_10155
MessageExt poll(final KeyValue properties) { int currentPollTimeout = clientConfig.getOperationTimeout(); - if (properties.containsKey("TIMEOUT")) { - currentPollTimeout = properties.getInt("TIMEOUT"); } return poll(currentPollTimeout); } Here,the "TIMEOUT" value can be placed into a constant variable. MessageExt poll(final KeyValue properties) { int currentPollTimeout = clientConfig.getOperationTimeout(); + if (properties.containsKey(NonStandardKeys.TIMEOUT)) { + currentPollTimeout = properties.getInt(NonStandardKeys.TIMEOUT); } return poll(currentPollTimeout); }
codereview_java_data_10164
} } public Production substituteProd(Production prod, Sort expectedSort, BiFunction<Integer, Production, Sort> getSort, HasLocation loc) { Production substituted = prod; List<Sort> args = new ArrayList<>(); This needs a small description. } } + /** + * Generate the substituted production with its sort parameters added for a parametric production. + * @param prod The production to add sort parameters to. + * @param expectedSort the sort context where the term with the specified production appears. + * @param getSort a function taking the 0-based index of the child of this production and the substitutedFresh production and returning the sort of the child. + * @param loc The location to report upon an error. + * @return The production substituted with the least upper bounds of its sort parameters based on its children's sorts. + */ public Production substituteProd(Production prod, Sort expectedSort, BiFunction<Integer, Production, Sort> getSort, HasLocation loc) { Production substituted = prod; List<Sort> args = new ArrayList<>();
codereview_java_data_10165
*/ default <K> Map<K, T> toMapBy(Function<? super T, ? extends K> keyMapper) { Objects.requireNonNull(keyMapper, "keyMapper is null"); - return toMap(keyMapper, v -> v); } /** identity() instead of v -> v */ default <K> Map<K, T> toMapBy(Function<? super T, ? extends K> keyMapper) { Objects.requireNonNull(keyMapper, "keyMapper is null"); + return toMap(keyMapper, identity()); } /**
codereview_java_data_10170
import org.h2.message.DbException; import org.h2.mvstore.DataUtils; import org.h2.mvstore.FileStore; -import org.h2.mvstore.MVMap; import org.h2.mvstore.MVStore; import org.h2.mvstore.MVStoreTool; import org.h2.mvstore.tx.Transaction; A leftover import. import org.h2.message.DbException; import org.h2.mvstore.DataUtils; import org.h2.mvstore.FileStore; import org.h2.mvstore.MVStore; import org.h2.mvstore.MVStoreTool; import org.h2.mvstore.tx.Transaction;
codereview_java_data_10181
protected Store<K, V> kvStore; @After public void tearDown() { if (kvStore != null) { The introduction of `@Before` allows this code to be refactored into a `setUp` method. protected Store<K, V> kvStore; + @Before + public void setUp() { + kvStore = factory.newStore(factory.newConfiguration(factory.getKeyType(), factory.getValueType(), null, null, null)); + } + @After public void tearDown() { if (kvStore != null) {
codereview_java_data_10185
* @author Shane Bryzak * */ -public @RequestScoped @Named class LoginAction { @Inject Identity identity; Put annotations before the public keyword on their own line * @author Shane Bryzak * */ +@RequestScoped +@Named +public class LoginAction { @Inject Identity identity;
codereview_java_data_10196
// This code will even wait on tablets that are assigned to dead tablets servers. This is // intentional because the master may make metadata writes for these tablets. See #587 log.debug( - "Still waiting for table({}) to be deleted, Tablet state to be UNASSIGNED. Tablet state: {} locationState: {}", tableId, state, locationState); done = false; break; ```suggestion "Still waiting for table({}) to be deleted; Target tablet state: UNASSIGNED, Current tablet state: {}, locationState: {}", ``` // This code will even wait on tablets that are assigned to dead tablets servers. This is // intentional because the master may make metadata writes for these tablets. See #587 log.debug( + "Still waiting for table({}) to be deleted; Target tablet state: UNASSIGNED, Current tablet state: {}, locationState: {}", tableId, state, locationState); done = false; break;
codereview_java_data_10201
* <b>Sample Spring XML for Hazelcast Jet Client:</b> * <pre>{@code * <jet:client id="client"> - * <jet:group name="jet" password="jet-pass"/> * <jet:network connection-attempt-limit="3" * connection-attempt-period="3000" * connection-timeout="1000" group password is now removed * <b>Sample Spring XML for Hazelcast Jet Client:</b> * <pre>{@code * <jet:client id="client"> + * <jet:group name="jet"/> * <jet:network connection-attempt-limit="3" * connection-attempt-period="3000" * connection-timeout="1000"
codereview_java_data_10204
"cast", "coalesce", "convert", "csvread", "csvwrite", "currval", "database-path", "database", "decode", "disk-space-used", "file-read", "file-write", "greatest", "h2version", "identity", - "ifnull", "least", "link-schema", "lock-mode", "lock-timeout", "memory-free", "memory-used", "nextval", "nullif", "nvl2", "readonly", "rownum", "schema", "scope-identity", "session-id", - "set", "table", "transaction-id", "truncate-value", "unnest", "user", "last-insert-id" }) { testScript("functions/system/" + s + ".sql"); } for (String s : new String[] { "add_months", "current_date", "current_timestamp", This list is sorted alphabetically. "cast", "coalesce", "convert", "csvread", "csvwrite", "currval", "database-path", "database", "decode", "disk-space-used", "file-read", "file-write", "greatest", "h2version", "identity", + "ifnull", "last-insert-id", "least", "link-schema", "lock-mode", "lock-timeout", "memory-free", "memory-used", "nextval", "nullif", "nvl2", "readonly", "rownum", "schema", "scope-identity", "session-id", + "set", "table", "transaction-id", "truncate-value", "unnest", "user" }) { testScript("functions/system/" + s + ".sql"); } for (String s : new String[] { "add_months", "current_date", "current_timestamp",
codereview_java_data_10206
void completeJob(MasterContext masterContext, long completionTime, Throwable error) { // the order of operations is important. - long jobId = masterContext.getJobId(); String coordinator = nodeEngine.getNode().getThisUuid(); jobRepository.completeJob(jobId, coordinator, completionTime, error); - if (masterContexts.remove(masterContext.getJobId(), masterContext)) { logger.fine(masterContext.jobIdString() + " is completed"); } else { MasterContext existing = masterContexts.get(jobId); should rename this method to `jobId()` as well void completeJob(MasterContext masterContext, long completionTime, Throwable error) { // the order of operations is important. + long jobId = masterContext.jobId(); String coordinator = nodeEngine.getNode().getThisUuid(); jobRepository.completeJob(jobId, coordinator, completionTime, error); + if (masterContexts.remove(masterContext.jobId(), masterContext)) { logger.fine(masterContext.jobIdString() + " is completed"); } else { MasterContext existing = masterContexts.get(jobId);
codereview_java_data_10216
StoredTabletFile metaFile = null; long startTime = System.currentTimeMillis(); - long entriesWritten = 0; - boolean failed = false; CompactionStats stats = new CompactionStats(); try { What does this method do? If its nots quick to explain just let me know, I can look at the source. StoredTabletFile metaFile = null; long startTime = System.currentTimeMillis(); + // create an empty stats object to be populated by CompactableUtils.compact() CompactionStats stats = new CompactionStats(); try {
codereview_java_data_10221
return rel; } if (rowType.getFieldCount() != castRowType.getFieldCount()) { - throw new IllegalArgumentException("Field count is not equal: " + "rowType [" + rowType + "] castRowType [" + castRowType + "]"); } final RexBuilder rexBuilder = rel.getCluster().getRexBuilder(); count is -> counts are return rel; } if (rowType.getFieldCount() != castRowType.getFieldCount()) { + throw new IllegalArgumentException("Field counts are not equal: " + "rowType [" + rowType + "] castRowType [" + castRowType + "]"); } final RexBuilder rexBuilder = rel.getCluster().getRexBuilder();
codereview_java_data_10224
* @param schedulerId threads run taskId. * @param run whether to run. */ - private void updateSchedulerMap(Integer schedulerId, Boolean run) { synchronized (schedulerMap) { Map<Integer, Boolean> copy = new HashMap<Integer, Boolean>(schedulerMap.get()); - copy.put(schedulerId, run); schedulerMap.set(copy); } } The parameter run -> isRun is better? * @param schedulerId threads run taskId. * @param run whether to run. */ + private void updateSchedulerMap(Integer schedulerId, Boolean isRun) { synchronized (schedulerMap) { Map<Integer, Boolean> copy = new HashMap<Integer, Boolean>(schedulerMap.get()); + copy.put(schedulerId, isRun); schedulerMap.set(copy); } }
codereview_java_data_10228
.comment(MainApp.gs(R.string.smb_frequency_exceeded)) .enacted(false).success(false)).run(); } } PumpInterface pump = getActivePump(); isn't there a `return` missing to guard from further execution and still adding it to the `CommandQueue`? .comment(MainApp.gs(R.string.smb_frequency_exceeded)) .enacted(false).success(false)).run(); } + return; } PumpInterface pump = getActivePump();
codereview_java_data_10240
result.onError(t1); return null; } - } finally { - PooledObjects.close(content); } return null; Don't we have try / resources now? result.onError(t1); return null; } } return null;
codereview_java_data_10242
assertEquals("DEFAULT", conf.get(Property.INSTANCE_SECRET)); assertEquals("", conf.get(Property.INSTANCE_VOLUMES)); assertEquals("120s", conf.get(Property.GENERAL_RPC_TIMEOUT)); - @SuppressWarnings("deprecation") - Property deprecatedProp = Property.TSERV_WALOG_MAX_SIZE; - assertEquals("1G", conf.get(conf.resolve(Property.TSERV_WAL_MAX_SIZE, deprecatedProp))); assertEquals("org.apache.accumulo.core.spi.crypto.NoCryptoService", conf.get(Property.INSTANCE_CRYPTO_SERVICE)); } Since this test is just testing the default values for a bunch of props not set in a config file, it'd be fine to just use the new prop, without calling `conf.resolve`. assertEquals("DEFAULT", conf.get(Property.INSTANCE_SECRET)); assertEquals("", conf.get(Property.INSTANCE_VOLUMES)); assertEquals("120s", conf.get(Property.GENERAL_RPC_TIMEOUT)); + assertEquals("1G", conf.get(Property.TSERV_WAL_MAX_SIZE)); assertEquals("org.apache.accumulo.core.spi.crypto.NoCryptoService", conf.get(Property.INSTANCE_CRYPTO_SERVICE)); }
codereview_java_data_10249
try { dockerUtils.pull(task.getTaskInfo().getContainer().getDocker().getImage()); } catch (DockerException e) { - throw new ProcessFailedException(String.format("Could not pull docker image due to error: %s", e)); } } Don't add the exception to an error message, include the exception as a cause argument. try { dockerUtils.pull(task.getTaskInfo().getContainer().getDocker().getImage()); } catch (DockerException e) { + throw new ProcessFailedException("Could not pull docker image", e); } }
codereview_java_data_10253
this.plannerFactory = Objects.requireNonNull(plannerFactory, "plannerFactory"); this.conformance = Objects.requireNonNull(conformance, "conformance"); this.contextTransform = Objects.requireNonNull(contextTransform, "contextTransform"); - this.typeFactory = typeFactory; } public RelRoot convertSqlToRel(String sql) { I would create a overloaded version of this constructor so that the below codes remains unchanged this.plannerFactory = Objects.requireNonNull(plannerFactory, "plannerFactory"); this.conformance = Objects.requireNonNull(conformance, "conformance"); this.contextTransform = Objects.requireNonNull(contextTransform, "contextTransform"); + this.typeFactorySupplier = Objects.requireNonNull(typeFactorySupplier, "typeFactorySupplier"); } public RelRoot convertSqlToRel(String sql) {
codereview_java_data_10276
MISSING_HOOK_OCAML, MISSING_SYNTAX_MODULE, INVALID_EXIT_CODE, - DEPRECATED_BACKEND, INVALID_CONFIG_VAR, FUTURE_ERROR, UNUSED_VAR, I think backend-specific things should not be in this list. So we should just have `MISSING_HOOK`, instead of `MISSING_HOOK_OCAML` or `MISSING_HOOK_JAVA`. And we should get rid of `DEPRECATED_BACKEND` and just use `FUTURE_ERROR`. MISSING_HOOK_OCAML, MISSING_SYNTAX_MODULE, INVALID_EXIT_CODE, INVALID_CONFIG_VAR, FUTURE_ERROR, UNUSED_VAR,
codereview_java_data_10278
isContributionsFragmentVisible = false; updateMenuItem(); // Do all permission and GPS related tasks on tab selected, not on create - ((NearbyParentFragment)contributionsActivityPagerAdapter.getItem(1)).nearbyParentFragmentPresenter.onTabSelected(); break; default: tabLayout.getTabAt(CONTRIBUTIONS_TAB_POSITION).select(); Why is this referring to child fragment's presenter. We should ideally just let the fragment take care of it, this should just inform the fragment that the tab is selected. Also, is there a way the fragment could determine by itself that it is visible and in resumed state, if that is what we are trying to achieve. isContributionsFragmentVisible = false; updateMenuItem(); // Do all permission and GPS related tasks on tab selected, not on create + NearbyParentFragmentPresenter.getInstance().onTabSelected(); break; default: tabLayout.getTabAt(CONTRIBUTIONS_TAB_POSITION).select();
codereview_java_data_10282
*/ package zipkin2.internal; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; Dunno if it's kosher for this codebase but awaitility makes these sort of tests simpler without having to worry about latches */ package zipkin2.internal; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;
codereview_java_data_10284
import java.util.Optional; import java.util.concurrent.ExecutionException; -import static com.github.javaparser.ParseStart.*; -import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; import static com.github.javaparser.Providers.provider; /** Yes, I should have written this a long time ago... import java.util.Optional; import java.util.concurrent.ExecutionException; +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.BLEEDING_EDGE; import static com.github.javaparser.Providers.provider; /**
codereview_java_data_10286
for (Account account: preferences.getAccounts()) { if (accountUuids.contains(account.getUuid())) { LocalStore localStore = DI.get(LocalStoreProvider.class).getInstance(account); - LocalFolder.createLocalFolder(localStore, Account.OUTBOX, outboxName); } } Please move the dependency lookup outside of the loop. for (Account account: preferences.getAccounts()) { if (accountUuids.contains(account.getUuid())) { LocalStore localStore = DI.get(LocalStoreProvider.class).getInstance(account); + localStore.createLocalFolder(Account.OUTBOX, Account.OUTBOX_NAME); } }
codereview_java_data_10298
closeData(); - BCFile.Writer.BlockAppender mba = fileWriter.prepareMetaBlock("RFile.index"); mba.writeInt(RINDEX_MAGIC); mba.writeInt(RINDEX_VER_8); Could just use BlockAppender here with an import closeData(); + BlockAppender mba = fileWriter.prepareMetaBlock("RFile.index"); mba.writeInt(RINDEX_MAGIC); mba.writeInt(RINDEX_VER_8);
codereview_java_data_10303
public abstract void fireBeforeSelectTriggers(); /** - * Indicate to this query that it is an exists subquery. */ public abstract void setExistsSubquery(boolean isExistsSubquery); Indicate to this query that it is wrapped inside an EXISTS() public abstract void fireBeforeSelectTriggers(); /** + * Indicate to this query that it is wrapped inside an EXISTS(). */ public abstract void setExistsSubquery(boolean isExistsSubquery);
codereview_java_data_10306
} public static void clearCache(Instance instance) { - cacheResetCount.incrementAndGet(); getZooCache(instance).clear(ZooUtil.getRoot(instance) + Constants.ZTABLES); getZooCache(instance).clear(ZooUtil.getRoot(instance) + Constants.ZNAMESPACES); - tableMapCache = null; } /** There is also a clearCacheByPath method where this should be set to null } public static void clearCache(Instance instance) { getZooCache(instance).clear(ZooUtil.getRoot(instance) + Constants.ZTABLES); getZooCache(instance).clear(ZooUtil.getRoot(instance) + Constants.ZNAMESPACES); + instanceToMapCache.invalidateAll(); } /**
codereview_java_data_10309
this.key = key; } /** * Returns the grouping key. */ I think it would be better to implement Map.Entry here, or extend `TimestampedEntry` so that it can be directly written to map sink. WindowResult can be perhaps an interface? this.key = key; } + /** + * @param start start time of the window + * @param end end time of the window + * @param key grouping key + * @param result result of aggregation + */ + public KeyedWindowResult(long start, long end, @Nonnull K key, @Nonnull R result) { + this(start, end, key, result, false); + } + /** * Returns the grouping key. */
codereview_java_data_10316
@Override public String toString() { return MoreObjects.toStringHelper(this) - .add("dataFilesCount", dataFilesCount.get()) - .add("dataFilesRecordCount", dataFilesRecordCount.get()) - .add("dataFilesByteCount", dataFilesByteCount.get()) - .add("deleteFilesCount", deleteFilesCount.get()) - .add("deleteFilesRecordCount", deleteFilesRecordCount.get()) .add("deleteFilesByteCount", deleteFilesByteCount) .toString(); } Missed a get? @Override public String toString() { return MoreObjects.toStringHelper(this) + .add("dataFilesCount", dataFilesCount) + .add("dataFilesRecordCount", dataFilesRecordCount) + .add("dataFilesByteCount", dataFilesByteCount) + .add("deleteFilesCount", deleteFilesCount) + .add("deleteFilesRecordCount", deleteFilesRecordCount) .add("deleteFilesByteCount", deleteFilesByteCount) .toString(); }
codereview_java_data_10317
} public void onResume() { super.onResume(); I couldn't see the alternate code for this method. } + @Override + @NavigationDrawerType + public int getNavigationDrawerType() { + return ITEM_ALERT; + } + public void onResume() { super.onResume();
codereview_java_data_10322
// END FLOW-CONTROL STATE - public ReceiverTasklet(OutboundCollector collector, int rwinMultiplier, int flowControlPeriodMs, - LoggingService loggingService) { this.collector = collector; this.rwinMultiplier = rwinMultiplier; this.flowControlPeriodNs = (double) MILLISECONDS.toNanos(flowControlPeriodMs); - this.logger = loggingService.getLogger(getClass()); this.receiveWindowCompressed = INITIAL_RECEIVE_WINDOW_COMPRESSED; } how does this add context? for example, which edge this receiver is corresponding to? // END FLOW-CONTROL STATE + public ReceiverTasklet( + OutboundCollector collector, int rwinMultiplier, int flowControlPeriodMs, + LoggingService loggingService, String debugName + ) { this.collector = collector; this.rwinMultiplier = rwinMultiplier; this.flowControlPeriodNs = (double) MILLISECONDS.toNanos(flowControlPeriodMs); + this.logger = loggingService.getLogger(getClass().getName() + '.' + debugName); this.receiveWindowCompressed = INITIAL_RECEIVE_WINDOW_COMPRESSED; }
codereview_java_data_10330
@Test public void testPrintHelloWorld() throws Exception { - String xpath = "//ASTTermApplyNode/ASTTermNameNode[@Image=\"println\"]"; rule.setXPath(xpath); rule.setVersion(XPathRuleQuery.XPATH_2_0); Report report = getReportForTestString(rule, Yes, I'd say we should go without "AST" and without "Node"... Then this becomes: `//TermApply/TermName[@Image='println']` @Test public void testPrintHelloWorld() throws Exception { + String xpath = "//TermApply/TermName[@Image=\"println\"]"; rule.setXPath(xpath); rule.setVersion(XPathRuleQuery.XPATH_2_0); Report report = getReportForTestString(rule,
codereview_java_data_10336
try { if (userpoolsLoginKey.equals(mStore.get(PROVIDER_KEY))) { String token = mStore.get("token"); - return (String) CognitoJWTParser.getPayload(token).get("sub"); } return null; } catch (Exception e) { is this equivalent to the following? ``` return CognitoJWTParser.getClaim(token, "sub"); ``` try { if (userpoolsLoginKey.equals(mStore.get(PROVIDER_KEY))) { String token = mStore.get("token"); + return CognitoJWTParser.getClaim(token, "sub"); } return null; } catch (Exception e) {
codereview_java_data_10340
} } - public void onCryptoModeChanged(CryptoMode type) { - recipientPresenter.onCryptoModeChanged(type); } enum Action { `type` as parameter name seems odd. } } + @Override + public void onCryptoModeChanged(CryptoMode cryptoMode) { + recipientPresenter.onCryptoModeChanged(cryptoMode); } enum Action {
codereview_java_data_10347
} } public Row getTemplateRow() { return database.createRow(new Value[getColumns().length], Row.MEMORY_CALCULATE); } this is a little icky, it means that the columns field no longer always applies to the Table class. Probably better to create an AbstractTable class to act as the common base class for this and TableSynonym } } + @Override public Row getTemplateRow() { return database.createRow(new Value[getColumns().length], Row.MEMORY_CALCULATE); }
codereview_java_data_10356
values[i] = SortOrder.valueOf(valueStrs[i]); } - int idxCurrentSort = -1; for (int i = 0; i < values.length; i++) { - if (currentSortOrder == values[i] || currentSortOrder == null) { idxCurrentSort = i; break; } Thanks for looking into this. I think it looks a bit strange to have this check inside the for loop. Wouldn't it also work to initialize `idxCurrentSort` with 0 instead? values[i] = SortOrder.valueOf(valueStrs[i]); } + int idxCurrentSort = 0; for (int i = 0; i < values.length; i++) { + if (currentSortOrder == values[i]) { idxCurrentSort = i; break; }
codereview_java_data_10363
* @param consumer * emit counter objects derived from key and value to this consumer */ - void convert(Key k, Consumer<K> consumer); } /** This looks like it shouldn't be removed. * @param consumer * emit counter objects derived from key and value to this consumer */ + void convert(Key k, Value v, Consumer<K> consumer); } /**
codereview_java_data_10377
args.put("endpoints.shutdown.enabled", "true"); ModuleLaunchRequest moduleLaunchRequest = new ModuleLaunchRequest(module); launcher.launch(Arrays.asList(moduleLaunchRequest)); ModuleDeploymentId id = new ModuleDeploymentId(request.getDefinition().getGroup(), request.getDefinition().getLabel()); these 2 args need to be qualified also args.put("endpoints.shutdown.enabled", "true"); ModuleLaunchRequest moduleLaunchRequest = new ModuleLaunchRequest(module); + moduleLaunchRequest.setArguments(args); launcher.launch(Arrays.asList(moduleLaunchRequest)); ModuleDeploymentId id = new ModuleDeploymentId(request.getDefinition().getGroup(), request.getDefinition().getLabel());
codereview_java_data_10388
public boolean isPrimitive() { return clazz.isPrimitive(); } - - // not an override - public boolean equals(JavaTypeDefinition def) { // TODO: JavaTypeDefinition generic equality return clazz.equals(def.clazz) && getTypeParameterCount() == def.getTypeParameterCount(); } I think I have already asked, but can't recall... why is this not an override? public boolean isPrimitive() { return clazz.isPrimitive(); } + + public boolean equivalent(JavaTypeDefinition def) { // TODO: JavaTypeDefinition generic equality return clazz.equals(def.clazz) && getTypeParameterCount() == def.getTypeParameterCount(); }
codereview_java_data_10390
private HttpRequestFactory httpRequestFactory; private Optional<EthNetworkConfig> ethNetworkConfig = Optional.empty(); private boolean useWsForJsonRpc = false; - private boolean useAuthenticationTokenInHeaderForJsonRpc = false; private String token = null; public PantheonNode( Can probably simplify this boolean out by either making token an Optional<String> or checking token != null private HttpRequestFactory httpRequestFactory; private Optional<EthNetworkConfig> ethNetworkConfig = Optional.empty(); private boolean useWsForJsonRpc = false; private String token = null; public PantheonNode(
codereview_java_data_10392
assertEquals("mysecret", conf.get(Property.INSTANCE_SECRET)); assertEquals("hdfs://localhost:8020/accumulo123", conf.get(Property.INSTANCE_VOLUMES)); assertEquals("123s", conf.get(Property.GENERAL_RPC_TIMEOUT)); - @SuppressWarnings("deprecation") - Property deprecatedProp = Property.TSERV_WALOG_MAX_SIZE; - assertEquals("256M", conf.get(conf.resolve(Property.TSERV_WAL_MAX_SIZE, deprecatedProp))); assertEquals("org.apache.accumulo.core.spi.crypto.AESCryptoService", conf.get(Property.INSTANCE_CRYPTO_SERVICE)); assertEquals(System.getenv("USER"), conf.get("general.test.user.name")); Since this test is just testing that we can read the file correctly, we don't need to check the deprecated prop, just the new one, so there's no need to do `conf.resolve` here. I see that you already updated the config file to use the new prop, anyway, so just checking the new prop should suffice. That is, unless you wanted this to serve as a test for `conf.resolve` itself... but I assume that's already unit tested elsewhere. assertEquals("mysecret", conf.get(Property.INSTANCE_SECRET)); assertEquals("hdfs://localhost:8020/accumulo123", conf.get(Property.INSTANCE_VOLUMES)); assertEquals("123s", conf.get(Property.GENERAL_RPC_TIMEOUT)); + assertEquals("256M", conf.get(Property.TSERV_WAL_MAX_SIZE)); assertEquals("org.apache.accumulo.core.spi.crypto.AESCryptoService", conf.get(Property.INSTANCE_CRYPTO_SERVICE)); assertEquals(System.getenv("USER"), conf.get("general.test.user.name"));
codereview_java_data_10395
public class Kafka8MessageTimestamp implements KafkaMessageTimestamp { @Override - public Long getTimestamp(MessageAndMetadata<byte[], byte[]> kafkaMessage) { return 0l; } @Override - public Long getTimestamp(MessageAndOffset messageAndOffset) { return 0l; } } Looks like both k8 and k10 will return a valid long, should the method now return a small long instead of big Long? public class Kafka8MessageTimestamp implements KafkaMessageTimestamp { @Override + public long getTimestamp(MessageAndMetadata<byte[], byte[]> kafkaMessage) { return 0l; } @Override + public long getTimestamp(MessageAndOffset messageAndOffset) { return 0l; } }
codereview_java_data_10398
* @param preInvocationAdvice the {@link PreInvocationAuthorizationAdvice} to use * @param postInvocationAdvice the {@link PostInvocationAuthorizationAdvice} to use */ - public PrePostAdviceReactiveMethodInterceptor(MethodSecurityMetadataSource attributeSource, PreInvocationAuthorizationReactiveAdvice preInvocationAdvice, PostInvocationAuthorizationAdvice postInvocationAdvice) { Assert.notNull(attributeSource, "attributeSource cannot be null"); Assert.notNull(preInvocationAdvice, "preInvocationAdvice cannot be null"); Assert.notNull(postInvocationAdvice, "postInvocationAdvice cannot be null"); This is a breaking change that we cannot make. We would need to add another constructor * @param preInvocationAdvice the {@link PreInvocationAuthorizationAdvice} to use * @param postInvocationAdvice the {@link PostInvocationAuthorizationAdvice} to use */ + public PrePostAdviceReactiveMethodInterceptor(MethodSecurityMetadataSource attributeSource, PreInvocationAuthorizationAdvice preInvocationAdvice, PostInvocationAuthorizationAdvice postInvocationAdvice) { Assert.notNull(attributeSource, "attributeSource cannot be null"); Assert.notNull(preInvocationAdvice, "preInvocationAdvice cannot be null"); Assert.notNull(postInvocationAdvice, "postInvocationAdvice cannot be null");
codereview_java_data_10402
return context.getContentResolver().acquireContentProviderClient(CONTRIBUTION_AUTHORITY); } - @Provides - @Named("revertCount") - public SharedPreferences provideRevertCountSharedPreferences( Context context) { - return context.getSharedPreferences("revertCount", MODE_PRIVATE); - } - @Provides @Named("modification") public ContentProviderClient provideModificationContentProviderClient(Context context) { Do we really need a separate shared pref for revert counts? It could be part of default prefs itself. Your call. :) If you feel the need for a separate pref then I would suggest renaming it to something more generic such as `userStatistics` pref. return context.getContentResolver().acquireContentProviderClient(CONTRIBUTION_AUTHORITY); } @Provides @Named("modification") public ContentProviderClient provideModificationContentProviderClient(Context context) {
codereview_java_data_10403
"\t| | | | / | | | | | | | \\ | | | \n" + "\to o o o o---o o---o o---o o---o o o o---o o o--o o---o o "); logger.info("Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved."); - - Runtime.getRuntime().addShutdownHook(shutdownHookThread); } /** I would move this line up before the logs are printed "\t| | | | / | | | | | | | \\ | | | \n" + "\to o o o o---o o---o o---o o---o o o o---o o o--o o---o o "); logger.info("Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved."); } /**
codereview_java_data_10404
Stage stageOne = (Stage) cmmnModel.getPrimaryCase().getPlanModel().findPlanItemDefinitionInStageOrDownwards("stageOne"); List<PlanItem> planItems1 = stageOne.getPlanItems(); assertThat(planItems1).hasSize(1); - assertThat(planItems1) - .extracting(planItem2 -> planItem2.getItemControl(), - planItem2 -> planItem2.getItemControl().getParentCompletionRule()) - .doesNotContainNull(); - assertThat(planItems1.get(0).getItemControl().getParentCompletionRule().getType()).isEqualTo(ParentCompletionRule.IGNORE_AFTER_FIRST_COMPLETION); } } The extracting from assertJ is really powerful, but I don't think that ti fits the purpose everywhere. In this case the new assertions are more difficult to follow (at least to me) Stage stageOne = (Stage) cmmnModel.getPrimaryCase().getPlanModel().findPlanItemDefinitionInStageOrDownwards("stageOne"); List<PlanItem> planItems1 = stageOne.getPlanItems(); assertThat(planItems1).hasSize(1); + PlanItem planItem = planItems1.get(0); + assertThat(planItem.getItemControl()).isNotNull(); + assertThat(planItem.getItemControl().getParentCompletionRule()).isNotNull(); + assertThat(planItem.getItemControl().getParentCompletionRule().getType()).isEqualTo(ParentCompletionRule.IGNORE_AFTER_FIRST_COMPLETION); } }
codereview_java_data_10416
import java.util.Date; import java.util.HashMap; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; This does not seem to be used anywhere. unused import? import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Random; import java.util.Set;
codereview_java_data_10431
Claims claims = Jwts.claims().setSubject(userName); return Jwts.builder().setClaims(claims).setExpiration(validity) - .signWith(Keys.hmacShaKeyFor(Decoders.BASE64.decode(authConfigs.getSecretKey())), - SignatureAlgorithm.HS256).compact(); } /** Please double check this part. Why Jwts need to decode base 64 by ourselves. Claims claims = Jwts.claims().setSubject(userName); return Jwts.builder().setClaims(claims).setExpiration(validity) + .signWith(Keys.hmacShaKeyFor(authConfigs.getSecretKeyBytes()), SignatureAlgorithm.HS256).compact(); } /**
codereview_java_data_10432
final HashSet<T> set = (HashSet<T>) elements; return set; } - if (Collections.isEmpty(elements) || this.equals(elements)){ return this; } else { - return new HashSet<>(addAll(tree, elements)); } } The new way is only better when this HashSet and the elements are equal but it adds an overhead for all other cases. Please restore the previous version. final HashSet<T> set = (HashSet<T>) elements; return set; } + final HashArrayMappedTrie<T, T> that = addAll(tree, elements); + if (that.size() == tree.size()) { return this; } else { + return new HashSet<>(that); } }
codereview_java_data_10433
LOG.fine("Adding host: " + host.asSummary()); hosts.add(host); - LOG.info(String.format("Added node %s.", node.getId().toUuid())); host.runHealthCheck(); Runnable runnable = host::runHealthCheck; Prefer adding a `toString` to `NodeId`. LOG.fine("Adding host: " + host.asSummary()); hosts.add(host); + LOG.info(String.format("Added node %s.", node.getId().toString())); host.runHealthCheck(); Runnable runnable = host::runHealthCheck;
codereview_java_data_10439
} /** - * @return true if struct represents union schema */ - public boolean isUnionSchema() { - return isUnionSchema; } } Why do we need this in the main API? The API should not expose unions or info about union IMO. } /** + * @return true if struct represents union schema converted to struct type */ + public boolean isConvertedFromUnionSchema() { + return convertedFromUnionSchema; } }
codereview_java_data_10446
@Override public void setDataSource(String streamUrl, String username, String password) { } } Should this call the method without username and password? @Override public void setDataSource(String streamUrl, String username, String password) { + try { + setDataSource(streamUrl); + } catch (IllegalArgumentException e) { + Log.e(TAG, e.toString()); + } catch (IllegalStateException e) { + Log.e(TAG, e.toString()); + } catch(IOException e) { + Log.e(TAG, e.toString()); + } } }
codereview_java_data_10448
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration; import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.dataflow.server.completion.TapOnDestinationRecoveryStrategy; import org.springframework.cloud.dataflow.server.controller.StreamDefinitionController; import org.springframework.cloud.dataflow.server.repository.InMemoryStreamDefinitionRepository; these are no longer in proper alphabetical order after the name change... should re-org imports not just replace the strings import org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration; import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.cloud.dataflow.artifact.registry.ArtifactRegistry; +import org.springframework.cloud.dataflow.artifact.registry.RedisArtifactRegistry; +import org.springframework.cloud.dataflow.completion.CompletionConfiguration; +import org.springframework.cloud.dataflow.completion.RecoveryStrategy; +import org.springframework.cloud.dataflow.completion.StreamCompletionProvider; import org.springframework.cloud.dataflow.server.completion.TapOnDestinationRecoveryStrategy; import org.springframework.cloud.dataflow.server.controller.StreamDefinitionController; import org.springframework.cloud.dataflow.server.repository.InMemoryStreamDefinitionRepository;
codereview_java_data_10450
List<ByteBuffer> args = Arrays.asList(ByteBuffer.wrap(tableName.getBytes(UTF_8))); Map<String,String> opts = new HashMap<>(); try { - cancelCompaction(tableName); doTableFateOperation(tableName, TableNotFoundException.class, FateOperation.TABLE_DELETE, args, opts); } catch (TableExistsException e) { To avoid certain race conditions, it would be nice if we did something like the following to only resolve the tableName to a tableId once. However I don't see an easy way to do this. 1. tableId = resolveTableId(tableName) 2. cancelCompaction(tableId) 3. delete(tableId) Looking around in the code, this would be easy for cancelCompaction because it already resolves the table id client side. So could create `private cancelCompaction(TableId)` used by this method and the public `cancelCompaction(String)` method. However delete table seems like its currently passing the table name to the server side where it would resolve the table name to a table id server side. I may have missed it but I tried to follow the code to the thrift call and did not see anything on the client side resolving the table id for delete table. List<ByteBuffer> args = Arrays.asList(ByteBuffer.wrap(tableName.getBytes(UTF_8))); Map<String,String> opts = new HashMap<>(); try { doTableFateOperation(tableName, TableNotFoundException.class, FateOperation.TABLE_DELETE, args, opts); } catch (TableExistsException e) {
codereview_java_data_10451
// default network option // Then we have no control over genesis default value here. @CommandLine.Option( - names = {"--private-genesis-file"}, paramLabel = MANDATORY_FILE_FORMAT_HELP, description = - "The path to genesis file. Setting this option makes --chain option ignored and requires --network-id to be set." ) final File genesisFile = null; } We seem to have come back to calling this `--genesis-file` instead of `--private-genesis-file` but doesn't need to be changed as part of this PR. Also I think the description should be referring to the `--network` option not the `--chain` option. // default network option // Then we have no control over genesis default value here. @CommandLine.Option( + names = {"--genesis-file"}, paramLabel = MANDATORY_FILE_FORMAT_HELP, description = + "The path to genesis file. Setting this option makes --network option ignored and requires --network-id to be set." ) final File genesisFile = null; }
codereview_java_data_10455
assertTrue(scopes.contains(IteratorScope.majc)); Map<String,String> config = tops.getConfiguration(MetadataTable.NAME); - HashMap<String,String> properties = new HashMap<>(); - config.forEach(properties::put); for (IteratorScope scope : scopes) { String key = Property.TABLE_ITERATOR_PREFIX.getKey() + scope.name() + "." Another opportunity for `Map.copyOf` assertTrue(scopes.contains(IteratorScope.majc)); Map<String,String> config = tops.getConfiguration(MetadataTable.NAME); + Map<String,String> properties = Map.copyOf(config); for (IteratorScope scope : scopes) { String key = Property.TABLE_ITERATOR_PREFIX.getKey() + scope.name() + "."
codereview_java_data_10460
boolean transferOK = HAService.this.push2SlaveMaxOffset.get() >= req.getNextOffset(); long waitUntillWhen = HAService.this.defaultMessageStore.getSystemClock().now() + HAService.this.defaultMessageStore.getMessageStoreConfig().getSyncFlushTimeout(); - while (HAService.this.defaultMessageStore.getSystemClock().now() < waitUntillWhen) { this.notifyTransferObject.waitForRunning(1000); transferOK = HAService.this.push2SlaveMaxOffset.get() >= req.getNextOffset(); - if (transferOK) { - break; - } } if (!transferOK) { you should check transferok to reduce unnecessary block boolean transferOK = HAService.this.push2SlaveMaxOffset.get() >= req.getNextOffset(); long waitUntillWhen = HAService.this.defaultMessageStore.getSystemClock().now() + HAService.this.defaultMessageStore.getMessageStoreConfig().getSyncFlushTimeout(); + while (!transferOK && HAService.this.defaultMessageStore.getSystemClock().now() < waitUntillWhen) { this.notifyTransferObject.waitForRunning(1000); transferOK = HAService.this.push2SlaveMaxOffset.get() >= req.getNextOffset(); } if (!transferOK) {
codereview_java_data_10464
args.add(ByteBuffer.wrap(String.valueOf(numSplits).getBytes(UTF_8))); if (numSplits > 0) { for (Text t : ntc.getSplits()) { - args.add(ByteBuffer.wrap(t.toString().getBytes(UTF_8))); } } Splits may be binary data. Converting Text to a String and then to a ByteBuffer could scramble the binary data (because it encodes and then decodes utf-8). I would recommend doing `args.add(TextUtil. getByteBuffer(t))`. Using TextUtil properly handles the edge case where Text has a byte array thats longer than its length. args.add(ByteBuffer.wrap(String.valueOf(numSplits).getBytes(UTF_8))); if (numSplits > 0) { for (Text t : ntc.getSplits()) { + args.add(TextUtil.getByteBuffer(t)); } }
codereview_java_data_10474
@Override public Cursor getCursor() { - return DatabaseFactory.getImageDatabase(getContext()).getMediaForThread(threadId); } } } getImageDatabase(...) -> getMediaDatabase(...) in DatabaseFactory @Override public Cursor getCursor() { + return DatabaseFactory.getMediaDatabase(getContext()).getMediaForThread(threadId); } } }
codereview_java_data_10489
} @Override - public ImmutableList<String> struct(Types.StructType readStruct, Iterable<List<String>> fieldErrorLists) { Preconditions.checkNotNull(readStruct, "Evaluation must start with a schema."); if (!currentType.isStructType()) { We don't typically use `ImmutableList` to avoid leaking it in methods that are accidentally public or purposely part of the API. I'm +1 for returning `ImmutableList.copyOf(errors)` below, but I don't think we should guarantee the list will be an `ImmutableList`. } @Override + public List<String> struct(Types.StructType readStruct, Iterable<List<String>> fieldErrorLists) { Preconditions.checkNotNull(readStruct, "Evaluation must start with a schema."); if (!currentType.isStructType()) {
codereview_java_data_10496
} public void decrementOpenFiles(int numOpenFiles) { - openFiles.addAndGet(numOpenFiles); } @Override In the cases where this is used, will the value of `openFiles` ever actually be decremented? It looks like `incrementOpenFiles()` and `decrementOpenFiles()` will both do the same thing at the moment. Is the idea that we always pass a negative number to `decrementOpenFiles()`? } public void decrementOpenFiles(int numOpenFiles) { + openFiles.addAndGet(numOpenFiles > 0 ? numOpenFiles : numOpenFiles * -1); } @Override
codereview_java_data_10506
// drop wal walPath = walPath.getParent(); - walPath = new Path(walPath, - FileType.RECOVERY.getDirectory() + '-' + context.getUniqueNameAllocator().getNextName()); - log.debug("Unique Name Allocated: " + walPath); walPath = new Path(walPath, uuid); return walPath; ```suggestion log.debug("Directory selected for WAL recovery: " + walPath); ``` // drop wal walPath = walPath.getParent(); + walPath = new Path(walPath, FileType.RECOVERY.getDirectory() + ' ' + context.whoami()); walPath = new Path(walPath, uuid); return walPath;
codereview_java_data_10509
* @param member {@link Member} */ public static void onSuccess(Member member) { manager.getMemberAddressInfos().add(member.getAddress()); member.setState(NodeState.UP); member.setFailAccessCnt(0); - manager.notifyMemberChange(); } public static void onFail(Member member) { Whether will cause always notify change? * @param member {@link Member} */ public static void onSuccess(Member member) { + final NodeState old = member.getState(); manager.getMemberAddressInfos().add(member.getAddress()); member.setState(NodeState.UP); member.setFailAccessCnt(0); + if (!Objects.equals(old, member.getState())) { + manager.notifyMemberChange(); + } } public static void onFail(Member member) {
codereview_java_data_10518
* best-practice to set uid for all operators</a> before deploying to production. Flink has an option to {@code * pipeline.auto-generate-uids=false} to disable auto-generation and force explicit setting of all operator uids. * <br><br> - * Be careful with setting this for an existing job, because now we are changing the opeartor uid from an * auto-generated one to this new value. When deploying the change with a checkpoint, Flink won't be able to restore * the previous Flink sink operator state (more specifically the committer operator state). You need to use {@code * --allowNonRestoredState} to ignore the previous sink state. During restore Flink sink state is used to check if `opeartor` ? typo ? * best-practice to set uid for all operators</a> before deploying to production. Flink has an option to {@code * pipeline.auto-generate-uids=false} to disable auto-generation and force explicit setting of all operator uids. * <br><br> + * Be careful with setting this for an existing job, because now we are changing the operator uid from an * auto-generated one to this new value. When deploying the change with a checkpoint, Flink won't be able to restore * the previous Flink sink operator state (more specifically the committer operator state). You need to use {@code * --allowNonRestoredState} to ignore the previous sink state. During restore Flink sink state is used to check if
codereview_java_data_10520
assertThatThrownBy(() -> runtimeService.startProcessInstanceByKey("failStatusCodes")) .isExactlyInstanceOf(FlowableException.class) .hasMessage("HTTP400"); - assertThat(process).as("Process instance was not started.").isNull(); } @Test This is always null since `process` is never re-assigned assertThatThrownBy(() -> runtimeService.startProcessInstanceByKey("failStatusCodes")) .isExactlyInstanceOf(FlowableException.class) .hasMessage("HTTP400"); } @Test
codereview_java_data_10525
// snippet-sourcetype:[snippet] // snippet-sourcedate:[2019-01-10] // snippet-sourceauthor:[AWS] - /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Do you mean TranscriptResultStream? Also, second sentence needs a period: ...for more details. // snippet-sourcetype:[snippet] // snippet-sourcedate:[2019-01-10] // snippet-sourceauthor:[AWS] +// snippet-start:[transcribe.java-streaming-client-behavior-imp] /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
codereview_java_data_10526
private static final int DEFAULT_WORLD_STATE_MAX_REQUESTS_WITHOUT_PROGRESS = 1000; private static final long DEFAULT_WORLD_STATE_MIN_MILLIS_BEFORE_STALLING = TimeUnit.MINUTES.toMillis(5); - private static final int DEFAULT_MAX_GET_BLOCK_HEADERS = 192; - private static final int DEFAULT_MAX_GET_BLOCK_BODIES = 128; - private static final int DEFAULT_MAX_GET_RECEIPTS = 256; - private static final int DEFAULT_MAX_GET_NODE_DATA = 384; // Fast sync config private final int fastSyncPivotDistance; These constants aren't really related to the synchronizer, I'd move them to `EthServer` or `EthProtocolManager` private static final int DEFAULT_WORLD_STATE_MAX_REQUESTS_WITHOUT_PROGRESS = 1000; private static final long DEFAULT_WORLD_STATE_MIN_MILLIS_BEFORE_STALLING = TimeUnit.MINUTES.toMillis(5); // Fast sync config private final int fastSyncPivotDistance;
codereview_java_data_10537
this.master = master; existenceCache = CacheBuilder.newBuilder().expireAfterWrite(timeToCacheExistsInMillis, TimeUnit.MILLISECONDS) - .maximumWeight(10000000).weigher(new Weigher<Path,Boolean>() { @Override public int weigh(Path path, Boolean exist) { return path.toString().length(); Weigher is a functional interface. You can use a lambda here. Also, you can use underscores to make the number more readable: ```java .maximumWeight(10_000_000).weigher((path, exist) -> path.toString().length()).build(); ``` this.master = master; existenceCache = CacheBuilder.newBuilder().expireAfterWrite(timeToCacheExistsInMillis, TimeUnit.MILLISECONDS) + .maximumWeight(10_000_000).weigher(new Weigher<Path,Boolean>() { @Override public int weigh(Path path, Boolean exist) { return path.toString().length();
codereview_java_data_10539
@Override public ConnectionType setNetworkConnection( ConnectionType type) { - Map<String, Integer> mode = ImmutableMap.of("type", type.getBitMask()); return new ConnectionType(((Number) executeMethod.execute(DriverCommand.SET_NETWORK_CONNECTION, ImmutableMap .of("parameters", mode))) can you change this instead to just `type.toString()` and then you wouldn't have to expose the getBitMask in the enum. (Alternatively you could have used `type.hashCode()` but that doesn't feel as nice) @Override public ConnectionType setNetworkConnection( ConnectionType type) { + Map<String, ConnectionType> mode = ImmutableMap.of("type", type); return new ConnectionType(((Number) executeMethod.execute(DriverCommand.SET_NETWORK_CONNECTION, ImmutableMap .of("parameters", mode)))
codereview_java_data_10544
/** * We use map because there can be nested, anonymous etc classes. */ - private Map<String, JavaClassObject> classObjectsByName = new HashMap<>(); private SecureClassLoader classLoader = new SecureClassLoader() { This field needs to have default visibility to avoid synthetic access. /** * We use map because there can be nested, anonymous etc classes. */ + Map<String, JavaClassObject> classObjectsByName = new HashMap<>(); private SecureClassLoader classLoader = new SecureClassLoader() {
codereview_java_data_10547
*/ package tech.pegasys.pantheon.consensus.ibft; -import tech.pegasys.pantheon.ethereum.core.Address; import tech.pegasys.pantheon.ethereum.p2p.api.Message; -import tech.pegasys.pantheon.ethereum.p2p.api.MessageData; - -import java.util.List; public interface Gossiper { - boolean gossipMessage(Message message); - - boolean send(MessageData messageData, List<Address> excludeAddressesList); } This form of gossip where we haven't got the original message is never going to have excluded addresses so perhaps just remove that argument? */ package tech.pegasys.pantheon.consensus.ibft; import tech.pegasys.pantheon.ethereum.p2p.api.Message; public interface Gossiper { + void gossipMessage(Message message); }
codereview_java_data_10552
case NOT_EQ: return String.valueOf(ref()) + " != " + literal(); case STARTS_WITH: - return "startsWith(" + ref() + "," + literal() + ")"; // case IN: // break; // case NOT_IN: I wonder if it would be more clear to use `ref() + "LIKE '" + literal() + "%'"` instead of this. Or maybe just use `startsWith` as an infix operator to avoid adding the SQL wildcard character, `%`. case NOT_EQ: return String.valueOf(ref()) + " != " + literal(); case STARTS_WITH: + return ref() + " startsWith \"" + literal() + "\""; // case IN: // break; // case NOT_IN:
codereview_java_data_10553
@Override default List<T> padTo(int length, T element) { - if(length == 0) { return this; } else { - return appendAll(Stream.gen(() -> element).take(length)); } } here also - it should be take(length - this.length()), am I right? @Override default List<T> padTo(int length, T element) { + if(length <= length()) { return this; } else { + return appendAll(Stream.gen(() -> element).take(length - length())); } }
codereview_java_data_10555
private static <T extends Node> T simplifiedParse(ParseStart<T> context, Provider provider) { ParseResult<T> result = new JavaParser(staticConfiguration).parse(context, provider); if (result.isSuccessful()) { - considerInjectingSymbolResolver(result, staticConfiguration); return result.getResult().get(); } throw new ParseProblemException(result.getProblems()); This is already done in the other method. private static <T extends Node> T simplifiedParse(ParseStart<T> context, Provider provider) { ParseResult<T> result = new JavaParser(staticConfiguration).parse(context, provider); if (result.isSuccessful()) { return result.getResult().get(); } throw new ParseProblemException(result.getProblems());
codereview_java_data_10559
int numTasksToShutDown = Math.max(otherActiveTasks.size() - (request.getInstancesSafe() - deployProgress.getTargetActiveInstances()), 0); List<SingularityTaskId> sortedOtherTasks = new ArrayList<>(otherActiveTasks); Collections.sort(sortedOtherTasks, SingularityTaskId.INSTANCE_NO_COMPARATOR); - return sortedOtherTasks.subList(0, Math.min(numTasksToShutDown, sortedOtherTasks.size() - 1)); } private boolean canMoveToNextStep(SingularityDeployProgress deployProgress) { i might be misunderstanding something obvious, but why subtract one here? int numTasksToShutDown = Math.max(otherActiveTasks.size() - (request.getInstancesSafe() - deployProgress.getTargetActiveInstances()), 0); List<SingularityTaskId> sortedOtherTasks = new ArrayList<>(otherActiveTasks); Collections.sort(sortedOtherTasks, SingularityTaskId.INSTANCE_NO_COMPARATOR); + return sortedOtherTasks.isEmpty() ? sortedOtherTasks : sortedOtherTasks.subList(0, Math.min(numTasksToShutDown, sortedOtherTasks.size())); } private boolean canMoveToNextStep(SingularityDeployProgress deployProgress) {
codereview_java_data_10567
import java.util.List; /** - * An extension of StreamDefinitionException that remembers the point up * to which parsing went OK (signaled by a '*' in the dumped message). * * @author Eric Bottard `StreamDefinitionException` -> `TaskDefinitionException` import java.util.List; /** + * An extension of TaskDefinitionException that remembers the point up * to which parsing went OK (signaled by a '*' in the dumped message). * * @author Eric Bottard
codereview_java_data_10570
@JsonProperty private String dockerPrefix = "se-"; - @NotNull @JsonProperty private int dockerStopTimeout = 15; `int` can't be null, but could could default to zero -- we should decide what a good minimum is, and then use the `@Min` annotation @JsonProperty private String dockerPrefix = "se-"; + @Min(5) @JsonProperty private int dockerStopTimeout = 15;
codereview_java_data_10573
String lang = Locale.getDefault().getLanguage(); - HashMap<String, RequestBody> imgMap = new HashMap<>(); imgMap.put("code", image.getCode()); imgMap.put("imagefield", image.getField()); imgMap.put("imgupload_front\"; filename=\"front_"+ lang +".png\"", image.getImguploadFront()); use a generic interface for declaration like `Map<String, RequestBody> imgMap = new HashMap<>();` String lang = Locale.getDefault().getLanguage(); + Map<String, RequestBody> imgMap = new HashMap<>(); imgMap.put("code", image.getCode()); imgMap.put("imagefield", image.getField()); imgMap.put("imgupload_front\"; filename=\"front_"+ lang +".png\"", image.getImguploadFront());
codereview_java_data_10591
(Traversable<?> seq, Object elem) -> ((List<Object>) seq).remove(elem) ); - final BiFunction<Traversable<?>, Object, Traversable<?>> add; - final BiFunction<Traversable<?>, Object, Traversable<?>> remove; ContainerType(BiFunction<Traversable<?>, Object, Traversable<?>> add, BiFunction<Traversable<?>, Object, Traversable<?>> remove) { We should make the instance variables `add` and `remove` and the constructor `ContainerType` private. (Traversable<?> seq, Object elem) -> ((List<Object>) seq).remove(elem) ); + private final BiFunction<Traversable<?>, Object, Traversable<?>> add; + private final BiFunction<Traversable<?>, Object, Traversable<?>> remove; ContainerType(BiFunction<Traversable<?>, Object, Traversable<?>> add, BiFunction<Traversable<?>, Object, Traversable<?>> remove) {
codereview_java_data_10592
this.to = receiptWithMetadata.getTransaction().getTo().map(BytesValue::toString).orElse(null); this.transactionHash = receiptWithMetadata.getTransaction().hash().toString(); this.transactionIndex = Quantity.create(receiptWithMetadata.getTransactionIndex()); - this.revertReason = - receipt - .getRevertReason() - .map(reason -> reason.isEmpty() ? "" : reason.toString()) - .orElse(null); } @JsonGetter(value = "blockHash") I think this should just be: ```suggestion .map(BytesValue::toUnprefixedString) ``` as we want to output it as a hex value in the same way as `StructLog` does above. this.to = receiptWithMetadata.getTransaction().getTo().map(BytesValue::toString).orElse(null); this.transactionHash = receiptWithMetadata.getTransaction().hash().toString(); this.transactionIndex = Quantity.create(receiptWithMetadata.getTransactionIndex()); + this.revertReason = receipt.getRevertReason().map(BytesValue::toString).orElse(null); } @JsonGetter(value = "blockHash")
codereview_java_data_10596
@Override public Void visitDynamicParam(RexDynamicParam dynamicParam) { found = true; - return super.visitDynamicParam(dynamicParam); } @Override public Void visitInputRef(RexInputRef inputRef) { found = true; - return super.visitInputRef(inputRef); } } Could not we just `return null` here (similarly below)? @Override public Void visitDynamicParam(RexDynamicParam dynamicParam) { found = true; + return null; } @Override public Void visitInputRef(RexInputRef inputRef) { found = true; + return null; } }
codereview_java_data_10597
return null; } Integer row_port = row.getInteger("native_port"); - if (row_port == null) { row_port = port; } return addressTranslator.translate(new InetSocketAddress(nativeAddress, row_port)); Please use the Java conventions for variable names: `rowPort`. return null; } Integer row_port = row.getInteger("native_port"); + if (row_port == null || row_port == 0) { row_port = port; } return addressTranslator.translate(new InetSocketAddress(nativeAddress, row_port));
codereview_java_data_10598
*/ package org.apache.accumulo.core.manager.balancer; import java.util.HashMap; import java.util.Map; -import java.util.Objects; import org.apache.accumulo.core.master.thrift.TabletServerStatus; import org.apache.accumulo.core.spi.balancer.data.TServerStatus; This is cleanest with a static import of `requireNonNull`: ```suggestion this.thriftStatus = requireNonNull(thriftStatus); ``` But, even without a static import, you can still one-line this: ```suggestion this.thriftStatus = Objects.requireNonNull(thriftStatus); ``` */ package org.apache.accumulo.core.manager.balancer; +import static java.util.Objects.requireNonNull; + import java.util.HashMap; import java.util.Map; import org.apache.accumulo.core.master.thrift.TabletServerStatus; import org.apache.accumulo.core.spi.balancer.data.TServerStatus;
codereview_java_data_10603
} public static ResultSet testFunctionIndexFunction() { SimpleResultSet rs = new SimpleResultSet(); rs.addColumn("ID", Types.INTEGER, ValueInt.PRECISION, 0); rs.addColumn("VALUE", Types.INTEGER, ValueInt.PRECISION, 0); this test is not verifying that we call testFunctionIndexFunction only once? which was the original bug. } public static ResultSet testFunctionIndexFunction() { + // There are additional callers like JdbcConnection.prepareCommand() and + // CommandContainer.recompileIfReqired() + for (StackTraceElement element : Thread.currentThread().getStackTrace()) { + if (element.getClassName() == Select.class.getName()) { + testFunctionIndexCounter++; + break; + } + } SimpleResultSet rs = new SimpleResultSet(); rs.addColumn("ID", Types.INTEGER, ValueInt.PRECISION, 0); rs.addColumn("VALUE", Types.INTEGER, ValueInt.PRECISION, 0);