id
stringlengths
23
26
content
stringlengths
182
2.49k
codereview_java_data_2433
asList("--miner-coinbase", "--min-gas-price", "--miner-extra-data")); // Check that fast sync options are able to work or send an error - checkFastSyncOptions(); //noinspection ConstantConditions if (isMiningEnabled && coinbase == null) { for the static imports asList("--miner-coinbase", "--min-gas-price", "--miner-extra-data")); // Check that fast sync options are able to work or send an error + if (fastSyncMaxWaitTime < 0) { + throw new ParameterException( + commandLine, "--fast-sync-max-wait-time must be greater than or equal to 0"); + } + checkOptionDependencies( + logger, + commandLine, + "--sync-mode", + SyncMode.FAST.equals(syncMode), + asList("--fast-sync-num-peers", "--fast-sync-timeout")); //noinspection ConstantConditions if (isMiningEnabled && coinbase == null) {
codereview_java_data_2437
} @Override - public double getReservoirLevel() { return -1; } public String getBaseBasalRateString() { final DecimalFormat df = new DecimalFormat("#.##"); You can look at the `getJSONStatus` method of each pump to see what can be reported, there (line 761), you'll see that the Insight stores the reservoir level in the field `reservoirInUnits`. } @Override + public double getReservoirLevel() { return reservoirInUnits; } public String getBaseBasalRateString() { final DecimalFormat df = new DecimalFormat("#.##");
codereview_java_data_2442
if (numMissingInstances > 0) { schedule(numMissingInstances, matchingTaskIds, request, state, deployStatistics, pendingRequest, maybePendingDeploy); - - List<SingularityTaskId> remainingActiveTasks = new ArrayList<>(matchingTaskIds); - if (requestManager.getExpiringBounce(request.getId()).isPresent() && remainingActiveTasks.size() == 0) { - requestManager.deleteExpiringObject(SingularityExpiringBounce.class, request.getId()); - requestManager.markBounceComplete(request.getId()); - } } else if (numMissingInstances < 0) { final long now = System.currentTimeMillis(); Logic here is good, just debating if this is the right place to put this. Ideally since bounce is all cleanup related this would live in the `SingularityCleaner`. Maybe it makes sense for each run of the cleaner to double check any in progress bounces or requests that are currently marked as bouncing and verify that they are correct? Having it here will solve the current edge case we ran into, but I could see there still being more. Moving something like that to the cleaner might give us a better long term solution if (numMissingInstances > 0) { schedule(numMissingInstances, matchingTaskIds, request, state, deployStatistics, pendingRequest, maybePendingDeploy); } else if (numMissingInstances < 0) { final long now = System.currentTimeMillis();
codereview_java_data_2443
} - // Returns a collection that returns the latest five posts from the Redshift table. public String getPosts(String lang, int num) { try { returns the last 5, 10, or all posts } + // Returns a collection that returns 5, 10, or all posts from the Redshift table. public String getPosts(String lang, int num) { try {
codereview_java_data_2456
} List<SingularityMesosArtifact> combinedArtifacts = task.getDeploy().getUris().or(Collections.<SingularityMesosArtifact> emptyList()); - combinedArtifacts.addAll(task.getPendingTask().getExtraArtifacts().or(Collections.<SingularityMesosArtifact> emptyList())); for (SingularityMesosArtifact artifact : combinedArtifacts) { commandBldr.addUris(URI.newBuilder() No longer need the <...> in Java 8 } List<SingularityMesosArtifact> combinedArtifacts = task.getDeploy().getUris().or(Collections.<SingularityMesosArtifact> emptyList()); + combinedArtifacts.addAll(task.getPendingTask().getExtraArtifacts()); for (SingularityMesosArtifact artifact : combinedArtifacts) { commandBldr.addUris(URI.newBuilder()
codereview_java_data_2468
* @return a function that applies arguments to the given {@code partialFunction} and returns {@code Some(result)} * if the function is defined for the given arguments, and {@code None} otherwise. */ static <R> Function0<Option<R>> lift(CheckedFunction0<? extends R> partialFunction) { - return () -> Try.of(of(partialFunction)::apply).getOption(); } /** We can replace the method call `of(partialFunction)` by providing a type hint `<R>`: ``` java return () -> Try.<R> of(partialFunction::apply).getOption(); ``` * @return a function that applies arguments to the given {@code partialFunction} and returns {@code Some(result)} * if the function is defined for the given arguments, and {@code None} otherwise. */ + @SuppressWarnings("RedundantTypeArguments") static <R> Function0<Option<R>> lift(CheckedFunction0<? extends R> partialFunction) { + return () -> Try.<R>of(partialFunction::apply).getOption(); } /**
codereview_java_data_2472
import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import static com.hazelcast.spi.properties.GroupProperty.SHUTDOWNHOOK_POLICY; import static java.util.concurrent.TimeUnit.SECONDS; can we move this `GroupProperty` ? import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; +import static com.hazelcast.spi.properties.GroupProperty.SHUTDOWNHOOK_ENABLED; import static com.hazelcast.spi.properties.GroupProperty.SHUTDOWNHOOK_POLICY; import static java.util.concurrent.TimeUnit.SECONDS;
codereview_java_data_2474
} else {//Or use the original unedited pictures newFilePath = data.getStringExtra(EditImageActivity.FILE_PATH); - ; } //System.out.println("newFilePath---->" + newFilePath); //File file = new File(newFilePath); Why is an extra semicolon placed here? Also, try not to refactor code until and unless it is absolutely required. } else {//Or use the original unedited pictures newFilePath = data.getStringExtra(EditImageActivity.FILE_PATH); } //System.out.println("newFilePath---->" + newFilePath); //File file = new File(newFilePath);
codereview_java_data_2475
final Collection<ValidatorPeer> peers, final Block blockToPropose) { - final List<SignedData<RoundChangePayload>> roundChangePayloads = Lists.newArrayList(); - for (final ValidatorPeer peer : peers) { - roundChangePayloads.add( - peer.getMessageFactory().createSignedRoundChangePayload(targetRoundId, empty())); - } final SignedData<ProposalPayload> proposal = proposer.getMessageFactory().createSignedProposalPayload(targetRoundId, blockToPropose); nit: be nicer to create this list using stream().map final Collection<ValidatorPeer> peers, final Block blockToPropose) { + final List<SignedData<RoundChangePayload>> roundChangePayloads = + peers + .stream() + .map(p -> p.getMessageFactory().createSignedRoundChangePayload(targetRoundId, empty())) + .collect(Collectors.toList()); final SignedData<ProposalPayload> proposal = proposer.getMessageFactory().createSignedProposalPayload(targetRoundId, blockToPropose);
codereview_java_data_2486
BROADCAST, /** * This policy sends each item to a single processor on each of the - * cluster members. It is only available on a distributed edge. */ FANOUT } This doesn't state which processor on each member. The PR mentions "round robin" so I guess it's a different processor every time? BROADCAST, /** * This policy sends each item to a single processor on each of the + * cluster members in a round robin fashion. It is only available + * on a distributed edge. */ FANOUT }
codereview_java_data_2491
@Override public void setJsonParameters(Map<String, Object> allParameters) throws Exception { Map<String, Object> parameters = (Map<String, Object>)allParameters.get("parameters"); - Long bitmask = (Long) parameters.get("type"); type = new ConnectionType(bitmask.intValue()); } should use Number instead of Long @Override public void setJsonParameters(Map<String, Object> allParameters) throws Exception { Map<String, Object> parameters = (Map<String, Object>)allParameters.get("parameters"); + Number bitmask = (Number) parameters.get("type"); type = new ConnectionType(bitmask.intValue()); }
codereview_java_data_2511
package com.getcapacitor; import org.json.JSONException; -import org.junit.Assert; import org.junit.Test; public class JSObjectTest { @Test This can be changed to `import static org.junit.Assert.*;` then all the `Assert.assertFoo(...)` can become `assertFoo(...)` package com.getcapacitor; import org.json.JSONException; import org.junit.Test; +import static org.junit.Assert.*; + public class JSObjectTest { @Test
codereview_java_data_2520
if (error != null) { initFuture.completeExceptionally(error); } else { - notifyLifecycleListeners(); initFuture.complete(DefaultSession.this); } }); } catch (Throwable throwable) { Shouldn't the call come after `initFuture.complete(DefaultSession.this);`? if (error != null) { initFuture.completeExceptionally(error); } else { initFuture.complete(DefaultSession.this); + notifyLifecycleListeners(); } }); } catch (Throwable throwable) {
codereview_java_data_2524
Function<FileScanTask, Long> weightFunc = file -> Math.max(file.length(), openFileCost); CloseableIterable<FileScanTask> splitFiles = splitFiles(splitSize); - return CloseableIterable.transform(CloseableIterable.combine( - new BinPacking.PackingIterable<>(splitFiles, splitSize, lookback, weightFunc, true), - splitFiles), BaseCombinedScanTask::new); } Was this change required? I liked that it was clear that all 3 lines were not passed to the same function. (Minor) Function<FileScanTask, Long> weightFunc = file -> Math.max(file.length(), openFileCost); CloseableIterable<FileScanTask> splitFiles = splitFiles(splitSize); + return CloseableIterable.transform( + CloseableIterable.combine( + new BinPacking.PackingIterable<>(splitFiles, splitSize, lookback, weightFunc, true), + splitFiles), BaseCombinedScanTask::new); }
codereview_java_data_2525
private TableMetadata base; private long expireOlderThan; private int minNumSnapshots; - private ExpireSnapshotResult expireSnapshotResult; private Consumer<String> deleteFunc = defaultDelete; private ExecutorService deleteExecutorService = DEFAULT_DELETE_EXECUTOR_SERVICE; - public RemoveSnapshots(TableOperations ops) { this.ops = ops; this.base = ops.current(); This is created by calling `expireSnapshots` on a table. Why did you make it public? private TableMetadata base; private long expireOlderThan; private int minNumSnapshots; private Consumer<String> deleteFunc = defaultDelete; private ExecutorService deleteExecutorService = DEFAULT_DELETE_EXECUTOR_SERVICE; + RemoveSnapshots(TableOperations ops) { this.ops = ops; this.base = ops.current();
codereview_java_data_2542
private String cookieName = DEFAULT_CSRF_COOKIE_NAME; - private Method setHttpOnlyMethod; - private boolean cookieHttpOnly = true; public CookieCsrfTokenRepository() { this.setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class); } @Override Just for understanding: Any reason why using Reflection here? Support of older servlet specs? private String cookieName = DEFAULT_CSRF_COOKIE_NAME; + private final Method setHttpOnlyMethod; + private boolean cookieHttpOnly; public CookieCsrfTokenRepository() { this.setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class); + if (this.setHttpOnlyMethod != null) { + this.cookieHttpOnly = true; + } } @Override
codereview_java_data_2549
} }); - AlertDialog dialog = builder.create(); - dialog.setCanceledOnTouchOutside(true); - dialog.show(); } private void handleDisconnectDevice(final long deviceId) { why are you calling this? } }); + builder.show(); } private void handleDisconnectDevice(final long deviceId) {
codereview_java_data_2550
import tech.pegasys.pantheon.services.pipeline.Pipeline; import tech.pegasys.pantheon.services.pipeline.PipelineBuilder; -import java.time.Duration; import java.util.Optional; public class FullSyncDownloadPipelineFactory<C> implements DownloadPipelineFactory { Should this duration be stored as a constant somewhere? import tech.pegasys.pantheon.services.pipeline.Pipeline; import tech.pegasys.pantheon.services.pipeline.PipelineBuilder; import java.util.Optional; public class FullSyncDownloadPipelineFactory<C> implements DownloadPipelineFactory {
codereview_java_data_2556
* @param startFileIndex A startFileIndex used to skip processed files. * @param targetSizeInBytes Used to control the size of MicroBatch, the processed file bytes must be smaller than * this size. - * @param scanAllFiles Used to check where all the data file should be processed, or only added files. * @return A MicroBatch. */ private MicroBatch generateMicroBatch(List<Pair<ManifestFile, Integer>> indexedManifests, Typo from before : where -. whether * @param startFileIndex A startFileIndex used to skip processed files. * @param targetSizeInBytes Used to control the size of MicroBatch, the processed file bytes must be smaller than * this size. + * @param scanAllFiles Used to check whether all the data files should be processed, or only added files. * @return A MicroBatch. */ private MicroBatch generateMicroBatch(List<Pair<ManifestFile, Integer>> indexedManifests,
codereview_java_data_2568
/** * Retrieves Software Version data. This method gives access to temporary Software Version data only. - * @param key a <code>String</code> value of stored data ID. - * @return a <code>Map<String,String></code> value of data . */ @Override public Map<String, String> getSoftwareVersion() { -return softwareVersionData; } /** Exposing the Map exposes implementation details. It should be possible to swap out such implementation details with affecting the API (e.g. the XEP-0092 POJO I mentioned earlier). IMHO, as a rule of thumb, it's almost never appropriate to expose Maps via accessor methods. /** * Retrieves Software Version data. This method gives access to temporary Software Version data only. + * @return a Map collection value of data . */ @Override public Map<String, String> getSoftwareVersion() { + return softwareVersionData; } /**
codereview_java_data_2583
} @Override - public void addTransactionFilterToTransactionValidators( - final TransactionFilter transactionFilter) { protocolSpecs.forEach(spec -> spec.getSpec().setTransactionFilter(transactionFilter)); } } Should be setTransactionFilter... } @Override + public void setTransactionFilter(final TransactionFilter transactionFilter) { protocolSpecs.forEach(spec -> spec.getSpec().setTransactionFilter(transactionFilter)); } }
codereview_java_data_2590
// This file is generated via a gradle task and should not be edited directly. public final class PantheonInfo { - private static final String clientIdentity = "pantheon"; - private static final String version = - clientIdentity + "/v" + PantheonInfo.class.getPackage().getImplementationVersion() + "/" nit: Since these are constants they should be uppercase (e.g. CLIENT_IDENTITY). // This file is generated via a gradle task and should not be edited directly. public final class PantheonInfo { + private static final String CLIENT_IDENTITY = "pantheon"; + private static final String VERSION = + CLIENT_IDENTITY + "/v" + PantheonInfo.class.getPackage().getImplementationVersion() + "/"
codereview_java_data_2592
return query(channel, queryString, Collections.emptyMap()); } - private String fetchPeersTable() { if (isSchemaV2) { return "system.peers_v2"; } Nit: I find the name a bit misleading, to me "fetch" implies that we retrieve it for somewhere (like a database query). return query(channel, queryString, Collections.emptyMap()); } + private String retrievePeerTableName() { if (isSchemaV2) { return "system.peers_v2"; }
codereview_java_data_2595
this.exportedSnapshotDetailsCache = instance.getMap(EXPORTED_SNAPSHOTS_DETAIL_CACHE); } - public static String keyPrefixForChunkedMap(String jobId, String fileId) { - return jobId + ':' + fileId; - } - // for tests void setResourcesExpirationMillis(long resourcesExpirationMillis) { this.resourcesExpirationMillis = resourcesExpirationMillis; why does jobId need to be in key prefix here? this.exportedSnapshotDetailsCache = instance.getMap(EXPORTED_SNAPSHOTS_DETAIL_CACHE); } // for tests void setResourcesExpirationMillis(long resourcesExpirationMillis) { this.resourcesExpirationMillis = resourcesExpirationMillis;
codereview_java_data_2603
final TransactionPool transactionPool = pantheonController.getTransactionPool(); final MiningCoordinator miningCoordinator = pantheonController.getMiningCoordinator(); - AccountWhitelistController accountWhitelistController = - new AccountWhitelistController(permissioningConfiguration); - - transactionPool.setAccountWhitelist(accountWhitelistController); final FilterManager filterManager = createFilterManager(vertx, context, transactionPool); We don't need to call the setter if the account whitelist property hasn't been set. Why don't we check it here? ``` if (permissioningConfiguration.isAccountWhitelistSet()) { transactionPool.setAccountWhitelist(accountWhitelistController); } ``` final TransactionPool transactionPool = pantheonController.getTransactionPool(); final MiningCoordinator miningCoordinator = pantheonController.getMiningCoordinator(); + if (permissioningConfiguration.isAccountWhitelistSet()) { + AccountWhitelistController accountWhitelistController = + new AccountWhitelistController(permissioningConfiguration); + transactionPool.setAccountWhitelist(accountWhitelistController); + } final FilterManager filterManager = createFilterManager(vertx, context, transactionPool);
codereview_java_data_2609
@Bean public ResourceLoader resourceLoader() { MavenProperties mavenProperties = new MavenProperties(); - mavenProperties.setRemoteRepositories(new HashMap<>(Collections.singletonMap("mavenCentral", new MavenProperties.RemoteRepository("https://repo.spring.io/libs-snapshot")))); return new MavenResourceLoader(mavenProperties); } this is not "mavenCentral" ;) @Bean public ResourceLoader resourceLoader() { MavenProperties mavenProperties = new MavenProperties(); + mavenProperties.setRemoteRepositories(new HashMap<>(Collections.singletonMap("springRepo", new MavenProperties.RemoteRepository("https://repo.spring.io/libs-snapshot")))); return new MavenResourceLoader(mavenProperties); }
codereview_java_data_2610
package net.sourceforge.pmd.lang.java.rule.errorprone; -import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.rule.AbstractJUnitRule; If using the protected fields from the base class, you don't need to search here again for the compilation unit and call again the methods - that was already done.... package net.sourceforge.pmd.lang.java.rule.errorprone; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.rule.AbstractJUnitRule;
codereview_java_data_2614
"com.palantir.baseline:baseline-error-prone:" + version); project.getDependencies().add( "refasterCompiler", - "com.palantir.baseline:baseline-refaster-plugin:" + version); - Provider<RegularFile> refasterRulesFile = project.getLayout().getBuildDirectory() - .file("refaster/rules.refaster"); Task compileRefaster = project.getTasks().create("compileRefaster", RefasterCompileTask.class, task -> { task.setSource(refasterSources); I think it might not actually be necessary to ship this to everyone as the _vast_ majority of builds will not use `-PrefasterApply`, still fine to use it in tests tho "com.palantir.baseline:baseline-error-prone:" + version); project.getDependencies().add( "refasterCompiler", + "com.palantir.baseline:baseline-refaster-javac-plugin:" + version); + Provider<File> refasterRulesFile = project.getLayout().getBuildDirectory() + .file("refaster/rules.refaster") + .map(RegularFile::getAsFile); Task compileRefaster = project.getTasks().create("compileRefaster", RefasterCompileTask.class, task -> { task.setSource(refasterSources);
codereview_java_data_2641
return false; } - private boolean isWithSecurityEnforced(final AbstractApexNode<?> node){ - if(node instanceof ASTSoqlExpression){ String pattern = "(?i).*[^']\\s*WITH SECURITY_ENFORCED\\s*[^']*"; String query = ((ASTSoqlExpression) node).getQuery(); return query.matches(pattern); Would `node.getNode().getQuery().endsWith("WITH SECURITY_ENFORCED");` produce the same result? return false; } + private boolean isWithSecurityEnforced(final AbstractApexNode<?> node) { + if (node instanceof ASTSoqlExpression) { String pattern = "(?i).*[^']\\s*WITH SECURITY_ENFORCED\\s*[^']*"; String query = ((ASTSoqlExpression) node).getQuery(); return query.matches(pattern);
codereview_java_data_2651
int levelWarning = SP.getInt(R.string.key_reservoirview_levelwarning, 80); int levelCritical = SP.getInt(R.string.key_reservoirview_levelcritical, 5); reservoirView.setText(reservoirLevel + " " + MainApp.sResources.getString(R.string.insulin_unit_shortname)); - if (reservoirLevel <= levelWarning) { reservoirView.setBackgroundColor(Color.RED); reservoirView.setTextColor(Color.GRAY); - } else if (reservoirLevel <= levelCritical) { reservoirView.setBackgroundColor(Color.YELLOW); reservoirView.setTextColor(Color.DKGRAY); } else { You've mixed up _levelWarning_ here and _levelCritical_ on the _else if_ below :-) int levelWarning = SP.getInt(R.string.key_reservoirview_levelwarning, 80); int levelCritical = SP.getInt(R.string.key_reservoirview_levelcritical, 5); reservoirView.setText(reservoirLevel + " " + MainApp.sResources.getString(R.string.insulin_unit_shortname)); + if (reservoirLevel <= levelCritical) { reservoirView.setBackgroundColor(Color.RED); reservoirView.setTextColor(Color.GRAY); + } else if (reservoirLevel <= levelWarning) { reservoirView.setBackgroundColor(Color.YELLOW); reservoirView.setTextColor(Color.DKGRAY); } else {
codereview_java_data_2652
throw validator.newValidationError(aggCall, RESOURCE.overNonAggregate()); } final SqlNode window = call.operand(1); - SqlLiteral qualifier = aggCall.getFunctionQuantifier(); - if (qualifier != null && qualifier.getValue() == SqlSelectKeyword.DISTINCT - && window.getKind() == SqlKind.WINDOW) { - throw validator.newValidationError(aggCall, - RESOURCE.functionQuantifierNotAllowed(window.toString())); - } validator.validateWindow(window, scope, aggCall); } Can we move this validation to a separate method? See this for reference: org.apache.calcite.sql.SqlFunction#validateQuantifier throw validator.newValidationError(aggCall, RESOURCE.overNonAggregate()); } final SqlNode window = call.operand(1); + checkDistinctOnWindowAggregate(validator, aggCall, window); validator.validateWindow(window, scope, aggCall); }
codereview_java_data_2658
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { - handleSilenceRinger(); - return true; } return super.onKeyDown(keyCode, event); } This looks like it will silence the ringer whenever vol up or vol down is pressed. There are a couple of problems here: 1. We only want this to be the case when the user sees this activity from their lock screen. 2. We also only want this to be the case when the call's state matches those within the SILENCE RINGER intent handling. 2. can be solved by using `getStickyEvent` and checking against the event state, as is done in a few other places. 1. might be a trickier solve. This (only silencing when in 'lock screen' mode) is in line with what other calling apps do. For example, if you enter this screen from the notification bar while your phone is unlocked, the volume buttons would only modify volume (as it does in Signal today). @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { + WebRtcViewModel model = EventBus.getDefault().getStickyEvent(WebRtcViewModel.class); + + if (model != null && model.getState() == WebRtcViewModel.State.CALL_INCOMING) { + handleSilenceRinger(); + return true; + } } return super.onKeyDown(keyCode, event); }
codereview_java_data_2670
* System.out.println(Option.of(1).transform(f)); * * // Prints "3-transformed" - * System.out.println(Option.none().transform(f)); * }</pre> * * @param f A transformation This example does not compile. I got error: ``` jshell> System.out.println(Option.none().transform(f)); | Error: | method transform in class io.vavr.control.Option<T> cannot be applied to given types; | required: java.util.function.Function<? super io.vavr.control.Option<java.lang.Object>,? extends U> | found: java.util.function.Function<io.vavr.control.Option<java.lang.Integer>,java.lang.String> | reason: cannot infer type-variable(s) U | (argument mismatch; java.util.function.Function<io.vavr.control.Option<java.lang.Integer>,java.lang.String> cannot be converted to java.util.function.Function<? super io.vavr.control.Option<java.lang.Object>,? extends U>) | System.out.println(Option.none().transform(f)); | ^---------------------^ ``` What about: ```java System.out.println(Option.<Integer> none().transform(f)); ``` * System.out.println(Option.of(1).transform(f)); * * // Prints "3-transformed" + * System.out.println(Option.<Integer>none().transform(f)); * }</pre> * * @param f A transformation
codereview_java_data_2677
private static final int LOCATION_REQUEST = 1; private static final String MAP_LAST_USED_PREFERENCE = "mapLastUsed"; - private boolean LOCATION_CHANGED=false; @BindView(R.id.progressBar) ProgressBar progressBar; please refer to google style guide for private variable naming conventions. :) private static final int LOCATION_REQUEST = 1; private static final String MAP_LAST_USED_PREFERENCE = "mapLastUsed"; + @BindView(R.id.progressBar) ProgressBar progressBar;
codereview_java_data_2681
* * @param sql the SQL statement * @param autoGeneratedKeys - * {@link Statement.RETURN_GENERATED_KEYS} if generated keys should - * be available for retrieval, {@link Statement.NO_GENERATED_KEYS} if * generated keys should not be available * @return the prepared statement * @throws SQLException if the connection is closed Shouldn't it be Statement#RETURN_GENERATED_KEYS and Statement#NO_GENERATED_KEYS instead? IMHO, this java doc and few others just can to be removed, since behavior do not deviate from the standard interface anymore. * * @param sql the SQL statement * @param autoGeneratedKeys + * {@link Statement#RETURN_GENERATED_KEYS} if generated keys should + * be available for retrieval, {@link Statement#NO_GENERATED_KEYS} if * generated keys should not be available * @return the prepared statement * @throws SQLException if the connection is closed
codereview_java_data_2685
return save(request, RequestState.ACTIVE, historyType, timestamp, user, message); } - public SingularityCreateResult deleting(SingularityRequest request, RequestHistoryType historyType, long timestamp, Optional<String> user, Optional<String> message) { return save(request, RequestState.DELETING, historyType, timestamp, user, message); } - public SingularityCreateResult deleted(SingularityRequest request, RequestHistoryType historyType, long timestamp, Optional<String> user, Optional<String> message) { return save(request, RequestState.DELETED, historyType, timestamp, user, message); } maybe for these methods we name them more like an action. i.e. `markDeleted` or `markDeleting`, just to clarify what they are doing. Especially since we already have a `deleteRequest` method (which could maybe be renamed to something like `startRequestDelete`?) return save(request, RequestState.ACTIVE, historyType, timestamp, user, message); } + public SingularityCreateResult markDeleting(SingularityRequest request, RequestHistoryType historyType, long timestamp, Optional<String> user, Optional<String> message) { return save(request, RequestState.DELETING, historyType, timestamp, user, message); } + public SingularityCreateResult markDeleted(SingularityRequest request, RequestHistoryType historyType, long timestamp, Optional<String> user, Optional<String> message) { return save(request, RequestState.DELETED, historyType, timestamp, user, message); }
codereview_java_data_2688
this.bootNodes = ethNetworkConfig.bootNodes; } - public Builder() {} - public Builder setGenesisConfig(final String genesisConfig) { this.genesisConfig = genesisConfig; return this; This appears to be unused. this.bootNodes = ethNetworkConfig.bootNodes; } public Builder setGenesisConfig(final String genesisConfig) { this.genesisConfig = genesisConfig; return this;
codereview_java_data_2689
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class SingularityTokenResponse { private final String token; private final SingularityUser user; Just OOC, why does hashCode need overriding? import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; + +@Schema(description = "Response containing the generated long lived auth token and associated user data") public class SingularityTokenResponse { private final String token; private final SingularityUser user;
codereview_java_data_2690
* A snack bar which has an action button which on click dismisses the snackbar and invokes the * listener passed */ - public static void showSnackBar(View view, - int messageResourceId, - int actionButtonResourceId, - View.OnClickListener onClickListener) { if (view.getContext() == null) { return; } What's the rationale behind renaming this method? * A snack bar which has an action button which on click dismisses the snackbar and invokes the * listener passed */ + public static void showDismissibleSnackBar(View view, + int messageResourceId, + int actionButtonResourceId, + View.OnClickListener onClickListener) { if (view.getContext() == null) { return; }
codereview_java_data_2691
private void writeStandaloneAction(StringBuilder flex, TerminalLike key) { flex.append(" {\n" + " int kind = ").append(tokens.get(key)._1()+1).append(";\n" + - " *((char **)yylval ) = malloc(strlen(yytext) + 1);\n" + " strcpy(*((char **)yylval), yytext);\n" + " return kind;\n" + " }\n"); Why the extra space? :) private void writeStandaloneAction(StringBuilder flex, TerminalLike key) { flex.append(" {\n" + " int kind = ").append(tokens.get(key)._1()+1).append(";\n" + + " *((char **)yylval) = malloc(strlen(yytext) + 1);\n" + " strcpy(*((char **)yylval), yytext);\n" + " return kind;\n" + " }\n");
codereview_java_data_2700
private String diskUtil() { double physicRatio = 100; String storePath = this.brokerController.getMessageStoreConfig().getStorePathCommitLog(); - if (storePath.contains(MessageStoreConfig.MULTI_PATH_SPLITTER)) { - String[] paths = storePath.trim().split(MessageStoreConfig.MULTI_PATH_SPLITTER); - for (String storePathPhysic : paths) { - physicRatio = Math.min(physicRatio, UtilAll.getDiskPartitionSpaceUsedPercent(storePathPhysic)); - } - } else { - physicRatio = UtilAll.getDiskPartitionSpaceUsedPercent(storePath); } String storePathLogis = this if branch is not necessary, could use the same code with MULTI_PATH branch private String diskUtil() { double physicRatio = 100; String storePath = this.brokerController.getMessageStoreConfig().getStorePathCommitLog(); + String[] paths = storePath.trim().split(MessageStoreConfig.MULTI_PATH_SPLITTER); + for (String storePathPhysic : paths) { + physicRatio = Math.min(physicRatio, UtilAll.getDiskPartitionSpaceUsedPercent(storePathPhysic)); } String storePathLogis =
codereview_java_data_2707
* @param token token */ public void validateToken(String token) { - makeSureSecretKeyBytes(); Jwts.parserBuilder().setSigningKey(authConfigs.getSecretKeyBytes()).build().parseClaimsJws(token); } - private void makeSureSecretKeyBytes() { - if (authConfigs.getSecretKeyBytes() == null) { - authConfigs.setSecretKeyBytes(Decoders.BASE64.decode(authConfigs.getSecretKey())); - } - } } Can We remove this Base64? * @param token token */ public void validateToken(String token) { Jwts.parserBuilder().setSigningKey(authConfigs.getSecretKeyBytes()).build().parseClaimsJws(token); } }
codereview_java_data_2720
} } - public static final Type DEFAULT_CONNECTION_CHECK_TYPE = Type.WIFI_ONLY; Type connectionCheckType = DEFAULT_CONNECTION_CHECK_TYPE; The default connection should be all inline with what is present today i.e ANY } } + public static final Type DEFAULT_CONNECTION_CHECK_TYPE = Type.ANY; Type connectionCheckType = DEFAULT_CONNECTION_CHECK_TYPE;
codereview_java_data_2721
@Override public void onConfigurationChanged(@NonNull final Configuration newConfig) { super.onConfigurationChanged(newConfig); - ViewGroup.LayoutParams rlBottomSheetLayoutParams=rlBottomSheet.getLayoutParams(); rlBottomSheetLayoutParams.height = getActivity().getWindowManager().getDefaultDisplay().getHeight() / 16 * 9; rlBottomSheet.setLayoutParams(rlBottomSheetLayoutParams); } could you please add single spaces before and after "=" to keep style guides? @Override public void onConfigurationChanged(@NonNull final Configuration newConfig) { super.onConfigurationChanged(newConfig); + ViewGroup.LayoutParams rlBottomSheetLayoutParams = rlBottomSheet.getLayoutParams(); rlBottomSheetLayoutParams.height = getActivity().getWindowManager().getDefaultDisplay().getHeight() / 16 * 9; rlBottomSheet.setLayoutParams(rlBottomSheetLayoutParams); }
codereview_java_data_2724
"--output", koreOutputFile.getAbsolutePath())); if (depth.isPresent()) { args.add("--depth"); - args.add(depth.toString()); } if (smtOptions.smtPrelude != null) { args.add("--smt-prelude"); the java library specification does not provide any guarantees about the value of Optional.toString so you really should be calling get() here. "--output", koreOutputFile.getAbsolutePath())); if (depth.isPresent()) { args.add("--depth"); + args.add(Integer.toString(depth.get())); } if (smtOptions.smtPrelude != null) { args.add("--smt-prelude");
codereview_java_data_2725
private <X> Iterator<X> chooseIterator(K from, K to, boolean forEntries) { switch (transaction.isolationLevel) { case READ_UNCOMMITTED: - return new UncommittedIterator<>(this, from, to, false, forEntries); case REPEATABLE_READ: case SERIALIZABLE: if (transaction.hasChanges()) { - new RepeatableIterator<K, X>(this, from, to, forEntries); } //$FALL-THROUGH$ case READ_COMMITTED: Missing `return` before `new`. private <X> Iterator<X> chooseIterator(K from, K to, boolean forEntries) { switch (transaction.isolationLevel) { case READ_UNCOMMITTED: + return new UncommittedIterator<>(this, from, to, forEntries); case REPEATABLE_READ: case SERIALIZABLE: if (transaction.hasChanges()) { + return new RepeatableIterator<>(this, from, to, forEntries); } //$FALL-THROUGH$ case READ_COMMITTED:
codereview_java_data_2737
} catch (FileNotFoundException e) { //ignored } catch (IOException | ClassNotFoundException e) { - kem.registerInternalWarning("Invalidating serialized cache due to corruption.", e); } catch (InterruptedException e) { throw KEMException.criticalError("Interrupted while locking to read " + file.getAbsolutePath(), e); } this should not be a regular warning as it can happen during normal operation. } catch (FileNotFoundException e) { //ignored } catch (IOException | ClassNotFoundException e) { + kem.registerInternalHiddenWarning("Invalidating serialized cache due to corruption.", e); } catch (InterruptedException e) { throw KEMException.criticalError("Interrupted while locking to read " + file.getAbsolutePath(), e); }
codereview_java_data_2742
if (!isSlaveAttributesMatch(offerHolder, taskRequest, isPreemptibleTask)) { return SlaveMatchState.SLAVE_ATTRIBUTES_DO_NOT_MATCH; } else if (!areSlaveAttributeMinimumsFeasible(offerHolder, taskRequest, activeTaskIdsForRequest)) { - return SlaveMatchState.SLAVE_ATTRIBUTES_DO_NOT_MATCH; // TODO: other enum? } final SlavePlacement slavePlacement = taskRequest.getRequest().getSlavePlacement().or(configuration.getDefaultSlavePlacement()); SLAVE_ATTRIBUTES_DO_NOT_MATCH enum is probably fine here, since it is still another case of this that we are checking for if (!isSlaveAttributesMatch(offerHolder, taskRequest, isPreemptibleTask)) { return SlaveMatchState.SLAVE_ATTRIBUTES_DO_NOT_MATCH; } else if (!areSlaveAttributeMinimumsFeasible(offerHolder, taskRequest, activeTaskIdsForRequest)) { + return SlaveMatchState.SLAVE_ATTRIBUTES_DO_NOT_MATCH; } final SlavePlacement slavePlacement = taskRequest.getRequest().getSlavePlacement().or(configuration.getDefaultSlavePlacement());
codereview_java_data_2747
} public TabletIteratorEnvironment(ServerContext context, IteratorScope scope, boolean fullMajC, - MajorCompactionReason reason) { if (scope != IteratorScope.majc) throw new IllegalArgumentException( "Tried to set maj compaction type when scope was " + scope); Will this just throw an exception now? } public TabletIteratorEnvironment(ServerContext context, IteratorScope scope, boolean fullMajC, + AccumuloConfiguration tableConfig, MajorCompactionReason reason) { if (scope != IteratorScope.majc) throw new IllegalArgumentException( "Tried to set maj compaction type when scope was " + scope);
codereview_java_data_2763
} descriptions = uploadItem.getDescriptions(); - compositeDisposable - .add(downSampleImage(uploadItem.getContentUri()) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(bitmap -> { - if (null != bitmap) { - photoViewBackgroundImage.setImageBitmap(bitmap); - } - }, Timber::d)); setDescriptionsInAdapter(descriptions); } Can we use a SimpleDraweeView and `.setImageURI` to avoid manual bounds decoding? } descriptions = uploadItem.getDescriptions(); + showImageWithLocalUri(uploadItem.getMediaUri()); setDescriptionsInAdapter(descriptions); }
codereview_java_data_2764
iconId = R.drawable.ic_notification_sync_error; intent = ClientConfig.downloadServiceCallbacks.getReportNotificationContentIntent(context); id = R.id.notification_download_report; - content = context.getResources().getQuantityString(R.plurals.download_report_content, successfulDownloads, successfulDownloads, failedDownloads); } NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId); The line is a bit too long. That's why the test currently fails. Please break it into two lines. iconId = R.drawable.ic_notification_sync_error; intent = ClientConfig.downloadServiceCallbacks.getReportNotificationContentIntent(context); id = R.id.notification_download_report; + content = context.getResources() + .getQuantityString(R.plurals.download_report_content, + successfulDownloads, + successfulDownloads, + failedDownloads); } NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId);
codereview_java_data_2765
import com.intellij.lang.annotation.Annotation; import com.intellij.lang.annotation.Annotator; import com.intellij.psi.PsiElement; import com.intellij.testFramework.fixtures.CodeInsightTestUtil; /** Great that you figured out a better, more robust replacement for the future. import com.intellij.lang.annotation.Annotation; import com.intellij.lang.annotation.Annotator; +import com.intellij.openapi.components.ComponentManager; import com.intellij.psi.PsiElement; +import com.intellij.serviceContainer.ComponentManagerImpl; import com.intellij.testFramework.fixtures.CodeInsightTestUtil; /**
codereview_java_data_2766
@Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - addPreferencesFromResource(R.xml.preferences_notification); setUpScreen(); } Please rename the xml file to `preferences_notifications` (plural). I think that reads a bit better. The Java class name is fine as-is @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { + addPreferencesFromResource(R.xml.preferences_notifications); setUpScreen(); }
codereview_java_data_2771
@Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] arguments = invocationOnMock.getArguments(); - resultCollector.append(arguments[0]); return null; } - }).when(dlqLogger).info(anyString()); Field dlqLoggerField = SendMessageProcessor.class.getDeclaredField("dlqLogger"); dlqLoggerField.setAccessible(true); Can we use the unified `assertThat` of `assertj`? @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] arguments = invocationOnMock.getArguments(); + InnerLoggerFactory.MessageFormatter messageFormatter = new InnerLoggerFactory.MessageFormatter(); + String pattern = (String) arguments[0]; + Object[] objects = {arguments[1], arguments[2], arguments[3]}; + String message = messageFormatter.arrayFormat(pattern, objects).getMessage(); + resultCollector.append(message); return null; } + }).when(dlqLogger).info(anyString(), new Object[]{Mockito.any()}); Field dlqLoggerField = SendMessageProcessor.class.getDeclaredField("dlqLogger"); dlqLoggerField.setAccessible(true);
codereview_java_data_2772
block.rewind(); // Fixbug - An IllegalStateException that wraps EOFException is thrown when partial writes happens //in the case of power off or file system issues. - // So we should first check the read length of block, and skip the broken block at end of DB file. if(pos + block.limit() > fileSize) { break; } DataUtils.readFully(file, pos, block); I think in this case we should be printing out a message e.g. see further down, we do pw.printf("ERROR illegal position %d%n", p); block.rewind(); // Fixbug - An IllegalStateException that wraps EOFException is thrown when partial writes happens //in the case of power off or file system issues. + // So we should first check the read length of block, and skip the broken block at end of the DB file. if(pos + block.limit() > fileSize) { + pw.printf("ERROR a broken block at end of the DB file %s, then skip it%n", fileName); break; } DataUtils.readFully(file, pos, block);
codereview_java_data_2777
@Subscribe public void onStatusEvent(final EventTempTargetChange ev) { - new Thread(() -> LoopPlugin.getPlugin().invoke("EventTempTargetChange", true)).start(); FabricPrivacy.getInstance().logCustom(new CustomEvent("TT_Loop_Run")); } Minor style point: _LoopPlugin.getPlugin()_ is redundant. Calling _invoke_ directly would make the intent easier to read. @Subscribe public void onStatusEvent(final EventTempTargetChange ev) { + new Thread(() -> invoke("EventTempTargetChange", true)).start(); FabricPrivacy.getInstance().logCustom(new CustomEvent("TT_Loop_Run")); }
codereview_java_data_2781
import javax.annotation.Nullable; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import static com.hazelcast.jet.impl.util.Util.uncheckCall; /** * Private API, use {@link SourceProcessors#readJdbcP}. this can throw exception, which must be caught import javax.annotation.Nullable; import java.sql.Connection; import java.sql.ResultSet; +import java.sql.SQLException; import java.sql.Statement; import static com.hazelcast.jet.impl.util.Util.uncheckCall; +import static com.hazelcast.jet.impl.util.Util.uncheckRun; /** * Private API, use {@link SourceProcessors#readJdbcP}.
codereview_java_data_2785
}; } @Override public <M extends Metadata> Multimap<Method, MetadataHandler<M>> handlers( MetadataDef<M> def) { return ImmutableMultimap.of(); This method needs a deprecation annotation. }; } + @Deprecated @Override public <M extends Metadata> Multimap<Method, MetadataHandler<M>> handlers( MetadataDef<M> def) { return ImmutableMultimap.of();
codereview_java_data_2786
if (m.find()) { retval = SafeParse.stringToInt(m.group(1)) * 60 * 60 + SafeParse.stringToInt(m.group(2)) * 60; - if (m.group(3).equals(" AM") && m.group(1).equals("12")) retval -= 12 * 60 * 60; - if (m.group(3).equals(" PM") && !(m.group(1).equals("12"))) retval += 12 * 60 * 60; } return retval; on my android ".a.m" and ".p.m" is used add `||` here to support both variants if (m.find()) { retval = SafeParse.stringToInt(m.group(1)) * 60 * 60 + SafeParse.stringToInt(m.group(2)) * 60; + if (m.group(3).equals(" a.m.") || m.group(3).equals(" AM") && m.group(1).equals("12")) retval -= 12 * 60 * 60; + if (m.group(3).equals(" p.m.") || m.group(3).equals(" PM") && !(m.group(1).equals("12"))) retval += 12 * 60 * 60; } return retval;
codereview_java_data_2792
assertTrue(attributes.getDkimTokens().size() == dkim.getDkimTokens().size()); List verifyDomainResultTokens = dkim.getDkimTokens(); - for (String token : attributes.getDkimTokens()) { - assertTrue(verifyDomainResultTokens.contains(token)); - } try { SetIdentityDkimEnabledResult setIdentityDkimEnabledResult = email.setIdentityDkimEnabled(new SetIdentityDkimEnabledRequest() This is so much more succinct. Minor suggestion: assertTrue(dkim.getDkimTokens().containsAll(attributes.getDkimTokens()))? assertTrue(attributes.getDkimTokens().size() == dkim.getDkimTokens().size()); List verifyDomainResultTokens = dkim.getDkimTokens(); + assertTrue(verifyDomainResultTokens.containsAll(verifyDomainResultTokens)); try { SetIdentityDkimEnabledResult setIdentityDkimEnabledResult = email.setIdentityDkimEnabled(new SetIdentityDkimEnabledRequest()
codereview_java_data_2794
} @Override - public void scaleApplicationInstances(String streamName, String appName, String count, Map<String, String> properties) { // Skipper expects app names / labels not deployment ids logger.info(String.format("Scale %s:%s to %s with properties: %s", streamName, appName, count, properties)); - this.skipperStreamDeployer.scale(streamName, appName, Integer.valueOf(count), properties); } @Override We can remove this once we have Integer as the request path variable. } @Override + public void scaleApplicationInstances(String streamName, String appName, int count, Map<String, String> properties) { // Skipper expects app names / labels not deployment ids logger.info(String.format("Scale %s:%s to %s with properties: %s", streamName, appName, count, properties)); + this.skipperStreamDeployer.scale(streamName, appName, count, properties); } @Override
codereview_java_data_2798
JetPlanExecutor( MappingCatalog catalog, - JetInstance jetInstance, Map<Long, JetQueryResultProducer> resultConsumerRegistry ) { this.catalog = catalog; - this.jetInstance = (AbstractJetInstance) jetInstance; this.resultConsumerRegistry = resultConsumerRegistry; } Maybe pass `AbstractJetInstance` to the constructor instead of casting? JetPlanExecutor( MappingCatalog catalog, + AbstractJetInstance jetInstance, Map<Long, JetQueryResultProducer> resultConsumerRegistry ) { this.catalog = catalog; + this.jetInstance = jetInstance; this.resultConsumerRegistry = resultConsumerRegistry; }
codereview_java_data_2801
private View.OnLongClickListener photosOnLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { - if(checkForReveal ==0) { enterReveal(); - checkForReveal++; } Media m = (Media) v.findViewById(R.id.photo_path).getTag(); //If first long press, turn on selection mode It would be better if checkForReveal variable is of Boolean type. private View.OnLongClickListener photosOnLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { + if(checkForReveal) { enterReveal(); + checkForReveal = false; } Media m = (Media) v.findViewById(R.id.photo_path).getTag(); //If first long press, turn on selection mode
codereview_java_data_2802
nextItemAt = System.nanoTime() + MILLISECONDS.toNanos(((Delay) item).millis); pos++; return false; - } else if (item.equals(DONE_ITEM)) { getLogger().info("returning true"); return true; } I'd rename this to `DONE_ITEM_STR` or use the `"DONE_ITEM"` string directly, as this is likely to be mistaken for the actual DONE_ITEM. nextItemAt = System.nanoTime() + MILLISECONDS.toNanos(((Delay) item).millis); pos++; return false; + } else if (item.equals(DONE_ITEM_STR)) { getLogger().info("returning true"); return true; }
codereview_java_data_2803
* * @since 2.3 */ - List<AppDeploymentRequest> createRequests(String taskName, String dslText); } Can we make the name of this method more explicit by naming it as `createTaskDeploymentRequests` ? * * @since 2.3 */ + List<AppDeploymentRequest> createTaskDeploymentRequests(String taskName, String dslText); }
codereview_java_data_2804
SqlKind.OTHER_FUNCTION, ReturnTypes.DATE_NULLABLE, null, - OperandTypes.STRING_STRING_DATETIME, SqlFunctionCategory.TIMEDATE); @LibraryOperator(libraries = {MYSQL, POSTGRESQL}) Then add a `Redshift` library ? SqlKind.OTHER_FUNCTION, ReturnTypes.DATE_NULLABLE, null, + OperandTypes.CHARACTER_CHARACTER_DATETIME, SqlFunctionCategory.TIMEDATE); @LibraryOperator(libraries = {MYSQL, POSTGRESQL})
codereview_java_data_2808
if (numWaitingInInbox == 0 && rwinDiff < 0) { rwinDiff = 0; } - receiveWindowCompressed += rwinDiff / 2; - LoggingUtil.logFinest(logger, "receiveWindowCompressed=%d", receiveWindowCompressed); } return ackedSeqCompressed + receiveWindowCompressed; } This doesn't seem to address the concern that something should be printed only if the window size was changed if (numWaitingInInbox == 0 && rwinDiff < 0) { rwinDiff = 0; } + rwinDiff /= 2; + receiveWindowCompressed += rwinDiff; + if (rwinDiff != 0) { + logFinest(logger, "receiveWindowCompressed changed by %d to %d", rwinDiff, receiveWindowCompressed); + } } return ackedSeqCompressed + receiveWindowCompressed; }
codereview_java_data_2809
String s = new String(b, StandardCharsets.UTF_8); if (argument.equals("description/fetch")) { - s = preparePmsSpec(s); } return s; } - private String preparePmsSpec(String pmsXml) { - String result = pmsXml.replace("[uuid]", PMS.get().usn()); //.substring(0, PMS.get().usn().length()-2)); if (PMS.get().getServer().getHost() != null) { result = result.replace("[host]", PMS.get().getServer().getHost()); Not a big deal but it might make more sense for the new instances of `pms` to be `ums` String s = new String(b, StandardCharsets.UTF_8); if (argument.equals("description/fetch")) { + s = prepareUmsSpec(s); } return s; } + private String prepareUmsSpec(String umsXml) { + String result = umsXml.replace("[uuid]", PMS.get().usn()); //.substring(0, PMS.get().usn().length()-2)); if (PMS.get().getServer().getHost() != null) { result = result.replace("[host]", PMS.get().getServer().getHost());
codereview_java_data_2824
httpMethod.initEntity(requestHttpEntity.getBody(), headers.getValue(HttpHeaderConsts.CONTENT_TYPE)); } HttpRequestBase requestBase = httpMethod.getRequestBase(); - getConfig(requestBase, requestHttpEntity.getHttpClientConfig()); return requestBase; } I think the method name is not good. httpMethod.initEntity(requestHttpEntity.getBody(), headers.getValue(HttpHeaderConsts.CONTENT_TYPE)); } HttpRequestBase requestBase = httpMethod.getRequestBase(); + replaceDefaultConfig(requestBase, requestHttpEntity.getHttpClientConfig()); return requestBase; }
codereview_java_data_2827
GROUP, POLICY, SERVICE, - ENTITY, - TEMPLATE } private String domainName; Template is also not an object type so I don't expect to notify on templates. Instead when applying templates, we'll be updating roles/policies/services/groups. GROUP, POLICY, SERVICE, + ENTITY } private String domainName;
codereview_java_data_2836
: null; if (result == null && List.class.isAssignableFrom(method.getReturnType())) { // Lists are generally deprecated, see #2451 - result = ""; } return result; } ```suggestion result = DeprecatedAttribute.NO_REPLACEMENT; ``` : null; if (result == null && List.class.isAssignableFrom(method.getReturnType())) { // Lists are generally deprecated, see #2451 + result = DeprecatedAttribute.NO_REPLACEMENT; } return result; }
codereview_java_data_2839
response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else { - LOGGER.info("Unsupported action received: " + content); } } else if (method.equals("SUBSCRIBE")) { output.headers().set("SID", PMS.get().usn()); ```suggestion LOGGER.debug("Unsupported action received: " + content); ``` response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER); response.append(CRLF); } else { + LOGGER.debug("Unsupported action received: " + content); } } else if (method.equals("SUBSCRIBE")) { output.headers().set("SID", PMS.get().usn());
codereview_java_data_2840
import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; -import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.text.Editable; -import android.text.TextPaint; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.Menu; I think there is no need to edit SingleUploadFragment in this PR. import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.Menu;
codereview_java_data_2847
interface InputFormatOptions<T> { /** * Sets the {@link Authorizations} used to scan. Must be a subset of the user's authorizations. - * By Default, auths are set to {@link Authorizations#EMPTY} * * @param auths * the user's authorizations This doesn't match the new client API, which defaults to the maximal set for the user. interface InputFormatOptions<T> { /** * Sets the {@link Authorizations} used to scan. Must be a subset of the user's authorizations. + * By Default, all of the users auths are set. * * @param auths * the user's authorizations
codereview_java_data_2857
*/ @Nonnull public static <T> ProcessorMetaSupplier writeJmsQueueP( @Nonnull SupplierEx<? extends Connection> newConnectionFn, - @Nonnull BiFunctionEx<? super Session, ? super T, ? extends Message> messageFn, - @Nonnull String name ) { - return WriteJmsP.supplier(newConnectionFn, messageFn, name, false); } /** lambda should be last param here also. */ @Nonnull public static <T> ProcessorMetaSupplier writeJmsQueueP( + @Nonnull String queueName, @Nonnull SupplierEx<? extends Connection> newConnectionFn, + @Nonnull BiFunctionEx<? super Session, ? super T, ? extends Message> messageFn ) { + return WriteJmsP.supplier(queueName, newConnectionFn, messageFn, false); } /**
codereview_java_data_2865
opt.setRequired(true); options.addOption(opt); - opt = new Option("i", "queue", true, "set the queue, eg: 0,1"); opt.setRequired(false); options.addOption(opt); why not use -q ? q is short name of queue, which is understandable opt.setRequired(true); options.addOption(opt); + opt = new Option("q", "queue", true, "set the queue, eg: 0,1"); opt.setRequired(false); options.addOption(opt);
codereview_java_data_2871
release = this.skipperClient.install(installRequest); } catch (Exception e) { - this.skipperClient.packageDelete(packageName); throw new SkipperException(e.getMessage()); } // TODO store releasename in deploymentIdRepository... Should we try/catch packageDelete as well? Then it's a choice of logging a warning or choosing which error to wrap in `SkipperException`? release = this.skipperClient.install(installRequest); } catch (Exception e) { + logger.error("Skipper install failed. Deleting the package: " + packageName); + try { + this.skipperClient.packageDelete(packageName); + } + catch (Exception e1) { + logger.error("Package delete threw exception: " + e1.getMessage()); + } throw new SkipperException(e.getMessage()); } // TODO store releasename in deploymentIdRepository...
codereview_java_data_2873
long recentPubDate = recentPubDates.containsKey(feed.getId()) ? recentPubDates.get(feed.getId()) : -1; NavDrawerData.FeedDrawerItem drawerItem = new NavDrawerData.FeedDrawerItem(feed, feed.getId(), feedCounters.get(feed.getId()), playedCounters.get(feed.getId(), -1), recentPubDate); -// if (FeedPreferences.TAG_ROOT.equals(tag)) { -// items.add(drawerItem); -// continue; -// } NavDrawerData.FolderDrawerItem folder; if (folders.containsKey(tag)) { folder = folders.get(tag); This means that AntennaPod always needs to do 2 additional SQL queries that could potentially affect all episodes. Seems like it could cause performance problems. The app is rather sluggish with >150 subscriptions already. long recentPubDate = recentPubDates.containsKey(feed.getId()) ? recentPubDates.get(feed.getId()) : -1; NavDrawerData.FeedDrawerItem drawerItem = new NavDrawerData.FeedDrawerItem(feed, feed.getId(), feedCounters.get(feed.getId()), playedCounters.get(feed.getId(), -1), recentPubDate); + if (FeedPreferences.TAG_ROOT.equals(tag)) { + items.add(drawerItem); + } NavDrawerData.FolderDrawerItem folder; if (folders.containsKey(tag)) { folder = folders.get(tag);
codereview_java_data_2882
void visit(LineComment n, A arg); void visit(LongLiteralExpr n, A arg); void visit(MarkerAnnotationExpr n, A arg); would it make sense to order the methods by grouping related nodes? Like, all the literals near each other void visit(LineComment n, A arg); + void visit(LocalClassDeclarationStmt n, A arg); + void visit(LongLiteralExpr n, A arg); void visit(MarkerAnnotationExpr n, A arg);
codereview_java_data_2883
public class ScanCommand extends Command { private Option scanOptAuths, scanOptRow, scanOptColumns, disablePaginationOpt, showFewOpt, - formatterOpt, interpreterOpt, formatterInterpeterOpt, outputFileOpt, scanOptCfOptions, - scanOptColQualifier; protected Option timestampOpt; protected Option profileOpt; ```suggestion formatterOpt, interpreterOpt, formatterInterpeterOpt, outputFileOpt, scanOptColFam, scanOptColQualifier; ``` Doesn't have to be this specific wording but the two added opts should have a similar naming convention. public class ScanCommand extends Command { private Option scanOptAuths, scanOptRow, scanOptColumns, disablePaginationOpt, showFewOpt, + formatterOpt, interpreterOpt, formatterInterpeterOpt, outputFileOpt, scanOptCf, scanOptCq; protected Option timestampOpt; protected Option profileOpt;
codereview_java_data_2888
int pairs = 0; if (methodCount > 1) { - for (int i = 0; i < methodCount; i++) { for (int j = i + 1; j < methodCount; j++) { String firstMethodName = methods.get(i); String secondMethodName = methods.get(j); That would compare in the last round the same method - i == j. I think the condition for the out loop over i should be "i < methodCount - 1"? int pairs = 0; if (methodCount > 1) { + for (int i = 0; i < methodCount - 1; i++) { for (int j = i + 1; j < methodCount; j++) { String firstMethodName = methods.get(i); String secondMethodName = methods.get(j);
codereview_java_data_2889
public class TestAncestorsOfProcedure extends SparkExtensionsTestBase { - public TestAncestorsOfProcedure( - String catalogName, - String implementation, - Map<String, String> config) { super(catalogName, implementation, config); } nit: our style is to place this all on one line if it fits, and only carry over the arg that does not fit public class TestAncestorsOfProcedure extends SparkExtensionsTestBase { + public TestAncestorsOfProcedure(String catalogName, String implementation, Map<String, String> config) { super(catalogName, implementation, config); }
codereview_java_data_2890
codeEditorArea.richChanges() .filter(t -> !t.getInserted().equals(t.getRemoved())) - .successionEnds(Duration.ofMillis(100)) .subscribe(richChange -> parent.onRefreshASTClicked()); codeEditorArea.setParagraphGraphicFactory(LineNumberFactory.get(codeEditorArea)); You should probably abstract the duration into a named constant. codeEditorArea.richChanges() .filter(t -> !t.getInserted().equals(t.getRemoved())) + .successionEnds(timeDuration) .subscribe(richChange -> parent.onRefreshASTClicked()); codeEditorArea.setParagraphGraphicFactory(LineNumberFactory.get(codeEditorArea));
codereview_java_data_2892
// snippet-sourcetype:[snippet] // snippet-sourcedate:[2019-01-10] // snippet-sourceauthor:[AWS] -// snippet-start:[transcribe.java-streaming-client-behavior] /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * For parameter docs, I'd either say something more meaningful or remove them. // snippet-sourcetype:[snippet] // snippet-sourcedate:[2019-01-10] // snippet-sourceauthor:[AWS] + /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. *
codereview_java_data_2901
.map(mod -> (Module) mod).collect(Collectors.toSet()); List<FlatModule> flatModules = kilModules.stream().map(this::toFlatModule).sorted(Comparator.comparing(FlatModule::name)).collect(Collectors.toList()); - scala.collection.Set<org.kframework.definition.Module> koreModules = FlatModule.toModule(immutable(flatModules), Set()); return Definition( koreModules.find(x -> x.name().equals(d.getMainModule())) This is where I'm confused by calling it `toModule` instead of `toModules`. .map(mod -> (Module) mod).collect(Collectors.toSet()); List<FlatModule> flatModules = kilModules.stream().map(this::toFlatModule).sorted(Comparator.comparing(FlatModule::name)).collect(Collectors.toList()); + scala.collection.Set<org.kframework.definition.Module> koreModules = FlatModule.toModules(immutable(flatModules), Set()); return Definition( koreModules.find(x -> x.name().equals(d.getMainModule()))
codereview_java_data_2909
} @Test - public void testExpiredAuthorizationRequestsRemoved() { final Duration expiresIn = Duration.ofMinutes(2); - this.authorizationRequestRepository.setOAuth2AuthorizationRequestExpiresIn(expiresIn); this.authorizationRequestRepository.setClock(Clock.fixed(Instant.ofEpochMilli(0), ZoneId.systemDefault())); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); Rename method using conventions of existing tests } @Test + public void removeAuthorizationRequestWhenExpired() { final Duration expiresIn = Duration.ofMinutes(2); + this.authorizationRequestRepository.setAuthorizationRequestTimeToLive(expiresIn); this.authorizationRequestRepository.setClock(Clock.fixed(Instant.ofEpochMilli(0), ZoneId.systemDefault())); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse();
codereview_java_data_2911
<h1>Error 503 Backend is unhealthy</h1> <p>Backend is unhealthy</p> <h3>Guru Mediation:</h3> - <p>Details: cache-sea4454-SEA 1645538565 2107619846</p> <hr> <p>Varnish cache server</p> </body> I'm not yet sure if I like this form of testing. This method is complex enough that it's easy to make a mistake, maybe even the same mistake the class that is tested contains. I would have preferred testing with static input and expected output, but I realize that there are a lots of inputs to test, so maybe this is the best compromise. In any case this is vastly better than what we had before. So thanks a lot for that! <h1>Error 503 Backend is unhealthy</h1> <p>Backend is unhealthy</p> <h3>Guru Mediation:</h3> + <p>Details: cache-sea4465-SEA 1645538565 286887369</p> <hr> <p>Varnish cache server</p> </body>
codereview_java_data_2917
return candidates.stream().filter(s -> !s.isEmpty()) .map(cand -> computeMatchingSegments(cand, query, false)) .sorted(Comparator.<CompletionResult>naturalOrder().reversed()) - // second pass is done only on those we know we'll keep .limit(limit) .map(prev -> { // try to break ties between the top results, e.g. // 4 + 8 + 16 + 10 = 38... Where do the extra 2 come from? return candidates.stream().filter(s -> !s.isEmpty()) .map(cand -> computeMatchingSegments(cand, query, false)) .sorted(Comparator.<CompletionResult>naturalOrder().reversed()) + .filter(it -> it.getScore() > 0) .limit(limit) + // second pass is done only on those we know we'll keep .map(prev -> { // try to break ties between the top results, e.g. //
codereview_java_data_2924
return getTaskJobExecutionsForList(jobExecutions); } @Override public List<TaskJobExecution> listJobExecutionsWithStepCount(String queryString, Pageable pageable) { Assert.notNull(pageable, "pageable must not be null"); We'll need a unit test for this method as well. return getTaskJobExecutionsForList(jobExecutions); } + @Override + public List<TaskJobExecution> listJobExecutionsWithStepCount(Pageable pageable) { + return listJobExecutionsWithStepCount(null, pageable); + } + @Override public List<TaskJobExecution> listJobExecutionsWithStepCount(String queryString, Pageable pageable) { Assert.notNull(pageable, "pageable must not be null");
codereview_java_data_2925
Future<?> compactTask = startCompactTask(); - try { - - assertTrue("compaction fate transaction exits", findFate(tableName)); - - } catch (KeeperException ex) { - String msg = "Failing test with possible transient zookeeper exception, no node"; - log.debug("{}", msg, ex); - fail(msg); - } - AdminUtil.FateStatus withLocks = null; List<AdminUtil.TransactionStatus> noLocks = null; The blockUntilCompactionsRunning() essentially does this test. Perhaps that should return a boolean as to whether a compaction was found and that should be tested instead of depending on the timing of the compaction start on 226. Future<?> compactTask = startCompactTask(); AdminUtil.FateStatus withLocks = null; List<AdminUtil.TransactionStatus> noLocks = null;
codereview_java_data_2927
public class CdcJsonDataSerializerHook implements DataSerializerHook { - public static final int ELEMENT = 1; - public static final int EVENT = 2; public static final int FACTORY_ID = FactoryIdHelper.getFactoryId(JET_CDC_JSON_DS_FACTORY, JET_CDC_JSON_DS_FACTORY_ID); the names here don't seem aligned with the actual types public class CdcJsonDataSerializerHook implements DataSerializerHook { + public static final int RECORD = 1; + public static final int PART = 2; public static final int FACTORY_ID = FactoryIdHelper.getFactoryId(JET_CDC_JSON_DS_FACTORY, JET_CDC_JSON_DS_FACTORY_ID);
codereview_java_data_2930
int EXPECTED_AGGREGATE; Integer[] ELEMENTS; - int[] INT_ELEMENTS; int[] RANDOMIZED_INDICES; /* Only use this for non-mutating operations */ Once this is finished, I would be very interested in `>10m` - I can't run that on my laptop anymore :p int EXPECTED_AGGREGATE; Integer[] ELEMENTS; int[] RANDOMIZED_INDICES; /* Only use this for non-mutating operations */
codereview_java_data_2932
@Override public void write(InternalRow value, VectorizedRowBatch output) { Preconditions.checkArgument(value != null, "value must not be null"); - - int row = output.size; - output.size += 1; - - writer.rootNonNullWrite(row, value, output); } @Override Why does the value not allow to be null ? In my view, it's possible for people to append a `null` row to orc file.. @Override public void write(InternalRow value, VectorizedRowBatch output) { Preconditions.checkArgument(value != null, "value must not be null"); + writer.rootNonNullWrite(value, output); } @Override
codereview_java_data_2940
binder.bind(MetricRegistry.class).toProvider(DropwizardMetricRegistryProvider.class).in(Scopes.SINGLETON); binder.bind(AsyncHttpClient.class).to(SingularityAsyncHttpClient.class).in(Scopes.SINGLETON); - binder.bind(OkHttpClient.class).in(Scopes.SINGLETON); binder.bind(ServerProvider.class).in(Scopes.SINGLETON); binder.bind(SingularityDropwizardHealthcheck.class).in(Scopes.SINGLETON); Will want to also make sure to close this if it is Closeable. The `SingularityAsyncHttpClient` is bound for that reason, since it also implements dropwizard's `Managed` and will be closed on shutdown binder.bind(MetricRegistry.class).toProvider(DropwizardMetricRegistryProvider.class).in(Scopes.SINGLETON); binder.bind(AsyncHttpClient.class).to(SingularityAsyncHttpClient.class).in(Scopes.SINGLETON); + binder.bind(OkHttpClient.class).to(SingularityOkHttpClient.class).in(Scopes.SINGLETON); binder.bind(ServerProvider.class).in(Scopes.SINGLETON); binder.bind(SingularityDropwizardHealthcheck.class).in(Scopes.SINGLETON);
codereview_java_data_2945
@Test public void shouldHandleTransformOnNone() { - // TODO: What is the expected behavior when transform is called on None given return type may or may not be an Option? - // Calling None.get() will throw NoSuchElementException - // Should it be left to the caller to decide how to handle a value of None in their transform function? - // If not, should the default implementation of transform be overridden in None so that it is handled consistently? } // -- iterator `transform` is the swiss-army-knife of the methods. It allows us to return an object that is derived from the current object in a fluent manner. Not more, not less. It is up to the caller what type of object is returned. **Example:** Given an `Option<?> o = Option.none();`, instead of ``` java // non-fluent / imperative API final String s; if (o.isEmpty()) { s = "None"; } else { s = "Some"; } String result = s.toUpperCase(); ``` we write ``` java // fluent API String result = o.transform(self -> self.isEmpty() ? "None" : "Some").toUpperCase(); ``` @Test public void shouldHandleTransformOnNone() { + assertThat(Option.none().<String>transform(self -> self.isEmpty() ? "ok" : "failed")).isEqualTo("ok"); } // -- iterator
codereview_java_data_2946
public Map<String, Object> getInputContext() { return inputContext; } } During the review I've realized that there is an implicit contract: if `decisionServiceName` is specified, only that decision service is evaluated, otherwise all the services are evaluated. I'm wondering if it's better to make it explicit, so that it's more clear to read, consume, and extend in the future. wdyt? public Map<String, Object> getInputContext() { return inputContext; } + + public boolean isValid() { + return getModelName() != null && getModelNamespace() != null && getInputContext() != null; + } }
codereview_java_data_2956
} // constructor - public KeyValue(long offset, byte[] kafkaKey, byte[] value, Long timestamp) { this.mOffset = offset; this.mKafkaKey = kafkaKey; this.mValue = value; should this be 'long'? } // constructor + public KeyValue(long offset, byte[] kafkaKey, byte[] value, long timestamp) { this.mOffset = offset; this.mKafkaKey = kafkaKey; this.mValue = value;
codereview_java_data_2958
.getExtensions() .getByType(RecommendationProviderContainer.class); - extension.setStrategy(RecommendationStrategies.OverrideTransitives); // default is 'ConflictResolved'; File rootVersionsPropsFile = rootVersionsPropsFile(project); revert this semicolon change .getExtensions() .getByType(RecommendationProviderContainer.class); + extension.setStrategy(RecommendationStrategies.OverrideTransitives); // default is 'ConflictResolved' File rootVersionsPropsFile = rootVersionsPropsFile(project);
codereview_java_data_2970
package tech.pegasys.pantheon.consensus.ibft.tests; import static org.assertj.core.api.Assertions.assertThat; Is this message correct? where or what is local node ...I don't see a field with that name +/* + * Copyright 2019 ConsenSys AG. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ package tech.pegasys.pantheon.consensus.ibft.tests; import static org.assertj.core.api.Assertions.assertThat;
codereview_java_data_2972
downloadOrVerify("ext/lucene-queryparser-5.5.5.jar", "org/apache/lucene", "lucene-queryparser", "5.5.5", "6c965eb5838a2ba58b0de0fd860a420dcda11937", offline); - downloadOrVerify("ext/lucene-queries-5.5.5.jar", - "org/apache/lucene", "lucene-queries", "5.5.5", - "d99719e7c58c149113f897bca301f1d68cbf3241", offline); - downloadOrVerify("ext/lucene-sandbox-5.5.5.jar", - "org/apache/lucene", "lucene-sandbox", "5.5.5", - "d145d959109257c47151be43b211213dff455f47", offline); downloadOrVerify("ext/slf4j-api-1.6.0.jar", "org/slf4j", "slf4j-api", "1.6.0", "b353147a7d51fcfcd818d8aa6784839783db0915", offline); Do we really need `lucene-queries` and `lucene-sandbox` here? I didn't find where they are used. downloadOrVerify("ext/lucene-queryparser-5.5.5.jar", "org/apache/lucene", "lucene-queryparser", "5.5.5", "6c965eb5838a2ba58b0de0fd860a420dcda11937", offline); downloadOrVerify("ext/slf4j-api-1.6.0.jar", "org/slf4j", "slf4j-api", "1.6.0", "b353147a7d51fcfcd818d8aa6784839783db0915", offline);