id
stringlengths
23
26
content
stringlengths
182
2.49k
codereview_java_data_8283
LOG.debug("Request {} already has a shuffling task, skipping", taskIdWithUsage.getTaskId().getRequestId()); continue; } - if ((mostOverusedResource.overusage <= 0) || shuffledTasksOnSlave > configuration.getMaxTasksToShufflePerHost() || currentShuffleCleanupsTotal >= configuration.getMaxTasksToShuffleTotal()) { LOG.debug("Not shuffling any more tasks ({} overage : {}%, shuffledOnHost: {}, totalShuffleCleanups: {})", mostOverusedResource.resourceType, mostOverusedResource.overusage * 100, shuffledTasksOnSlave, currentShuffleCleanupsTotal); break; } `cpuOverage <= 0` worked as a condition for 'should this put us back in green?' because we updated it at the end of the loop. I don't currently see `mostOverusedResource.overusage` getting updated anywhere LOG.debug("Request {} already has a shuffling task, skipping", taskIdWithUsage.getTaskId().getRequestId()); continue; } + if (((shufflingForCpu && currentCpuLoad <= overloadedSlave.getSystemCpusTotal()) || + (!shufflingForCpu && currentMemUsageBytes <= configuration.getShuffleTasksWhenSlaveMemoryUtilizationPercentageExceeds() * overloadedSlave.getSystemMemTotalBytes())) + || shuffledTasksOnSlave > configuration.getMaxTasksToShufflePerHost() || currentShuffleCleanupsTotal >= configuration.getMaxTasksToShuffleTotal()) { LOG.debug("Not shuffling any more tasks ({} overage : {}%, shuffledOnHost: {}, totalShuffleCleanups: {})", mostOverusedResource.resourceType, mostOverusedResource.overusage * 100, shuffledTasksOnSlave, currentShuffleCleanupsTotal); break; }
codereview_java_data_8293
.setTarget(nav_cam) .setDismissText(getResources().getString(R.string.ok_button)) .setContentText(getResources().getString(R.string.camera_button)) - .hideOnTouchOutside() .build() ); Try using using `.setDismissOnTouch(true)` instead .setTarget(nav_cam) .setDismissText(getResources().getString(R.string.ok_button)) .setContentText(getResources().getString(R.string.camera_button)) + .setDismissOnTouch(true) .build() );
codereview_java_data_8294
} }).iterator(); this.workerPool = workerPool; - this.taskFutures = new Future[parallelism]; } @Override Is it possible to base this on the size of the `ExecutorService`, rather than pass it in? } }).iterator(); this.workerPool = workerPool; + // In default, we submit 2 tasks per worker at a time. + this.taskFutures = new Future[workerPoolSize * 2]; } @Override
codereview_java_data_8296
private String readIdentifierWithSchema2(String s) { schemaName = s; - if (readIf(DOT)) { - if (equalsToken(schemaName, database.getShortName()) || database.getIgnoreCatalogs()) { - schemaName = session.getCurrentSchemaName(); - s = readColumnIdentifier(); - } - } else { s = readColumnIdentifier(); if(currentTokenType == DOT) { if(equalsToken(schemaName, database.getShortName()) || database.getIgnoreCatalogs()) { Why this method is so complicated now? private String readIdentifierWithSchema2(String s) { schemaName = s; + if (!readIf(DOT)) { s = readColumnIdentifier(); if(currentTokenType == DOT) { if(equalsToken(schemaName, database.getShortName()) || database.getIgnoreCatalogs()) {
codereview_java_data_8300
@After public void after() { if (mysql != null) { - mysql = stopContainer(mysql); } } I think it would be clearer to assign null directly here: ``` stopContainer(mysql); mysql = null; ``` @After public void after() { if (mysql != null) { + stopContainer(mysql); } }
codereview_java_data_8301
@Override public String get(Property property) { - return get(property, true); - } - - public String get(Property property, boolean useDefault) { if (CliConfiguration.get(property) != null) { return CliConfiguration.get(property); } Instead of putting this functionality into SiteConfig did you consider creating another config layer bettween DefaultConfig and SiteConfig? @Override public String get(Property property) { if (CliConfiguration.get(property) != null) { return CliConfiguration.get(property); }
codereview_java_data_8303
} @Override - public Consumer<Value<T>> onSetNextValue(Consumer<Value<T>> callback) { this.onSetNextValueCallbacks.add(callback); - return callback; } @Override Is there a usage for the returned callback? } @Override + public void onSetNextValue(Consumer<Value<T>> callback) { this.onSetNextValueCallbacks.add(callback); } @Override
codereview_java_data_8312
throw new RuntimeException("Minor compaction after recovery fails for " + extent); } Assignment assignment = new Assignment(extent, server.getTabletSession()); - TabletStateStore.setLocation(server.getContext(), assignment, assignment.server); synchronized (server.openingTablets) { synchronized (server.onlineTablets) { Is `assignment.server` really the previously assigned location to clear? This doesn't seem right because MetaDataStateStore.setLocation just compares this `prevLastLoc` (passed in here as `assignment.server` against `assignment.server`. It seems like it would never be different, and the last location entries would remain (and possibly keep accruing?) throw new RuntimeException("Minor compaction after recovery fails for " + extent); } Assignment assignment = new Assignment(extent, server.getTabletSession()); + TServerInstance preLastLoc = new TServerInstance(tabletMetadata.getLocation()); + TabletStateStore.setLocation(server.getContext(), assignment, preLastLoc); synchronized (server.openingTablets) { synchronized (server.onlineTablets) {
codereview_java_data_8319
*/ public class CmmnParserImpl implements CmmnParser { - private final Logger LOGGER = LoggerFactory.getLogger(CmmnParserImpl.class); protected CmmnParseHandlers cmmnParseHandlers; protected CmmnActivityBehaviorFactory activityBehaviorFactory; This is an instance field, not a `static final` one. The logger should stay lowercase here. */ public class CmmnParserImpl implements CmmnParser { + private final Logger logger = LoggerFactory.getLogger(CmmnParserImpl.class); protected CmmnParseHandlers cmmnParseHandlers; protected CmmnActivityBehaviorFactory activityBehaviorFactory;
codereview_java_data_8330
// eventMessage protected int eventMessageLength = 163; - protected int eventMessageSubLength = 163; /** postprocessor for a task builder */ protected TaskPostProcessor taskPostProcessor = null; Shouldn't this value be 160 and not 163 (to leave room for `...`)? // eventMessage protected int eventMessageLength = 163; + protected int eventMessageSubLength = 160; /** postprocessor for a task builder */ protected TaskPostProcessor taskPostProcessor = null;
codereview_java_data_8335
*/ public static String getCPU() { if (!isPlatformAvailable()) - throw new UnsupportedOperationException("JNR Platform class not loaded"); return PlatformLoader.PLATFORM.getCPU().toString(); } I see that similar methods in this class use `IllegalStateException`, shouldn't we do the same here? */ public static String getCPU() { if (!isPlatformAvailable()) + throw new IllegalStateException( + "JNR Platform class not loaded. " + + "Check isGetProcessIdAvailable() before calling this method."); return PlatformLoader.PLATFORM.getCPU().toString(); }
codereview_java_data_8336
/** * Store the assigned locations in the data store. */ - void setFutureLocations(Collection<Assignment> assignments); /** * Tablet servers will update the data store with the location when they bring the tablet online */ - // void setLocations(Collection<Assignment> assignments) throws DistributedStoreException; - - void setLocations(Assignment assignment, TServerInstance prevLastLoc); /** * Mark the tablets as having no known or future location. ```suggestion void setLocation(Assignment assignment, TServerInstance prevLastLoc); ``` /** * Store the assigned locations in the data store. */ + void setFutureLocation(Assignment assignment); /** * Tablet servers will update the data store with the location when they bring the tablet online */ + void setLocation(Assignment assignment, TServerInstance prevLastLoc); /** * Mark the tablets as having no known or future location.
codereview_java_data_8337
JavadocInlineTag that = (JavadocInlineTag) o; - return type == that.type && content.equals(that.content); } If we allow for the Unknown type we should probably store the actual name of the tag used and use it also in the equals method and the toString method JavadocInlineTag that = (JavadocInlineTag) o; + if (type != that.type) return false; + return content.equals(that.content); }
codereview_java_data_8344
package com.hazelcast.jet.elasticsearch; -import com.hazelcast.function.SupplierEx; import com.hazelcast.jet.JetInstance; import com.hazelcast.jet.JetTestInstanceFactory; import com.hazelcast.jet.config.JetConfig; -import org.apache.http.HttpHost; -import org.elasticsearch.client.RestClient; -import org.elasticsearch.client.RestHighLevelClient; import org.junit.After; /** we can move this as a utility method to `ElasticSupport` package com.hazelcast.jet.elasticsearch; import com.hazelcast.jet.JetInstance; import com.hazelcast.jet.JetTestInstanceFactory; import com.hazelcast.jet.config.JetConfig; import org.junit.After; /**
codereview_java_data_8347
menu.findItem(R.id.menu_context_details).setVisible(false); menu.findItem(R.id.menu_context_save_attachment).setVisible(false); menu.findItem(R.id.menu_context_resend).setVisible(false); - menu.findItem(R.id.menu_context_copy).setVisible(!actionMessage); } else { MessageRecord messageRecord = messageRecords.iterator().next(); Doesn't this mean that selecting two media messages with no text will expose the "copy" option? menu.findItem(R.id.menu_context_details).setVisible(false); menu.findItem(R.id.menu_context_save_attachment).setVisible(false); menu.findItem(R.id.menu_context_resend).setVisible(false); } else { MessageRecord messageRecord = messageRecords.iterator().next();
codereview_java_data_8351
private void save(CompilationUnit cu, Path path) throws IOException { Files.createDirectories(path.getParent()); final String code = new PrettyPrinter().print(cu); - Files.write(path, code.getBytes()); } /** Oops, pass a character set to getBytes() please. private void save(CompilationUnit cu, Path path) throws IOException { Files.createDirectories(path.getParent()); final String code = new PrettyPrinter().print(cu); + Files.write(path, code.getBytes(UTF8)); } /**
codereview_java_data_8353
contained = false; List<Instance> instances = service.allIPs(); for (Instance instance : instances) { - String[] containedInstanceIpPort = IpUtil.splitIpPortStr(containedInstance); - if (containedInstanceIpPort.length == IpUtil.SPLIT_IP_PORT_RESULT_LENGTH) { if (StringUtils.equals(instance.getIp() + ":" + instance.getPort(), containedInstance)) { contained = true; break; replaced with `IpUtil.containPort`? contained = false; List<Instance> instances = service.allIPs(); for (Instance instance : instances) { + if (IpUtil.containsPort(containedInstance)) { if (StringUtils.equals(instance.getIp() + ":" + instance.getPort(), containedInstance)) { contained = true; break;
codereview_java_data_8363
count, skip, reverse, - labels -> () -> () -> 0.0D); final AtomicReference<AbstractPeerTask.PeerTaskResult<List<BlockHeader>>> actualResult = new AtomicReference<>(); final AtomicBoolean done = new AtomicBoolean(false); Should we make this a constant somewhere? It's a very cryptic line to have scattered around the code base so much. count, skip, reverse, + NoOpMetricsSystem.NO_OP_LABELLED_TIMER); final AtomicReference<AbstractPeerTask.PeerTaskResult<List<BlockHeader>>> actualResult = new AtomicReference<>(); final AtomicBoolean done = new AtomicBoolean(false);
codereview_java_data_8367
package com.hazelcast.jet.impl.exception; import com.hazelcast.jet.JetException; -import com.hazelcast.jet.impl.TerminationMode; - -import javax.annotation.Nonnull; public class EventLimitExceededException extends JetException { - public EventLimitExceededException() { - this(TerminationMode.CANCEL_GRACEFUL); - } - - private EventLimitExceededException(@Nonnull TerminationMode mode) { - super(mode.name()); - } } `CANCEL_GRACEFUL` is cancellation with a snapshot, an enterprise feature. And also what's the reason we're using this enum here? Just to get the text? package com.hazelcast.jet.impl.exception; import com.hazelcast.jet.JetException; public class EventLimitExceededException extends JetException { }
codereview_java_data_8369
private void sendMessageToSpecificAddresses( final Collection<Address> recipients, final MessageData message) { LOG.trace( - "Sending message to peers messageCode={} messageData={} recipients={}", - message.getCode(), - message.getData(), - recipients); recipients .stream() .map(peerConnections::get) the message data contained might be useful - but I suspect that given its a byte array, our ability to deconstruct it might be ... hard. private void sendMessageToSpecificAddresses( final Collection<Address> recipients, final MessageData message) { LOG.trace( + "Sending message to peers messageCode={} recipients={}", message.getCode(), recipients); recipients .stream() .map(peerConnections::get)
codereview_java_data_8372
textView.setVisibility(View.VISIBLE); } else - textView.setVisibility(View.INVISIBLE); } //region MENU Just hide the textview textView.setVisibility(View.VISIBLE); } else + textView.setVisibility(View.GONE); } //region MENU
codereview_java_data_8378
pendingRequest.getSkipHealthchecks(), pendingRequest.getMessage(), pendingRequest.getResources(), - null, pendingRequest.getActionId())); nextInstanceNumber++; this should be the last missing piece of the puzzle to connect it all the way through. The `SingularityPendingRequest` is the object that will carry the envOverrides from the RunNowRequest to the pending task. In `RequestResource.scheduleImmediately` we create a `SingularityPendingRequest` from the provided `SingularityRunNowRequest`. That pending request will need to take in the environment overrides, so that we can later use them on this line to put them on the pending task. The `RequestResource` calls `checkRunNowRequest` on the `SingularityValidator`, which is what actually constructs the object actually running some checks. That is where the envOverrides will need to be put on the `SingularityPendingRequest` pendingRequest.getSkipHealthchecks(), pendingRequest.getMessage(), pendingRequest.getResources(), + pendingRequest.getEnvOverrides(), pendingRequest.getActionId())); nextInstanceNumber++;
codereview_java_data_8381
@When("I type `$text` in field located `$locator` and keep keyboard opened") public void typeTextInFieldAndKeepKeyboard(String text, Locator locator) { - baseValidations.assertElementExists("The element to type text", locator) - .ifPresent(e -> keyboardActions.typeTextAndHide(e, text)); } /** ```suggestion .ifPresent(e -> keyboardActions.typeText(e, text)); ``` and the step below should be updated to use a method with updated name @When("I type `$text` in field located `$locator` and keep keyboard opened") public void typeTextInFieldAndKeepKeyboard(String text, Locator locator) { + baseValidations.assertElementExists(ELEMENT_TO_TYPE_TEXT, locator) + .ifPresent(e -> keyboardActions.typeText(e, text)); } /**
codereview_java_data_8385
import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.ArrayList; import java.util.Date; import java.util.List; Could you please make this verbose at least? It spams my entire logcat screen each time any page loads. :) import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Date; import java.util.List;
codereview_java_data_8396
static GridView gv_local_gallery; static ImageButton btn_local_more; static int local_rows_display = 0; - static LinearLayout ln_local_gallery; // Flickr Public static LinearLayout ln_flickr; TextView txtPFlickr; error: variable ln_local_gallery is already defined in class newGallery See the line number-165 static GridView gv_local_gallery; static ImageButton btn_local_more; static int local_rows_display = 0; // Flickr Public static LinearLayout ln_flickr; TextView txtPFlickr;
codereview_java_data_8398
if (task.isBeta) { header.addParam("isBeta", "true"); } - AsyncNotifyCallBack asyncNotifyCallBack = new AsyncNotifyCallBack(task); - try { - restTemplate.get(task.url, header, Query.EMPTY, String.class, asyncNotifyCallBack); - } catch (Exception e) { - asyncNotifyCallBack.onError(e); - } } } } Should we modified this `restTemplate.get` method, if any error when execute get, call the callback.onError in the` restTemplate.get` rather than throw exception? if (task.isBeta) { header.addParam("isBeta", "true"); } + restTemplate.get(task.url, header, Query.EMPTY, String.class, new AsyncNotifyCallBack(task)); } } }
codereview_java_data_8405
import com.google.idea.blaze.kotlin.sync.importer.BlazeKotlinWorkspaceImporter; import com.google.idea.blaze.kotlin.sync.model.BlazeKotlinImportResult; import com.google.idea.blaze.kotlin.sync.model.BlazeKotlinSyncData; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModifiableRootModel; This seems to be `settings.apiVersion` in 2017.2, but `settings.getApiVersion()` in 2017.3, we'll need an sdkcompat for this. import com.google.idea.blaze.kotlin.sync.importer.BlazeKotlinWorkspaceImporter; import com.google.idea.blaze.kotlin.sync.model.BlazeKotlinImportResult; import com.google.idea.blaze.kotlin.sync.model.BlazeKotlinSyncData; +import com.google.idea.sdkcompat.kotlin.BlazeKotlinCompilerArgumentsUpdaterCompat; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModifiableRootModel;
codereview_java_data_8409
assert aggregate == EXPECTED_AGGREGATE; return aggregate; } - - @Benchmark - public int slang_persistent_int() { - int aggregate = 0; - for (int i : RANDOMIZED_INDICES) { - final int[] leaf = (int[]) slangPersistentInt.leafUnsafe(i); - aggregate ^= leaf[slangPersistentInt.leafIndex(i)]; - } - assert aggregate == EXPECTED_AGGREGATE; - return aggregate; - } } /** Randomized update of every element */ it's more similar to the rest this way assert aggregate == EXPECTED_AGGREGATE; return aggregate; } } /** Randomized update of every element */
codereview_java_data_8419
assertThat(flowElement).isInstanceOf(ReceiveTask.class); assertThat(flowElement.getId()).isEqualTo("receiveTask"); - assertThat(model.getMainProcess().getCandidateStarterUsers()).isEqualTo(Arrays.asList("user1", "user2")); - assertThat(model.getMainProcess().getCandidateStarterGroups()).isEqualTo(Arrays.asList("group1", "group2")); } } Why not use `containsExactly` instead? assertThat(flowElement).isInstanceOf(ReceiveTask.class); assertThat(flowElement.getId()).isEqualTo("receiveTask"); + assertThat(model.getMainProcess().getCandidateStarterUsers()).containsExactly("user1", "user2"); + assertThat(model.getMainProcess().getCandidateStarterGroups()).containsExactly("group1", "group2"); } }
codereview_java_data_8422
/** * Resolves the SecurityContext * @author Dan Zheng - * @since 5.2.x */ public class CurrentSecurityContextArgumentResolver extends HandlerMethodArgumentResolverSupport { @rwinch, it may be a good time to consider whether this ought to be moved elsewhere since it's in four places now. What do you think? /** * Resolves the SecurityContext * @author Dan Zheng + * @since 5.2 */ public class CurrentSecurityContextArgumentResolver extends HandlerMethodArgumentResolverSupport {
codereview_java_data_8432
runningTaskIds = getRunningTaskIds(); } catch (Exception e) { LOG.error("While fetching running tasks from singularity", e); - exceptionNotifier.notify(String.format("Error fetchign running tasks (%s)", e.getMessage()), e, Collections.<String, String>emptyMap()); statisticsBldr.setErrorMessage(e.getMessage()); return statisticsBldr.build(); } Nit - typo in "fetching" runningTaskIds = getRunningTaskIds(); } catch (Exception e) { LOG.error("While fetching running tasks from singularity", e); + exceptionNotifier.notify(String.format("Error fetching running tasks (%s)", e.getMessage()), e, Collections.<String, String>emptyMap()); statisticsBldr.setErrorMessage(e.getMessage()); return statisticsBldr.build(); }
codereview_java_data_8438
nextQueue.add(result); } else { if (term.equals(result)) { - System.err.println("Step " + step + ": infinite loop after applying a spec rule."); proofResults.add(result); } } This is not an appropriate way to report a warning to a user, please look into KExceptionManager.registerCriticalWarning. nextQueue.add(result); } else { if (term.equals(result)) { + kem.registerCriticalWarning("Step " + step + ": infinite loop after applying a spec rule."); proofResults.add(result); } }
codereview_java_data_8443
ActivityResultLauncher<Intent> productActivityResultLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), (ActivityResultCallback<ActivityResult>) result -> { - setShownProduct(lastBarcode); }); /** ```suggestion if (result.getResultCode() == RESULT_OK) { setShownProduct(lastBarcode); } ``` ActivityResultLauncher<Intent> productActivityResultLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), (ActivityResultCallback<ActivityResult>) result -> { + if (result.getResultCode() == RESULT_OK) { + setShownProduct(lastBarcode); + } }); /**
codereview_java_data_8459
* Flag that indicates whether the connections of this type are client-oriented. * @return true if it is SOCKET_C2S or its fallback is SOCKET_C2S. */ - public boolean isC2S() { return SOCKET_C2S == this || SOCKET_C2S == this.getFallback(); } The naming of this method might be confusing. Can you rename it to `isClientOriented()`? * Flag that indicates whether the connections of this type are client-oriented. * @return true if it is SOCKET_C2S or its fallback is SOCKET_C2S. */ + public boolean isClientOriented() { return SOCKET_C2S == this || SOCKET_C2S == this.getFallback(); }
codereview_java_data_8468
} } - throw new IOException("readStringUntil(): end of stream reached. Read: " - + sb.toString() + " while waiting for '"+end+"'"); } private String readStringUntilEndOfLine() throws IOException { Code style: operator should be at the end of the line; missing spaces around last two `+` operators. One possible value of `end` is `\r`. We probably want to output the ASCII code rather than the character itself when `end` is less than 32. ```java throw new IOException("readStringUntil(): end of stream reached. " + "Read: \"" + sb.toString() + "\" while waiting for " + formatChar(end)); } private String formatChar(char value) { return value < 32 ? "[" + Integer.toString(value) + "]" : "'" + value + "'"; } ``` } } + throw new IOException("readStringUntil(): end of stream reached. " + + "Read: \"" + sb.toString() + "\" while waiting for " + formatChar(end)); + } + + private String formatChar(char value) { + return value < 32 ? "[" + Integer.toString(value) + "]" : "'" + value + "'"; } private String readStringUntilEndOfLine() throws IOException {
codereview_java_data_8475
// visible (not private) for testing VolumeChooser getDelegateChooser(VolumeChooserEnvironment env) { - switch (env.getScope()) { - case TABLE: - return getVolumeChooserForTable(env); - default: - return getVolumeChooserForScope(env); } } private VolumeChooser getVolumeChooserForTable(VolumeChooserEnvironment env) { At this point, the switch statement (here and in the other class) could be turned into a simple conditional: ```java if (env.getScope() == ChooserScope.TABLE) { return getVolumeChooserForTable(env); } return getVolumeChooserForScope(env); ``` This probably comes down to style also... both work fine, but the conditional is slightly shorter and probably easier to read, since the choice is binary. // visible (not private) for testing VolumeChooser getDelegateChooser(VolumeChooserEnvironment env) { + if (env.getScope() == ChooserScope.TABLE) { + return getVolumeChooserForTable(env); } + return getVolumeChooserForScope(env); } private VolumeChooser getVolumeChooserForTable(VolumeChooserEnvironment env) {
codereview_java_data_8477
initializeSuccessfulRegistry(appRegistry); when(this.taskLauncher.launch(any())).thenReturn("0"); taskExecutionService.executeTask("demo", new HashMap<>(), new LinkedList<>()); } } Can we test the task definitions repo to see if the task definition was created? initializeSuccessfulRegistry(appRegistry); when(this.taskLauncher.launch(any())).thenReturn("0"); taskExecutionService.executeTask("demo", new HashMap<>(), new LinkedList<>()); + assertNotNull(taskDefinitionRepository.findByTaskName("demo")); } }
codereview_java_data_8480
public void addHostedFeedData() throws IOException { if (feedDataHosted) throw new IllegalStateException("addHostedFeedData was called twice on the same instance"); for (int i = 0; i < NUM_FEEDS; i++) { - Feed feed = new Feed(0, null, "Title " + i, "https://news.google.com/news/rss?" + i, "Description of feed " + i, "http://example.com/pay/feed" + i, "author " + i, "en", Feed.TYPE_RSS2, "feed" + i, null, null, - "https://news.google.com/news/rss?" + i, false); // create items List<FeedItem> items = new ArrayList<>(); The tests should be fixed in #4841, so this is no longer needed public void addHostedFeedData() throws IOException { if (feedDataHosted) throw new IllegalStateException("addHostedFeedData was called twice on the same instance"); for (int i = 0; i < NUM_FEEDS; i++) { + Feed feed = new Feed(0, null, "Title " + i, "http://example.com/" + i, "Description of feed " + i, "http://example.com/pay/feed" + i, "author " + i, "en", Feed.TYPE_RSS2, "feed" + i, null, null, + "http://example.com/feed/src/" + i, false); // create items List<FeedItem> items = new ArrayList<>();
codereview_java_data_8481
@Override public int getTypeParameterCount() { if (typeParameterCount == -1) { - typeParameterCount = getTypeParameters(clazz).length; } return typeParameterCount; } I think, we should add here a try-catch for LinkageError. In case, we couldn't determine the type parameters, can we then set typeParametersCount=0 ? @Override public int getTypeParameterCount() { if (typeParameterCount == -1) { + try { + typeParameterCount = getTypeParameters(clazz).length; + } catch (LinkageError | TypeNotPresentException ignored) { + typeParameterCount = 0; // don't stay stuck on -1 + } } return typeParameterCount; }
codereview_java_data_8493
PreparedStatement prepareDomainScanStatement(String prefix, long modifiedSince) throws SQLException { - - Calendar cal = getCalendarInstance(); PreparedStatement ps; if (prefix != null && prefix.length() > 0) { this becomes a wasted operation if the command itself does not the calendar instance. please retain the original behavior where the calendar is obtained only when its needed. PreparedStatement prepareDomainScanStatement(String prefix, long modifiedSince) throws SQLException { + + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(MYSQL_SERVER_TIMEZONE)); PreparedStatement ps; if (prefix != null && prefix.length() > 0) {
codereview_java_data_8494
keystoreScanner.setScanInterval(reloadSslContextSeconds); server.addBean(keystoreScanner); } catch (IllegalArgumentException exception) { - LOG.error("Keystore will not be automatically reloaded when \"{}\" is changed: {}", sslContextFactory.getKeyStorePath(), exception.getMessage()); } } } I think that if reload is requested and there's an error during container boot we should throw an exception and prevent the service from coming up. Better than thinking it will be refreshed when it won't. keystoreScanner.setScanInterval(reloadSslContextSeconds); server.addBean(keystoreScanner); } catch (IllegalArgumentException exception) { + LOG.error("Keystore cant be automatically reloaded when \"{}\" is changed: {}", sslContextFactory.getKeyStorePath(), exception.getMessage()); + throw exception; } } }
codereview_java_data_8501
cmdList.add("-t"); cmdList.add("" + params.timeend); } - - // Streaming support -// cmdList.add("-movflags"); -// cmdList.add("frag_keyframe+empty_moov"); // Support for ffmpeg Experimental features cmdList.add("-strict"); @atamariya That's a speedy one, more well supported as well ;-) Is that "isml+frag_keyframe" will give same result ? cmdList.add("-t"); cmdList.add("" + params.timeend); } // Support for ffmpeg Experimental features cmdList.add("-strict");
codereview_java_data_8504
public static final int TIME_OR_TIMEZONE_CHANGE = 58; public static final int OMNIPOD_POD_NOT_ATTACHED = 59; public static final int CARBS_REQUIRED = 60; - public static final int IMPORTANCE_HIGH = 2; public static final int OMNIPOD_POD_SUSPENDED = 61; public static final int OMNIPOD_POD_ALERTS_UPDATED = 62; public static final String CATEGORY_ALARM = "alarm"; public static final int USERMESSAGE = 1000; Just a small ordering thing: Could you please bring `IMPORTANCE_HIGH` to the bottom and maybe even have one line between it and the Notification IDs? public static final int TIME_OR_TIMEZONE_CHANGE = 58; public static final int OMNIPOD_POD_NOT_ATTACHED = 59; public static final int CARBS_REQUIRED = 60; public static final int OMNIPOD_POD_SUSPENDED = 61; public static final int OMNIPOD_POD_ALERTS_UPDATED = 62; + public static final int IMPORTANCE_HIGH = 2; + public static final String CATEGORY_ALARM = "alarm"; public static final int USERMESSAGE = 1000;
codereview_java_data_8509
default void removeChildAtIndex(final int childIndex) { throw new UnsupportedOperationException("Out of scope for antlr current implementations"); } - - @Override - default List<Node> findChildNodesWithXPath(final String xpathString) throws JaxenException { - throw new UnsupportedOperationException("Out of scope for antlr current implementations"); - } } this is implemented in `Node`, do we really need to have it "unsupported" here? default void removeChildAtIndex(final int childIndex) { throw new UnsupportedOperationException("Out of scope for antlr current implementations"); } }
codereview_java_data_8517
import io.reactivex.Observable; /** - * Uses the PageEditInterface to make edit calls to MW API */ public class PageEditClient { Most of the java docs for methods in this class are not descriptive. Either make it descriptive or remove it if you are not sure what it does. Please check the same for other classes as well. :) import io.reactivex.Observable; /** + * This class acts as a Client to facilitate wiki page editing + * services to various dependency providing modules such as the Network module, the Review Controller ,etc + * + * The methods provided by this class will post to the Media wiki api + * documented at: https://commons.wikimedia.org/w/api.php?action=help&modules=edit */ public class PageEditClient {
codereview_java_data_8539
* @return */ public static boolean isMonumentsEnabled(final Date date) { - if (date.getDate() >= 1 && date.getMonth() >= 8 && date.getDate() <= 30 - && date.getMonth() <= 8) { return true; } return false; Shouldn't the month be `== 9` exactly? We want it to be active only from 1 Sep to 30 Sep. * @return */ public static boolean isMonumentsEnabled(final Date date) { + if (date.getMonth() == 8) { return true; } return false;
codereview_java_data_8546
); } } - - protected int getMaxDecommissioningAgents() { - return validator.getMaxDecommissioningAgents(); - } } The abstract machine resource serves both racks (e.g. aws availability zones) and agents. This would not apply for racks unless we have an equivalent maxDecommissioningRacks somewhere ); } } }
codereview_java_data_8554
public HttpResponse handleException(RequestContext ctx, HttpRequest req, Throwable cause) { ZipkinHttpCollector.metrics.incrementMessagesDropped(); - LOGGER.warn("Unexpected error handling request.", cause); - String message = cause.getMessage() != null ? cause.getMessage() : ""; if (cause instanceof IllegalArgumentException) { return HttpResponse.of(BAD_REQUEST, MediaType.ANY_TEXT_TYPE, message); } else { return HttpResponse.of(INTERNAL_SERVER_ERROR, MediaType.ANY_TEXT_TYPE, message); } } I'm not sure we want to add this logging in all cases. It seems too verbose to me for bad requests. public HttpResponse handleException(RequestContext ctx, HttpRequest req, Throwable cause) { ZipkinHttpCollector.metrics.incrementMessagesDropped(); String message = cause.getMessage() != null ? cause.getMessage() : ""; if (cause instanceof IllegalArgumentException) { return HttpResponse.of(BAD_REQUEST, MediaType.ANY_TEXT_TYPE, message); } else { + LOGGER.warn("Unexpected error handling request.", cause); + return HttpResponse.of(INTERNAL_SERVER_ERROR, MediaType.ANY_TEXT_TYPE, message); } }
codereview_java_data_8564
name = "UnclosedFilesStreamUsage", category = Category.ONE_OFF, severity = SeverityLevel.ERROR, - summary = "Ensure a stream returned by java.nio.file.Files#{list,walk} is closed.") public final class UnclosedFilesStreamUsage extends BugChecker implements BugChecker.MethodInvocationTreeMatcher { private static final long serialVersionUID = 1L; What about "Ensure a stream returned by java.nio.file.Files#{list,walk} is closed to prevent leaking file descriptors"? name = "UnclosedFilesStreamUsage", category = Category.ONE_OFF, severity = SeverityLevel.ERROR, + summary = "Ensure a stream returned by java.nio.file.Files#{list,walk} " + + "is closed to prevent leaking file descriptors.") public final class UnclosedFilesStreamUsage extends BugChecker implements BugChecker.MethodInvocationTreeMatcher { private static final long serialVersionUID = 1L;
codereview_java_data_8571
/** * @see <a href= "http://jonisalonen.com/2014/efficient-and-accurate-rolling-standard-deviation/">Efficient and accurate rolling standard deviation</a> */ - private void update(double n, double o, int w) { - double delta = n - o; double oldAverage = average; - average = average + delta / w; - variance += delta * (n - average + o - oldAverage) / (w - 1); stddev = FastMath.sqrt(variance); } I guess `n` & `o` is for new & old. Could instead use `newValue` & `oldValue` to make things clear. What is `w`? /** * @see <a href= "http://jonisalonen.com/2014/efficient-and-accurate-rolling-standard-deviation/">Efficient and accurate rolling standard deviation</a> */ + private void update(double newValue, double oldValue, int windowSize) { + double delta = newValue - oldValue; double oldAverage = average; + average = average + delta / windowSize; + variance += delta * (newValue - average + oldValue - oldAverage) / (windowSize - 1); stddev = FastMath.sqrt(variance); }
codereview_java_data_8580
* @author Glenn Renfro */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = { TaskDependencies.class, TaskServiceDependencies.class }, properties = { "spring.main.allow-bean-definition-overriding=true" }) @DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD) @AutoConfigureTestDatabase(replace = Replace.ANY) Do we need to create another Configuration class besides TaskDependencies so that we don't have to bean overriding? * @author Glenn Renfro */ @RunWith(SpringRunner.class) +@SpringBootTest(classes = { TaskServiceDependencies.class }, properties = { "spring.main.allow-bean-definition-overriding=true" }) @DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD) @AutoConfigureTestDatabase(replace = Replace.ANY)
codereview_java_data_8582
recipientsPanel.setPanelChangeListener(new RecipientsPanelChangeListener()); sendButton.setOnClickListener(sendButtonListener); - // Only enable send button if version is >4.4 and default sms app - boolean sendEnabled = false; - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - if(Telephony.Sms.getDefaultSmsPackage(this.getApplicationContext()).equals(this.getApplicationContext().getPackageName())) { - sendEnabled = true; - } - } else { - sendEnabled = true; - } - sendButton.setEnabled(sendEnabled); addContactButton.setOnClickListener(new AddRecipientButtonListener()); composeText.setOnKeyListener(composeKeyPressedListener); composeText.addTextChangedListener(composeKeyPressedListener); Is this necessary? I'd rather not break TextSecure functionality if it's non-default. recipientsPanel.setPanelChangeListener(new RecipientsPanelChangeListener()); sendButton.setOnClickListener(sendButtonListener); + sendButton.setEnabled(true); addContactButton.setOnClickListener(new AddRecipientButtonListener()); composeText.setOnKeyListener(composeKeyPressedListener); composeText.addTextChangedListener(composeKeyPressedListener);
codereview_java_data_8583
public class JsonUtil { /** - * Converts all to lowercase for easier lookup. This is useful incases such as the 'genesis.json' * file where all keys are assumed to be case insensitive. * * @param objectNode The ObjectNode to be normalized ```suggestion * Converts all to lowercase for easier lookup. This is useful in cases such as the 'genesis.json' ``` public class JsonUtil { /** + * Converts all to lowercase for easier lookup. This is useful in cases such as the 'genesis.json' * file where all keys are assumed to be case insensitive. * * @param objectNode The ObjectNode to be normalized
codereview_java_data_8596
*/ package org.apache.rocketmq.acl.common; -import com.alibaba.fastjson.JSONArray; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.apache.rocketmq.acl.plain.PlainAccessResource; public class Permission { It will be better to use Variable than raw integer. */ package org.apache.rocketmq.acl.common; import java.util.HashSet; +import java.util.List; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.apache.rocketmq.acl.plain.PlainAccessResource; +import org.apache.rocketmq.common.protocol.RequestCode; public class Permission {
codereview_java_data_8598
} - private boolean isContinuationChar(byte b) { return b >= (byte)0b1000_0000 && b <= (byte)0b1011_1111; } - private int numberOfFollowingBytes(byte b) { if (b >= (byte)0b1100_0000 && b <= (byte)0b1101_1111) { return 1; } else if (b >= (byte)0b1110_0000 && b <= (byte)0b1110_1111) { - make `isContinuationChar()` and `numberOfFollowingBytes()` static methods, since they don't depend on any local state - make all those binary numbers `private static final byte` constants } + private static boolean isContinuationChar(byte b) { return b >= (byte)0b1000_0000 && b <= (byte)0b1011_1111; } + private static int numberOfFollowingBytes(byte b) { if (b >= (byte)0b1100_0000 && b <= (byte)0b1101_1111) { return 1; } else if (b >= (byte)0b1110_0000 && b <= (byte)0b1110_1111) {
codereview_java_data_8604
log.warn("Use of {} and {} are deprecated. Consider using {} instead.", INSTANCE_DFS_URI, INSTANCE_DFS_DIR, Property.INSTANCE_VOLUMES); } - if (cipherSuite.equals(NULL_CIPHER) && !keyAlgorithm.equals(NULL_CIPHER)) { - fatal(Property.CRYPTO_CIPHER_SUITE.getKey() + " should be configured when " + Property.CRYPTO_CIPHER_KEY_ALGORITHM_NAME.getKey() + " is set."); - } - - if (!cipherSuite.equals(NULL_CIPHER) && keyAlgorithm.equals(NULL_CIPHER)) { - fatal(Property.CRYPTO_CIPHER_KEY_ALGORITHM_NAME.getKey() + " should be configured when " + Property.CRYPTO_CIPHER_SUITE.getKey() + " is set."); } if (cryptoModule.equals(NULL_CRYPTO_MODULE) && !secretKeyEncryptionStrategy.equals(NULL_SECRET_KEY_ENCRYPTION_STRATEGY)) { Would a single XOR-type check suffice to consolidate this and the following check? (with a reworded message, as appropriate): ```java (cipherSuite.equals(NULL_CIPHER) || keyAlgorithm.equals(NULL_CIPHER)) && !cipherSuite.equals(keyAlgorithm) ``` log.warn("Use of {} and {} are deprecated. Consider using {} instead.", INSTANCE_DFS_URI, INSTANCE_DFS_DIR, Property.INSTANCE_VOLUMES); } + if ((cipherSuite.equals(NULL_CIPHER) || keyAlgorithm.equals(NULL_CIPHER)) && !cipherSuite.equals(keyAlgorithm)) { + fatal(Property.CRYPTO_CIPHER_SUITE.getKey() + " and " + Property.CRYPTO_CIPHER_KEY_ALGORITHM_NAME + " must both be configured."); } if (cryptoModule.equals(NULL_CRYPTO_MODULE) && !secretKeyEncryptionStrategy.equals(NULL_SECRET_KEY_ENCRYPTION_STRATEGY)) {
codereview_java_data_8608
EnumSet.allOf(ColumnType.class), false); assertEquals(extent, tm.getExtent()); - assertEquals(HostAndPort.fromParts("server1", 8555), tm.getLocation().getLocation()); assertEquals("s001", tm.getLocation().getSession()); assertEquals(LocationType.FUTURE, tm.getLocation().getType()); assertFalse(tm.hasCurrent()); `getLocation().getLocation()` seems funny here. Too many types known as 'location'. EnumSet.allOf(ColumnType.class), false); assertEquals(extent, tm.getExtent()); + assertEquals(HostAndPort.fromParts("server1", 8555), tm.getLocation().getHostAndPort()); assertEquals("s001", tm.getLocation().getSession()); assertEquals(LocationType.FUTURE, tm.getLocation().getType()); assertFalse(tm.hasCurrent());
codereview_java_data_8610
private void performMapReadyActions() { if (((MainActivity)getActivity()).activeFragment == ActiveFragment.NEARBY && isMapBoxReady) { - if(!applicationKvStore.getBoolean("NotDisplayLocationPermissionAlertBox", false) || PermissionUtils.hasPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)){ checkPermissionsAndPerformAction(); }else{ Would you mind calling it `DoNotAskForLocationPermission`? If that sounds OK to you. private void performMapReadyActions() { if (((MainActivity)getActivity()).activeFragment == ActiveFragment.NEARBY && isMapBoxReady) { + if(!applicationKvStore.getBoolean("DoNotAskForLocationPermission", false) || PermissionUtils.hasPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)){ checkPermissionsAndPerformAction(); }else{
codereview_java_data_8623
* @param spec {@link PartitionSpec} used to produce {@link DataFile} partition tuples * @param outputFile the destination file location * @return a manifest writer */ public static ManifestWriter write(PartitionSpec spec, OutputFile outputFile) { return ManifestFiles.write(spec, outputFile); } Do we want to deprecate this too? * @param spec {@link PartitionSpec} used to produce {@link DataFile} partition tuples * @param outputFile the destination file location * @return a manifest writer + * @deprecated will be removed in 0.9.0; use {@link ManifestFiles#write(PartitionSpec, OutputFile)} instead. */ + @Deprecated public static ManifestWriter write(PartitionSpec spec, OutputFile outputFile) { return ManifestFiles.write(spec, outputFile); }
codereview_java_data_8627
} @Test - public void testLambdaBug1470() throws Exception { - String code = IOUtils.toString(ParserCornersTest.class.getResourceAsStream("LambdaBug1470.java"), - StandardCharsets.UTF_8); parseJava18(code); } We should make use of the method `readAsString(...)` instead. } @Test + public void testLambdaBug1470() { + String code = readAsString("LambdaBug1470.java"); parseJava18(code); }
codereview_java_data_8631
private DbException getSingleSortKeyException() { String sql = getSQL(); - return DbException.getSyntaxError(sql, sql.length() - 1, "single sort key is required for RANGE units"); } @Override exactly one sort key is required for RANGE units private DbException getSingleSortKeyException() { String sql = getSQL(); + return DbException.getSyntaxError(sql, sql.length() - 1, "exactly one sort key is required for RANGE units"); } @Override
codereview_java_data_8633
return 44_000; case ENUM: return 45_000; case ARRAY: return 50_000; case ROW: return 51_000; case RESULT_SET: return 52_000; - case JSON: - return 53_000; default: if (JdbcUtils.customDataTypesHandler != null) { return JdbcUtils.customDataTypesHandler.getDataTypeOrder(type); It should return some value lower than value for `ARRAY`. return 44_000; case ENUM: return 45_000; + case JSON: + return 46_000; case ARRAY: return 50_000; case ROW: return 51_000; case RESULT_SET: return 52_000; default: if (JdbcUtils.customDataTypesHandler != null) { return JdbcUtils.customDataTypesHandler.getDataTypeOrder(type);
codereview_java_data_8637
} else { throw new IllegalArgumentException("This process does not support parameters!"); } - } - variableScopeInstance.setDefaultValue(process, variableScope, variableScopeInstance); variableScopeInstance.enforceRequiredVariables(); return processInstance; I think setDefault value is not needed any longer } else { throw new IllegalArgumentException("This process does not support parameters!"); } + } variableScopeInstance.enforceRequiredVariables(); return processInstance;
codereview_java_data_8639
} @Test - public void permissionsSmartContractWithoutOptionMustDisplayUsage() { parseCommand("--permissions-nodes-contract-address"); verifyZeroInteractions(mockRunnerBuilder); I believe we want the CLI to fail when the user enables smart contract based permissioning but doesn't specify the contract address. We can't do smart contract permissioning without the address. } @Test + public void permissionsSmartContractWithoutOptionMustError() { parseCommand("--permissions-nodes-contract-address"); verifyZeroInteractions(mockRunnerBuilder);
codereview_java_data_8649
} /** - * Factory method for the subclasses of this class. * * @param range the range the import declaration covers. Range.UNKNOWN if not known. * @param name the qualified name of the import. This is not instantiating EmptyImportDeclarations, right? So it is not all subclasses } /** + * Factory method for import declarations. * * @param range the range the import declaration covers. Range.UNKNOWN if not known. * @param name the qualified name of the import.
codereview_java_data_8659
} /** - * Check if file destroyed in local dirs */ public static boolean fileExists(Uri localUri) { try { I think you may need to revert most of these "Find and replace" accidents ;) } /** + * Check if file exists in local dirs */ public static boolean fileExists(Uri localUri) { try {
codereview_java_data_8661
import com.hazelcast.function.SupplierEx; import com.hazelcast.jet.pipeline.Sink; import com.hazelcast.jet.pipeline.SinkBuilder; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.DocWriteRequest; how about changing this to `SupplierEx<? extends RestClientBuilder> clientBuilderSupport`. This will simplify the client creation for user and remove the necessity for a `destroyFn` import com.hazelcast.function.SupplierEx; import com.hazelcast.jet.pipeline.Sink; import com.hazelcast.jet.pipeline.SinkBuilder; +import com.hazelcast.logging.ILogger; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.DocWriteRequest;
codereview_java_data_8665
private int collectStatus; - private Map<String, String> listenersGrouperStatus; public int getCollectStatus() { return collectStatus; Why you change the name to 'listenersGrouperStatus', maybe 'listenersGroupKeyStatus' is better? I understand the word 'listener' is spelled wrong. private int collectStatus; + private Map<String, String> listenersGroupkeyStatus; public int getCollectStatus() { return collectStatus;
codereview_java_data_8666
private void testRecursiveTable() throws Exception { String[] expectedRowData =new String[]{"|meat|null","|fruit|3","|veg|2"}; String[] expectedColumnNames =new String[]{"VAL", - "SUM(SELECT X FROM ( SELECT SUM(1) AS X, A FROM PUBLIC.C INNER JOIN PUBLIC.B ON 1=1 WHERE B.VAL = C.B GROUP BY A ) BB WHERE BB.A IS A.VAL)"}; deleteDb("commonTableExpressionQueries"); Connection conn = getConnection("commonTableExpressionQueries"); this seems a little clever compared to a normal for loop :-) private void testRecursiveTable() throws Exception { String[] expectedRowData =new String[]{"|meat|null","|fruit|3","|veg|2"}; String[] expectedColumnNames =new String[]{"VAL", + "SUM(SELECT\n X\nFROM PUBLIC.\"\" BB\n /* SELECT\n SUM(1) AS X,\n A\n FROM PUBLIC.B\n /++ PUBLIC.B.tableScan ++/\n /++ WHERE A IS ?1\n ++/\n /++ scanCount: 4 ++/\n INNER JOIN PUBLIC.C\n /++ PUBLIC.C.tableScan ++/\n ON 1=1\n WHERE (A IS ?1)\n AND (B.VAL = C.B)\n GROUP BY A: A IS A.VAL\n */\n /* scanCount: 1 */\nWHERE BB.A IS A.VAL)"}; deleteDb("commonTableExpressionQueries"); Connection conn = getConnection("commonTableExpressionQueries");
codereview_java_data_8670
if (ds.getTotalConCount() <= 0) { ds.initMinConnection(null, true, getConHandler, null); } else { - LOGGER.info("connection with null schema has been created,because testConnection in pool"); getConHandler.initIncrement(); hasConnectionInPool = true; } can you also fix `because ...`? if (ds.getTotalConCount() <= 0) { ds.initMinConnection(null, true, getConHandler, null); } else { + LOGGER.info("connection with null schema has been created,because we tested the connection of the datasource at first"); getConHandler.initIncrement(); hasConnectionInPool = true; }
codereview_java_data_8677
public static final String APP_IS_DEFAULT = "APP_IS_DEFAULT"; public static final String STREAM_DEFINITION_DSL_TEXT = "streamDefinitionDslText"; public static final String TASK_DEFINITION_NAME = "taskDefinitionName"; I think app `uri` and `metadataUri` are the most important ones which are now not added. public static final String APP_IS_DEFAULT = "APP_IS_DEFAULT"; + public static final String APP_URI = "uri"; + + public static final String APP_META_DATA_URI = "metaDataUri"; + public static final String STREAM_DEFINITION_DSL_TEXT = "streamDefinitionDslText"; public static final String TASK_DEFINITION_NAME = "taskDefinitionName";
codereview_java_data_8692
@Nonnull Properties properties, @Nonnull FunctionEx<? super E, ProducerRecord<K, V>> toRecordFn ) { - // TODO [viliam] what should be the default for exactlyOnce? return Sinks.fromProcessor("writeKafka", writeKafkaP(properties, toRecordFn, true)); } Don't forget about this, I guess you wanted to address it before merging in. @Nonnull Properties properties, @Nonnull FunctionEx<? super E, ProducerRecord<K, V>> toRecordFn ) { return Sinks.fromProcessor("writeKafka", writeKafkaP(properties, toRecordFn, true)); }
codereview_java_data_8694
import java.util.Collections; import java.util.List; import fr.free.nrw.commons.R; import fr.free.nrw.commons.location.LatLng; import fr.free.nrw.commons.utils.UriDeserializer; import timber.log.Timber; -public class NearbyListFragment extends Fragment { private static final Type LIST_TYPE = new TypeToken<List<Place>>() { }.getType(); private static final Type CUR_LAT_LNG_TYPE = new TypeToken<LatLng>() { Why undo usage of `DaggerFragment` import java.util.Collections; import java.util.List; +import dagger.android.support.DaggerFragment; import fr.free.nrw.commons.R; import fr.free.nrw.commons.location.LatLng; import fr.free.nrw.commons.utils.UriDeserializer; import timber.log.Timber; +public class NearbyListFragment extends DaggerFragment { private static final Type LIST_TYPE = new TypeToken<List<Place>>() { }.getType(); private static final Type CUR_LAT_LNG_TYPE = new TypeToken<LatLng>() {
codereview_java_data_8698
severity = BugPattern.SeverityLevel.WARNING, summary = "Calling address.getHostName may result in a DNS lookup which is a network request, making the " + "invocation significantly more expensive than expected depending on the environment.\n" - + "This check is intended to be advisory - it's fine to @SuppressWarnings(\"ReverseDnsLookup\") " + "in certain cases, but is usually not recommended.") public final class ReverseDnsLookup extends BugChecker implements BugChecker.MethodInvocationTreeMatcher { Nit: double-space `check is` severity = BugPattern.SeverityLevel.WARNING, summary = "Calling address.getHostName may result in a DNS lookup which is a network request, making the " + "invocation significantly more expensive than expected depending on the environment.\n" + + "This check is intended to be advisory - it's fine to @SuppressWarnings(\"ReverseDnsLookup\") " + "in certain cases, but is usually not recommended.") public final class ReverseDnsLookup extends BugChecker implements BugChecker.MethodInvocationTreeMatcher {
codereview_java_data_8702
controllingMetaTag.setCapability(capabilities, meta); } } - - public static boolean isContainedIn(Meta meta, String metaName) - { - return new MetaWrapper(meta).getOptionalPropertyValue(metaName).isPresent(); - } } no need to make this method a part of ControllingMetaTag controllingMetaTag.setCapability(capabilities, meta); } } }
codereview_java_data_8707
try { List<ByteBuffer> messageBufferList = getMessageResult.getMessageBufferList(); for (ByteBuffer bb : messageBufferList) { - MessageExt msgExt = MessageDecoder.decode(bb); if (msgExt != null) { foundList.add(msgExt); } MessageExt msgExt = MessageDecoder.decode(bb); = MessageExt msgExt = MessageDecoder.decode(bb, true, false); to prevent the uncompress more that one times. try { List<ByteBuffer> messageBufferList = getMessageResult.getMessageBufferList(); for (ByteBuffer bb : messageBufferList) { + MessageExt msgExt = MessageDecoder.decode(bb, true, false); if (msgExt != null) { foundList.add(msgExt); }
codereview_java_data_8709
public void clear() { - service.getConnection().setProto(new MySQLProtoHandlerImpl()); isStart = false; schema = null; tableConfig = null; should keep this status in new "ProtoHandler" . public void clear() { + ProtoHandler proto = service.getConnection().getProto(); + if (proto instanceof LoadDataProtoHandlerImpl) { + service.getConnection().setProto(((LoadDataProtoHandlerImpl) proto).getMySQLProtoHandler()); + } isStart = false; schema = null; tableConfig = null;
codereview_java_data_8717
if (StringUtils.isNotBlank(sparkUploadFiles)) { sb.append("--files ").append(sparkUploadFiles).append(" "); } - sb.append("--principal ").append(config.getKerberosPrincipal()).append(" "); - sb.append("--keytab ").append(config.getKerberosKeytabPath()).append(" "); sb.append("--name job_step_%s "); sb.append("--jars %s %s %s"); String cmd = String.format(Locale.ROOT, sb.toString(), hadoopConf, sparkSubmitCmd, getId(), jars, kylinJobJar, why it needs these two lines directly ? please check the code in the method 'replaceSparkNodeJavaOpsConfIfNeeded', it will set the parameters about kerberos according to 'config.isKerberosEnabled()' if (StringUtils.isNotBlank(sparkUploadFiles)) { sb.append("--files ").append(sparkUploadFiles).append(" "); } + if (config.isKerberosEnabled()) { + sb.append("--principal ").append(config.getKerberosPrincipal()).append(" "); + sb.append("--keytab ").append(config.getKerberosKeytabPath()).append(" "); + } sb.append("--name job_step_%s "); sb.append("--jars %s %s %s"); String cmd = String.format(Locale.ROOT, sb.toString(), hadoopConf, sparkSubmitCmd, getId(), jars, kylinJobJar,
codereview_java_data_8732
import org.apache.iceberg.types.Types.StringType; import org.apache.iceberg.types.Types.StructType; -import java.nio.ByteBuffer; -import java.util.List; -import java.util.Map; import static org.apache.iceberg.types.Types.NestedField.optional; import static org.apache.iceberg.types.Types.NestedField.required; My guess is that import changes caused the tests to fail. import org.apache.iceberg.types.Types.StringType; import org.apache.iceberg.types.Types.StructType; import static org.apache.iceberg.types.Types.NestedField.optional; import static org.apache.iceberg.types.Types.NestedField.required;
codereview_java_data_8733
EventBus.getDefault().register(this); chip = layout.findViewById(R.id.feed_title_chip); - if ((getArguments().getLong(ARG_FEED) != 0) && !FEED_TITLE.isEmpty()) { - chip.setText(FEED_TITLE); - } else { - chip.setVisibility(View.GONE); - } return layout; } Please move this to the results section of the `search` method. This makes it possible to add a close button to the chip (which would greatly improve the user experience) with something like: ``` app:closeIconVisible="true" ``` ``` chip.setOnCloseIconClickListener(v -> { getArguments().putLong(ARG_FEED, 0); search(); }); ``` EventBus.getDefault().register(this); chip = layout.findViewById(R.id.feed_title_chip); + chip.setOnCloseIconClickListener(v -> { + getArguments().putLong(ARG_FEED, 0); + search(); + }); return layout; }
codereview_java_data_8739
// using the connection for the aborted session is expected to throw an // exception - assertThrows(ErrorCode.DATABASE_CALLED_AT_SHUTDOWN, stat2).executeQuery("select count(*) from test"); conn2.close(); conn.close(); It looks like you need to replace `ErrorCode.DATABASE_CALLED_AT_SHUTDOWN` with `config.networked ? ErrorCode.CONNECTION_BROKEN_1 : ErrorCode.DATABASE_CALLED_AT_SHUTDOWN`. // using the connection for the aborted session is expected to throw an // exception + assertThrows(config.networked ? ErrorCode.CONNECTION_BROKEN_1 : ErrorCode.DATABASE_CALLED_AT_SHUTDOWN, stat2) + .executeQuery("select count(*) from test"); conn2.close(); conn.close();
codereview_java_data_8741
/** * Auto load suggestions into various NachoTextViews - * */ - private void loadAutoSuggestions() { - DaoSession daoSession = OFFApplication.getInstance().getDaoSession(); AsyncSession asyncSessionCountries = daoSession.startAsyncSession(); AsyncSession asyncSessionLabels = daoSession.startAsyncSession(); AsyncSession asyncSessionCategories = daoSession.startAsyncSession(); ```suggestion /** * Auto load suggestions into various NachoTextViews * */ private void loadAutoSuggestions() { ``` /** * Auto load suggestions into various NachoTextViews + */ private void loadAutoSuggestions() { + DaoSession daoSession = OFFApplication.getDaoSession(); AsyncSession asyncSessionCountries = daoSession.startAsyncSession(); AsyncSession asyncSessionLabels = daoSession.startAsyncSession(); AsyncSession asyncSessionCategories = daoSession.startAsyncSession();
codereview_java_data_8758
} public void updateHeightEstimate(final long blockNumber) { - estimatedHeightKnown = true; - if (blockNumber > estimatedHeight) { - estimatedHeight = blockNumber; - estimatedHeightListeners.forEach(e -> e.onEstimatedHeightChanged(estimatedHeight)); } } This will need a `synchronized` block around the whole method content. Previously it was only called from other methods which already had `synchronized`. } public void updateHeightEstimate(final long blockNumber) { + synchronized (this) { + estimatedHeightKnown = true; + if (blockNumber > estimatedHeight) { + estimatedHeight = blockNumber; + estimatedHeightListeners.forEach(e -> e.onEstimatedHeightChanged(estimatedHeight)); + } } }
codereview_java_data_8763
{ String roundingModes = Stream.of(RoundingMode.values()).map(e -> e.name().toLowerCase()) .collect(Collectors.joining("|")); - String pattern = String.format("^round(?:\\((-?\\d+(?:\\.\\d*)?[Ee]?-?\\+?\\d*)" - + "(?:,\\s*(\\d+))?(?:,\\s*(%s))?\\))$", roundingModes); ROUND_EXPRESSION_PATTERN = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); } this regex will also match the following invalid strings: - `0.15237E` - `0.15237E-+2` - `0.15237-2` - `0.15237+2` { String roundingModes = Stream.of(RoundingMode.values()).map(e -> e.name().toLowerCase()) .collect(Collectors.joining("|")); + String pattern = String.format("^round(?:\\((-?\\d+(?:\\.\\d*)?(?:[Ee]+-?\\d+)?)(?:,\\s*(\\d+))?" + + "(?:,\\s*(%s))?\\))$", roundingModes); ROUND_EXPRESSION_PATTERN = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); }
codereview_java_data_8772
if (!s.isGoogleChromeAvailable()) { htmlClass += "browserNotAvailable "; imgSrc = imgSrc.split(".png")[0].concat("_unavailable.png"); - title = "browser not available"; } else { htmlClass += "browserAvailable "; } else if (browserName.contains(BrowserType.IE) || browserName.contains(BrowserType.IEXPLORE)) if (!s.isInternetExplorerAvailable()) { htmlClass += "browserNotAvailable "; imgSrc = imgSrc.split(".png")[0].concat("_unavailable.png"); - title = "browser not available"; } else { htmlClass += "browserAvailable "; } else if (browserName.contains(BrowserType.FIREFOX) || browserName.contains(BrowserType.FIREFOX_2) mentioned in IRC to change wording here and the 3 others below if (!s.isGoogleChromeAvailable()) { htmlClass += "browserNotAvailable "; imgSrc = imgSrc.split(".png")[0].concat("_unavailable.png"); + title = "browser not installed / found"; } else { htmlClass += "browserAvailable "; } else if (browserName.contains(BrowserType.IE) || browserName.contains(BrowserType.IEXPLORE)) if (!s.isInternetExplorerAvailable()) { htmlClass += "browserNotAvailable "; imgSrc = imgSrc.split(".png")[0].concat("_unavailable.png"); + title = "browser not installed / found"; } else { htmlClass += "browserAvailable "; } else if (browserName.contains(BrowserType.FIREFOX) || browserName.contains(BrowserType.FIREFOX_2)
codereview_java_data_8778
try { var config = new PropertiesConfiguration(); try (var reader = new FileReader(accumuloConfigUrl.getFile())) { - config.getLayout().load(config, reader); } String value = config.getString(propertyName); if (value != null) I wasn't aware of the `read()` method before. Apparently, we can just call `config.read(reader)` here. I also wasn't aware of `FileHandler` before, which I see is being used when saving files. I think we should try to be consistent. We should either use: ```java var config = PropertiesConfiguration(); try (var reader = new FileReader()) { config.read(reader); } // and try (var writer = new FileWriter()) { config.write(writer); } ``` OR ```java var config = new PropertiesConfiguration(); var fileHandler = new FileHandler(config); fileHandler.load(file); // and fileHandler.save(file); ``` Ultimately, they will both do the same thing, but I'm not sure which one is cleaner, since we still need to handle exceptions. Either way, but we should consistently use one pattern or the other. try { var config = new PropertiesConfiguration(); try (var reader = new FileReader(accumuloConfigUrl.getFile())) { + config.read(reader); } String value = config.getString(propertyName); if (value != null)
codereview_java_data_8781
} // remove map files that have no more key extents to assign - assignmentFailures.entrySet().removeIf(entry -> entry.getValue().size() == 0); Set<Entry<Path,Integer>> failureIter = failureCount.entrySet(); for (Entry<Path,Integer> entry : failureIter) { may be able to use `assignmentFailures.values()` here } // remove map files that have no more key extents to assign + assignmentFailures.values().removeIf(List::isEmpty); Set<Entry<Path,Integer>> failureIter = failureCount.entrySet(); for (Entry<Path,Integer> entry : failureIter) {
codereview_java_data_8782
* Account stores all of the settings for a single account defined by the user. It is able to save * and delete itself given a Preferences to work with. Each account is defined by a UUID. */ -@SuppressWarnings("unused") // unused methods are public API public class Account implements BaseAccount, StoreConfig { /** * Default value for the inbox folder (never changes for POP3 and IMAP) Still not a fan of suppressing warnings on such a broad scope. Warnings are usually there for a reason. Try to fix the issue. Otherwise preserve the warning so others will look into it eventually. In this case the reasoning feels weird, too. `Account` is not exposed outside of the app, so really there's no public API. If we don't use a method, then nobody is. * Account stores all of the settings for a single account defined by the user. It is able to save * and delete itself given a Preferences to work with. Each account is defined by a UUID. */ public class Account implements BaseAccount, StoreConfig { /** * Default value for the inbox folder (never changes for POP3 and IMAP)
codereview_java_data_8791
Object actualValue = actualRow[col]; if (expectedValue != null && expectedValue.getClass().isArray()) { String newContext = String.format("%s (nested col %d)", context, col + 1); - if (expectedValue.getClass().getComponentType().isPrimitive()) { - new ExactComparisonCriteria().arrayEquals(newContext, expectedValue, actualValue); - } else { - assertEquals(newContext, (Object[]) expectedValue, (Object[]) actualValue); - } } else if (expectedValue != ANY) { Assert.assertEquals(context + " contents should match", expectedValue, actualValue); } Why was this needed? Object actualValue = actualRow[col]; if (expectedValue != null && expectedValue.getClass().isArray()) { String newContext = String.format("%s (nested col %d)", context, col + 1); + assertEquals(newContext, (Object[]) expectedValue, (Object[]) actualValue); } else if (expectedValue != ANY) { Assert.assertEquals(context + " contents should match", expectedValue, actualValue); }
codereview_java_data_8792
public static final String DEFAULT_LICENSE = "defaultLicense"; public static final String UPLOADS_SHOWING = "uploadsshowing"; public static final String MANAGED_EXIF_TAGS = "managed_exif_tags"; - public static final String KEY_DESCRIPTION_LANGUAGE_VALUE = "languageDescription"; - public static final String KEY_APP_UI_LANGUAGE = "appUiLanguage"; public static final String KEY_THEME_VALUE = "appThemePref"; public static final String TELEMETRY_PREFERENCE = "telemetryPref"; I am sorry to ask you to change this again, but would you mind making it: ``` public static final String DESCRIPTION_LANGUAGE = "descriptionLanguage"; public static final String APP_UI_LANGUAGE = "appUiLanguage"; ``` public static final String DEFAULT_LICENSE = "defaultLicense"; public static final String UPLOADS_SHOWING = "uploadsshowing"; public static final String MANAGED_EXIF_TAGS = "managed_exif_tags"; + public static final String DESCRIPTION_LANGUAGE = "descriptionLanguage"; + public static final String APP_UI_LANGUAGE = "appUiLanguage"; public static final String KEY_THEME_VALUE = "appThemePref"; public static final String TELEMETRY_PREFERENCE = "telemetryPref";
codereview_java_data_8801
if (badArgs.isEmpty()) { return Description.NO_MATCH; } - - return buildDescription(tree) - .setMessage("slf4j log statement does not use logsafe parameters for arguments " + badArgs) - .build(); } } prefer symmetry for return cases: ``` Foo foo() { if (!precondition) { return ...; // early return is OK } // lots of logic // return something depending on logic if (something) { return ...; } else { return ...; } } ``` if (badArgs.isEmpty()) { return Description.NO_MATCH; + } else { + return buildDescription(tree) + .setMessage("slf4j log statement does not use logsafe parameters for arguments " + badArgs) + .build(); } } }
codereview_java_data_8816
List<Bound> newBounds = new ArrayList<>(); while (!constraints.isEmpty()) { - List<BoundOrConstraint> reduceResult = constraints.get(constraints.size() - 1).reduce(); - constraints.remove(constraints.size() - 1); - for (BoundOrConstraint boundOrConstraint : reduceResult) { if (boundOrConstraint instanceof Bound) { newBounds.add((Bound) boundOrConstraint); these 2 lines could be condensed. `remove` returns the removed element, so you could directly write: `List<BoundOrConstraint> reduceResult = constraints.remove(constraints.size() - 1).reduce();` List<Bound> newBounds = new ArrayList<>(); while (!constraints.isEmpty()) { + List<BoundOrConstraint> reduceResult = constraints.remove(constraints.size() - 1).reduce(); + for (BoundOrConstraint boundOrConstraint : reduceResult) { if (boundOrConstraint instanceof Bound) { newBounds.add((Bound) boundOrConstraint);
codereview_java_data_8828
return data; } - protected void init() { - reportPrivate = getProperty(REPORT_PRIVATE_DESCRIPTOR); - reportProtected = getProperty(REPORT_PROTECTED_DESCRIPTOR); - } - private void handleClassOrInterface(ApexNode<?> node, Object data) { ApexDocComment comment = getApexDocComment(node); if (comment == null) { You can override `start(RuleContext)` instead of using your custom init method. It will be called once per file. Even better, you could remove the fields and just use getProperty in the handleClassOrInterface method. return data; } private void handleClassOrInterface(ApexNode<?> node, Object data) { ApexDocComment comment = getApexDocComment(node); if (comment == null) {
codereview_java_data_8831
threw = false; } catch (TException | UnknownHostException e) { if (e.getMessage().contains("Table/View 'HIVE_LOCKS' does not exist")) { - LOG.error("Failed to acquire locks from metastore because 'HIVE_LOCKS' doesn't exist, " + - "this probably happened when using embedded metastore or doesn't create transactional" + - " meta table. Please reconfigure and start the metastore.", e); } throw new RuntimeException(String.format("Metastore operation failed for %s.%s", database, tableName), e); This recommendation isn't very helpful because it isn't clear what "the metastore" is. How about this instead: "To fix this, use an alternative metastore". threw = false; } catch (TException | UnknownHostException e) { if (e.getMessage().contains("Table/View 'HIVE_LOCKS' does not exist")) { + throw new RuntimeException("Failed to acquire locks from metastore because 'HIVE_LOCKS' doesn't " + + "exist, this probably happened when using embedded metastore or doesn't create a " + + "transactional meta table. To fix this, use an alternative metastore", e); } throw new RuntimeException(String.format("Metastore operation failed for %s.%s", database, tableName), e);
codereview_java_data_8833
}); } - private Activity getActivity() { - return this.getActivity(); - } - private boolean isProductIncomplete() { return product != null && (product.getImageUrl() == null || product.getQuantity() == null || product.getProductName() == null || product.getBrands() == null || Why is this method created? It is not used anywhere and this method recurses infinitely and can only end by throwing an exception. I guess this method should be removed. }); } private boolean isProductIncomplete() { return product != null && (product.getImageUrl() == null || product.getQuantity() == null || product.getProductName() == null || product.getBrands() == null ||
codereview_java_data_8836
import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; public class SWString extends SWItem { private List<String> labels; private List<String> values; private String groupName; this is only for radiobuttons ... (on more places) import android.widget.LinearLayout; import android.widget.TextView; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.List; public class SWString extends SWItem { + private static Logger log = LoggerFactory.getLogger(SWString.class); private List<String> labels; private List<String> values; private String groupName;
codereview_java_data_8842
} public double getQueueFullness() { - LOG.info("Queue size: {}", statusUpdatesExecutor.getQueue().size()); return ( (double) statusUpdatesExecutor.getQueue().size() / statusUpdatesExecutor.getQueueLimit() should I add more, like queue limit and the computation of queue fullness? } public double getQueueFullness() { + LOG.info( + "Queue size: {}, queue limit: {}, queue fullness: {}", + statusUpdatesExecutor.getQueue().size(), + statusUpdatesExecutor.getQueueLimit(), + (double) statusUpdatesExecutor.getQueue().size() / + statusUpdatesExecutor.getQueueLimit() + ); return ( (double) statusUpdatesExecutor.getQueue().size() / statusUpdatesExecutor.getQueueLimit()
codereview_java_data_8843
} } - @Override - public void onResume() { - super.onResume(); - backToCover(false); - } - public void backToCover(Boolean smoothScroll) { if (pager == null) { return; Please do this in `onStart` instead. Otherwise, it breaks using the app in multiwindow mode } } public void backToCover(Boolean smoothScroll) { if (pager == null) { return;
codereview_java_data_8847
} @Test - public void shutdown() throws NacosException { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848"); final ServerListManager serverListManager = new ServerListManager(properties); - serverListManager.shutdown(); } } Sorry, test method should be start with test } @Test + public void testShutdown() { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848"); final ServerListManager serverListManager = new ServerListManager(properties); + try { + serverListManager.shutdown(); + } catch (Exception e) { + Assert.fail(); + } } }
codereview_java_data_8853
deleteDb("fullTextReopen"); } - private static void close(Collection<Connection> list) throws SQLException { for (Connection conn : list) { - try { conn.close(); } catch (SQLException ignore) {/**/} } } we have IOUtils.closeSilently for this deleteDb("fullTextReopen"); } + private static void close(Collection<Connection> list) { for (Connection conn : list) { + IOUtils.closeSilently(conn); } }