id
stringlengths
23
26
content
stringlengths
182
2.49k
codereview_java_data_7125
} @Bean - @ConditionalOnMissingBean public DelegatingResourceLoader delegatingResourceLoader(MavenResourceLoader mavenResourceLoader) { DefaultResourceLoader defaultLoader = new DefaultResourceLoader(); Map<String, ResourceLoader> loaders = new HashMap<>(); I believe this should be: `@ConditionalOnMissingBean(DelegatingResourceLoader.class)` } @Bean + @ConditionalOnMissingBean(DelegatingResourceLoader.class) public DelegatingResourceLoader delegatingResourceLoader(MavenResourceLoader mavenResourceLoader) { DefaultResourceLoader defaultLoader = new DefaultResourceLoader(); Map<String, ResourceLoader> loaders = new HashMap<>();
codereview_java_data_7127
*/ public void notifyClientConnected(final Connection connection) { - if (connection.getAbilities() != null && connection.getAbilities().getConfigAbility() != null) { - if (connection.getAbilities().getConfigAbility().isSupportRemoteMetrics()) { - MetricsMonitor.getConfigTotalConnection().getAndIncrement(); - } - if (connection.getAbilities().getNamingAbility().isSupportRemoteMetric()) { - MetricsMonitor.getNamingTotalConnection().getAndIncrement(); - } - } - for (ClientConnectionEventListener clientConnectionEventListener : clientConnectionEventListeners) { try { clientConnectionEventListener.clientConnected(connection); Should extends `ClientConnectionEventListener`. */ public void notifyClientConnected(final Connection connection) { for (ClientConnectionEventListener clientConnectionEventListener : clientConnectionEventListeners) { try { clientConnectionEventListener.clientConnected(connection);
codereview_java_data_7131
/** * Attempt to consume the event and update the maintained state * - * @param event the external Action that has occurred * @param roundTimer timer that will fire expiry events that are expected to be received back into * this machine * @return whether this event was consumed or requires reprocessing later once the state machine This got capitalised in an auto refactor from the Action type? /** * Attempt to consume the event and update the maintained state * + * @param event the external action that has occurred * @param roundTimer timer that will fire expiry events that are expected to be received back into * this machine * @return whether this event was consumed or requires reprocessing later once the state machine
codereview_java_data_7140
quotaCheck.checkGroupQuota(con, domainName, group, ctx.getApiName()); - // retrieve our original role Group originalGroup = getGroup(con, domainName, groupName, false, false); // retrieve our original group quotaCheck.checkGroupQuota(con, domainName, group, ctx.getApiName()); + // retrieve our original group Group originalGroup = getGroup(con, domainName, groupName, false, false);
codereview_java_data_7141
} } try { - if (jobDefinition instanceof PipelineImpl) { - return newJob((PipelineImpl) jobDefinition, config); - } else { - return newJob((DAG) jobDefinition, config); - } } catch (JobAlreadyExistsException e) { logFine(getLogger(), "Could not submit job with duplicate name: %s, ignoring", config.getName()); } Maybe we can create a `JobDefinition` interface that will be internal. Will have no methods and can extend `Serializable`. Then make `DAG` and `PipelineImpl` implement it. It can be more readable this way. Then we can have `newJobInt` method that will do the above switching. } } try { + return newJobInt(jobDefinition, config); } catch (JobAlreadyExistsException e) { logFine(getLogger(), "Could not submit job with duplicate name: %s, ignoring", config.getName()); }
codereview_java_data_7152
return entry.getValue(); } - // The non-virtual interface was not found so choose the first virtual one if exists if (!virtualInterfaces.isEmpty()) { for (Entry<String, InterfaceAssociation> entry : virtualInterfaces.entrySet()) { return entry.getValue(); ```suggestion // We did not find any non-virtual interfaces, so choose the first virtual one if it exists ``` return entry.getValue(); } + // We did not find any non-virtual interfaces, so choose the first virtual one if it exists if (!virtualInterfaces.isEmpty()) { for (Entry<String, InterfaceAssociation> entry : virtualInterfaces.entrySet()) { return entry.getValue();
codereview_java_data_7162
@Override public void addObserver(@Nonnull Observer<T> observer) { - this.observers.add(observer); } @Override public void addObserver(@Nonnull Consumer<? super T> onNext, @Nonnull Consumer<? super Throwable> onError, @Nonnull Runnable onComplete) { - this.observers.add(Observer.of(onNext, onError, onComplete)); } @Override you don't need to prefix everything with `this` here. @Override public void addObserver(@Nonnull Observer<T> observer) { + observers.add(observer); } @Override public void addObserver(@Nonnull Consumer<? super T> onNext, @Nonnull Consumer<? super Throwable> onError, @Nonnull Runnable onComplete) { + observers.add(Observer.of(onNext, onError, onComplete)); } @Override
codereview_java_data_7163
} @Override - public void close() throws Exception { // nothing to do } } does SSLParameters are always `nonNull`? } @Override + public void close() { // nothing to do } }
codereview_java_data_7169
parsed = new ExpandMacros(compiledMod, files, def.kompileOptions, false).expand(parsed); } if (options.kore) { - ModuleToKORE converter = new ModuleToKORE(compiledMod, files, null); parsed = new AddSortInjections(compiledMod).addInjections(parsed, sort); converter.convert(parsed); System.out.println(converter.toString()); why was this done? parsed = new ExpandMacros(compiledMod, files, def.kompileOptions, false).expand(parsed); } if (options.kore) { + ModuleToKORE converter = new ModuleToKORE(compiledMod, files, def.topCellInitializer); parsed = new AddSortInjections(compiledMod).addInjections(parsed, sort); converter.convert(parsed); System.out.println(converter.toString());
codereview_java_data_7175
} @Override - public void setDataSource(String streamUrl, String username, String password) { - try { - setDataSource(streamUrl); - } catch (IllegalArgumentException e) { - Log.e(TAG, e.toString()); - } catch (IllegalStateException e) { - Log.e(TAG, e.toString()); - } catch (IOException e) { - Log.e(TAG, e.toString()); - } } } That looks like it could get the media player into an inconsistent state where AntennaPod thinks it is playing but it actually crashed. I think it would be better to pass the exceptions to the caller. } @Override + public void setDataSource(String streamUrl, String username, String password) throws IOException { + setDataSource(streamUrl); } }
codereview_java_data_7194
}); - @Override - public void onAttach(Context context) { - super.onAttach(context); - } - @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_browse_image, container, false); ButterKnife.bind(this, rootView); categoryName = getArguments().getString("categoryName"); isParentCategory = getArguments().getBoolean("isParentCategory"); Should not override this method }); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_browse_image, container, false); + boolean currentThemeIsDark = PreferenceManager.getDefaultSharedPreferences(getContext()).getBoolean("theme", false); ButterKnife.bind(this, rootView); categoryName = getArguments().getString("categoryName"); isParentCategory = getArguments().getBoolean("isParentCategory");
codereview_java_data_7195
@Parameter(names={"--port", "-p"}, description="The port to start the server on.") public int port = 2113; - @Parameter(names={"--socket"}, description="The socket to start the server on.") public String socket = null; } this should say something like "The directory to put the unix domain socket in" @Parameter(names={"--port", "-p"}, description="The port to start the server on.") public int port = 2113; + @Parameter(names={"--socket"}, description="The directory to put the unix domain socket in.") public String socket = null; }
codereview_java_data_7196
ts.exec("createtable " + tableName + " -sf " + splitsFile, true); Collection<Text> createdSplits = client.tableOperations().listSplits(tableName); assertEquals(expectedSplits, new TreeSet<>(createdSplits)); } finally { - if (Objects.nonNull(splitsFile)) { Files.delete(Paths.get(splitsFile)); } } `Objects.nonNull` exists for use as a lambda when a Predicate is required (`stream.filter(Objects::nonNull)`, for example). For plain old if statements, it's much more clear to just write: ```suggestion if (splitsFile != null) { ``` However, there's no reason for it to ever be null or for us to check for it being null. We can just assign it to `System.getProperty("user.dir") + "/target/splitFile";` in the first place. There's no reason that needs to be done inside the try block. ts.exec("createtable " + tableName + " -sf " + splitsFile, true); Collection<Text> createdSplits = client.tableOperations().listSplits(tableName); assertEquals(expectedSplits, new TreeSet<>(createdSplits)); + ts.exec("deletetable -f " + tableName); } finally { + if (splitsFile != null) { Files.delete(Paths.get(splitsFile)); } }
codereview_java_data_7197
/* - * Copyright 2004-2020 H2 Group. Multiple-Licensed under the MPL 2.0, and the - * EPL 1.0 (https://h2database.com/html/license.html). Initial Developer: H2 - * Group */ package org.h2.command.dml; Please, remove this change. /* + * Copyright 2004-2020 H2 Group. Multiple-Licensed under the MPL 2.0, + * and the EPL 1.0 (https://h2database.com/html/license.html). + * Initial Developer: H2 Group */ package org.h2.command.dml;
codereview_java_data_7203
return false; } - private Map<String, Object> createAclAccessConfigMap(Map<String, Object> existedAccoutMap, PlainAccessConfig plainAccessConfig) { Map<String, Object> newAccountsMap = null; - if (existedAccoutMap == null) { newAccountsMap = new LinkedHashMap<String, Object>(); } else { - newAccountsMap = existedAccoutMap; } if (StringUtils.isEmpty(plainAccessConfig.getAccessKey()) || accout -> account return false; } + private Map<String, Object> createAclAccessConfigMap(Map<String, Object> existedAccountMap, PlainAccessConfig plainAccessConfig) { Map<String, Object> newAccountsMap = null; + if (existedAccountMap == null) { newAccountsMap = new LinkedHashMap<String, Object>(); } else { + newAccountsMap = existedAccountMap; } if (StringUtils.isEmpty(plainAccessConfig.getAccessKey()) ||
codereview_java_data_7208
private static final String PREF_SHOW_DOWNLOAD_REPORT = "prefShowDownloadReport"; public static final String PREF_BACK_BUTTON_BEHAVIOR = "prefBackButtonBehavior"; private static final String PREF_BACK_BUTTON_GO_TO_PAGE = "prefBackButtonGoToPage"; - public static final String PREF_QUEUE_SORT_ORDER = "prefQueueSortOrder"; // Queue private static final String PREF_QUEUE_ADD_TO_FRONT = "prefQueueAddToFront"; // Playback public static final String PREF_PAUSE_ON_HEADSET_DISCONNECT = "prefPauseOnHeadsetDisconnect"; In my opinion, it would be better to have two separate settings. One that stores if sorting is enabled and one that stores the order. That allows to toggle automatic sort without having to re-select the order. private static final String PREF_SHOW_DOWNLOAD_REPORT = "prefShowDownloadReport"; public static final String PREF_BACK_BUTTON_BEHAVIOR = "prefBackButtonBehavior"; private static final String PREF_BACK_BUTTON_GO_TO_PAGE = "prefBackButtonGoToPage"; // Queue private static final String PREF_QUEUE_ADD_TO_FRONT = "prefQueueAddToFront"; + public static final String PREF_QUEUE_KEEP_SORTED = "prefQueueKeepSorted"; + public static final String PREF_QUEUE_KEEP_SORTED_ORDER = "prefQueueKeepSortedOrder"; // Playback public static final String PREF_PAUSE_ON_HEADSET_DISCONNECT = "prefPauseOnHeadsetDisconnect";
codereview_java_data_7212
if (ruleSetElement.hasAttribute("name")) { ruleSetBuilder.withName(ruleSetElement.getAttribute("name")); } NodeList nodeList = ruleSetElement.getChildNodes(); If there was concern about breaking current usages, perhaps use a default here and log a warning about plans for making it strictly required in the future. I find this strategy quite useful/practical for helping me maintain Gradle scripts/plugins, they're pretty good about warning about deprecated features and when they'll be dropped. if (ruleSetElement.hasAttribute("name")) { ruleSetBuilder.withName(ruleSetElement.getAttribute("name")); + } else { + LOG.warning("RuleSet name is missing. Future versions of PMD will require it."); + ruleSetBuilder.withName("Missing RuleSet Name"); } NodeList nodeList = ruleSetElement.getChildNodes();
codereview_java_data_7213
} else { Log.d(TAG, "Activity was started with url " + feedUrl); setLoadingLayout(); - //Remove subscribeonandroid.com from feed URL in order to subscribe to the actual feed URL - if(feedUrl.contains("subscribeonandroid.com")){ - feedUrl = feedUrl.replaceFirst("((www.)?(subscribeonandroid.com/))",""); } if (savedInstanceState == null) { startFeedDownload(feedUrl, null, null); Please use the Google java code style. Basically, add more space characters like in the statements below. Next to method arguments and curly braces. This is currently not checked on CI because it is too inconsistent in the code base but I would prefer new code to be consistent. } else { Log.d(TAG, "Activity was started with url " + feedUrl); setLoadingLayout(); + // Remove subscribeonandroid.com from feed URL in order to subscribe to the actual feed URL + if (feedUrl.contains("subscribeonandroid.com")) { + feedUrl = feedUrl.replaceFirst("((www.)?(subscribeonandroid.com/))", ""); } if (savedInstanceState == null) { startFeedDownload(feedUrl, null, null);
codereview_java_data_7233
*/ public class AntlrTokenFilter extends BaseTokenFilter<AntlrToken> { - private boolean discardingHiddenTokens = false; - /** * Creates a new AntlrTokenFilter * @param tokenManager The token manager from which to retrieve tokens to be filtered I'm not sure we should be doing it this way... overriding `isLanguageSpecificDiscarding` for something that is **not** language-specific, but rather Antlr-specific someone customizing the filter would have to call super on both `analyzeToken` and `isLanguageSpecificDiscarding` to not break the behavior. I think we should have Antlr behave a lot more like JavaCC, in that the `AntlrTokenManager.getNextToken()` should never return a hidden / special token directly, but always wrapped in the next non-hidden token. */ public class AntlrTokenFilter extends BaseTokenFilter<AntlrToken> { /** * Creates a new AntlrTokenFilter * @param tokenManager The token manager from which to retrieve tokens to be filtered
codereview_java_data_7236
} static String usingOffsetPrefix(SecorConfig config) { - return config.getString("secor.offsets.prefix", "offset="); } public ParsedMessage parse(Message message) throws Exception { In secor, we keep the convention that the default value is specified in secor.common.properties, not in Java code. You don't need the 2nd argument for default } static String usingOffsetPrefix(SecorConfig config) { + return config.getString("secor.offsets.prefix"); } public ParsedMessage parse(Message message) throws Exception {
codereview_java_data_7249
private BlockRead cacheBlock(String _lookup, BlockCache cache, BlockReader _currBlock, String block) throws IOException { - // ACCUMULO-4716 - Define MAX_ARRAY_SIZE smaller than Integer.MAX_VALUE to prevent possible OutOfMemory - // error as described in stackoverflow post: https://stackoverflow.com/a/8381338. - int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; - if ((cache == null) || (_currBlock.getRawSize() > Math.min(cache.getMaxSize(), MAX_ARRAY_SIZE))) { return new BlockRead(_currBlock, _currBlock.getRawSize()); } else { Personally, I would make this a static constants because all caps usually implies that by convention. private BlockRead cacheBlock(String _lookup, BlockCache cache, BlockReader _currBlock, String block) throws IOException { if ((cache == null) || (_currBlock.getRawSize() > Math.min(cache.getMaxSize(), MAX_ARRAY_SIZE))) { return new BlockRead(_currBlock, _currBlock.getRawSize()); } else {
codereview_java_data_7250
SelectRowCount.response(service); break; case ServerParseSelect.MAX_ALLOWED_PACKET: - SelectMaxAllowedPacket.response(service); break; default: service.execute(stmt, ServerParse.SELECT); whether to reuse SelectMaxAllowedPacket on the management side SelectRowCount.response(service); break; case ServerParseSelect.MAX_ALLOWED_PACKET: + SelectMaxAllowedPacket.execute(service); break; default: service.execute(stmt, ServerParse.SELECT);
codereview_java_data_7252
" </style>" + "</head><body><p>" + webViewData + "</p></body></html>"; webViewData = webViewData.replace("\n", "<br/>"); - } else { - depth = 0; } webViewData = String.format(webViewData, colorString); subscriber.onSuccess(webViewData); On Android 8 (emulated), this still does not work. When pressing the contributors, you have to press back twice. After the first press, the webview does not load the main about page again (does nothing). If you use the actual url (`"file:///android_asset/" + webViewData.toString()`) instead of `about:blank` as the history parameter of `loadDataWithBaseURL`, you can remove the depth variable (I think thus is the most elegant solution). " </style>" + "</head><body><p>" + webViewData + "</p></body></html>"; webViewData = webViewData.replace("\n", "<br/>"); } webViewData = String.format(webViewData, colorString); subscriber.onSuccess(webViewData);
codereview_java_data_7257
// 1) At least 3 characters // 2) 1st must be a Hex number or a : (colon) // 3) Must contain at least 2 colons (:) - if (s.length() < 3 || !(isHexCharacter(firstChar) || firstChar == ':') || s.indexOf(':') < 0 || StringUtils.countMatches(s, ':') < 2) { return false; } can't be remove `s.indexOf(':') < 0`? this seems to be more restrictive // 1) At least 3 characters // 2) 1st must be a Hex number or a : (colon) // 3) Must contain at least 2 colons (:) + if (s.length() < 3 || !(isHexCharacter(firstChar) || firstChar == ':') || StringUtils.countMatches(s, ':') < 2) { return false; }
codereview_java_data_7259
String[] entries = new String[speeds.length + 1]; entries[0] = getString(R.string.feed_auto_download_global); - for (int i = 0; i < speeds.length; i++) { - values[i + 1] = speeds[i]; - entries[i + 1] = speeds[i]; - } feedPlaybackSpeedPreference.setEntryValues(values); feedPlaybackSpeedPreference.setEntries(entries); Might be easier to understand and more efficient if you use the system provided arraycopy function String[] entries = new String[speeds.length + 1]; entries[0] = getString(R.string.feed_auto_download_global); + System.arraycopy(speeds, 0, values, 1, speeds.length); + System.arraycopy(speeds, 0, entries, 1, speeds.length); feedPlaybackSpeedPreference.setEntryValues(values); feedPlaybackSpeedPreference.setEntries(entries);
codereview_java_data_7260
LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (UserPreferences.getFeedFilter() != UserPreferences.FEED_FILTER_NONE) { convertView = inflater.inflate(R.layout.nav_section_filter_divider, parent, false); convertView.setEnabled(true); - convertView.setOnClickListener((l) -> FeedFilterDialog.showDialog(context)); } else { convertView = inflater.inflate(R.layout.nav_section_item, parent, false); convertView.setEnabled(false); Could you please move click handling to `NavDrawerFragment.onItemClick`? All other items of the sidebar are handled in that file. It's also a good practice to keep displaying (adapter) and behavior (click listener) separated. I must admit that this is not always the case in the code base but in this case, it should be pretty easy to do. LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + View convertView; if (UserPreferences.getFeedFilter() != UserPreferences.FEED_FILTER_NONE) { convertView = inflater.inflate(R.layout.nav_section_filter_divider, parent, false); convertView.setEnabled(true); } else { convertView = inflater.inflate(R.layout.nav_section_item, parent, false); convertView.setEnabled(false);
codereview_java_data_7261
return ruleUnits; } - public void addQueryInRuleUnit(Class<?> ruleUnitType, QueryDescr query) { addRuleUnit(ruleUnitType); queriesByRuleUnit.computeIfAbsent( ruleUnitType, k -> new ArrayList<>() ).add(query); } - public List<QueryDescr> getQueriesInRuleUnit(Class<?> ruleUnitType) { return queriesByRuleUnit.getOrDefault( ruleUnitType, Collections.emptyList() ); } and these could be methods for that class return ruleUnits; } + public void addQueryInRuleUnit(Class<?> ruleUnitType, QueryModel query) { addRuleUnit(ruleUnitType); queriesByRuleUnit.computeIfAbsent( ruleUnitType, k -> new ArrayList<>() ).add(query); } + public List<QueryModel> getQueriesInRuleUnit(Class<?> ruleUnitType) { return queriesByRuleUnit.getOrDefault( ruleUnitType, Collections.emptyList() ); }
codereview_java_data_7263
if (maybe != null) result.close(); } - @SuppressWarnings("EmptyCatch") ActiveMQSpanConsumer doInit() { final ActiveMQConnection connection; try { This is fine too though I think `// Ignore` in the catch block is fine too and probably what this check is intending, just making sure you didn't accidentally forget if (maybe != null) result.close(); } ActiveMQSpanConsumer doInit() { final ActiveMQConnection connection; try {
codereview_java_data_7282
private static class Bin<T> { private final long targetWeight; - private final int itemsPerBin; private final List<T> items = Lists.newArrayList(); private long binWeight = 0L; - Bin(long targetWeight, int itemsPerBin) { this.targetWeight = targetWeight; - this.itemsPerBin = itemsPerBin; } List<T> items() { I think there is a slight issue with this implementation and how it interacts with lookback. Consider we have a lookback of 3 a max number of items per bin of 2 and a max value of bin of 10 ``` // Add Item (6) [ 8 ], [3, 4], [4, 3] // Neither of our completed bins [3, 4], and [4,3] will be removed regardless of whether removeLargest is set I think to properly do this we need to also finish off any bins which have reached their max item size ``` private static class Bin<T> { private final long targetWeight; + private final int binItemsSize; private final List<T> items = Lists.newArrayList(); private long binWeight = 0L; + Bin(long targetWeight, int binItemsSize) { this.targetWeight = targetWeight; + this.binItemsSize = binItemsSize; } List<T> items() {
codereview_java_data_7284
} private void setLicenseSummary(String license) { - licenseSummaryView.setHtmlText(getString(R.string.share_license_summary, getString(Utils.licenseNameFor(license)))); } @Override Upload crashes due to these changes. It seems to me like these changes are related with another PR that you have submitted #1086 . To remove this confusion it is always better to work on separate branches instead of master, and focusing only one task at a time. } private void setLicenseSummary(String license) { + licenseSummaryView.setText(getString(R.string.share_license_summary, getString(Utils.licenseNameFor(license)))); } @Override
codereview_java_data_7286
private static TransferStatusUpdater transferStatusUpdater; /** - * Prefix for temporary File created when client uploads an `InputStream`. */ static final String TEMP_FILE_PREFIX = "aws-s3-d861b25a-1edf-11eb-adc1-0242ac120002"; ```suggestion /** * Prefix for temporary File created when client uploads an InputStream. When the * upload completes, the File is deleted, if it was created by the library, but not if it was * provided by the client. To ensure we don't delete any File objects provided by the client, * a random UUID is included in the prefix. */ ``` private static TransferStatusUpdater transferStatusUpdater; /** + * Prefix for temporary File created when client uploads an InputStream. When the + * upload completes, the File is deleted, if it was created by the library, but not if it was + * provided by the client. To ensure we don't delete any File objects provided by the client, + * a random UUID is included in the prefix. */ static final String TEMP_FILE_PREFIX = "aws-s3-d861b25a-1edf-11eb-adc1-0242ac120002";
codereview_java_data_7295
if (length <= back.length()) { return this; } - final StringBuilder sb = new StringBuilder(back); - sb.append(padding(element, length - back.length())); return new CharSeq(sb.toString()); } let's change signature to ``` java private static void padding(StringBuilder sb, Character element, int limit) ``` to avoid creating new StringBuilder instance if (length <= back.length()) { return this; } + final StringBuilder sb = new StringBuilder(back).append(padding(element, length - back.length())); return new CharSeq(sb.toString()); }
codereview_java_data_7309
* A snack bar which has an action button which on click dismisses the snackbar and invokes the listener passed * @param view * @param messageResourceId - * @param retryButtonResourceId * @param onClickListener */ public static void showDismissibleSnackBar(View view, int messageResourceId, - int retryButtonResourceId, View.OnClickListener onClickListener) { if (view.getContext() == null) { return; } it would be better if we could keep the variable name generic. the button text could be anything * A snack bar which has an action button which on click dismisses the snackbar and invokes the listener passed * @param view * @param messageResourceId + * @param actionButtonResourceId * @param onClickListener */ public static void showDismissibleSnackBar(View view, int messageResourceId, + int actionButtonResourceId, View.OnClickListener onClickListener) { if (view.getContext() == null) { return; }
codereview_java_data_7324
" void f(Optional<String> in, String out) {", " assertThat(in).hasValue(out);", " assertThat(in).hasValue(out);", " assertThat(in).hasValue(out);", " }", "}"); } looks like these expect a trailing blank line from the removed line. " void f(Optional<String> in, String out) {", " assertThat(in).hasValue(out);", " assertThat(in).hasValue(out);", + " }", + " void g(Optional<String> in, String out) {", " assertThat(in).hasValue(out);", + " ", " }", "}"); }
codereview_java_data_7330
entry("property1", "sampleValueForProperty1"), entry("property2", "sampleValueForProperty2") ) - .doesNotContain(entry("property3", null)); } @Test This is not exactly the same assertion as before. This will pass if there is a variable named `property3` with some other value. I think that we should use `containsOnly` instead. This way we are validating all the properties which are in the process. Let's do this for all the places where we assert the variables in the `CamelVariableTransferTest` entry("property1", "sampleValueForProperty1"), entry("property2", "sampleValueForProperty2") ) + .doesNotContainKey("property3"); } @Test
codereview_java_data_7335
lastSize[0] = blob.length; metricsJournal.add(entry(System.currentTimeMillis(), blob)); logFine(logger, "Collected %,d metrics, %,d bytes", renderer.getCount(), blob.length); - }, config.getCollectionIntervalSeconds(), config.getCollectionIntervalSeconds(), TimeUnit.SECONDS); } } Initial delay can remain 1000 ms i think lastSize[0] = blob.length; metricsJournal.add(entry(System.currentTimeMillis(), blob)); logFine(logger, "Collected %,d metrics, %,d bytes", renderer.getCount(), blob.length); + }, 1, config.getCollectionIntervalSeconds(), TimeUnit.SECONDS); } }
codereview_java_data_7340
public boolean isValid() { return rowId >= 0 && uniqueId >= 0; } - - @Override - public boolean equals(Object object) { - if (!(object instanceof PartId)){ - return false; - } - - PartId other = (PartId) object; - return rowId == other.rowId && uniqueId == other.uniqueId; - } } } please do whatever you need to do without adding this method public boolean isValid() { return rowId >= 0 && uniqueId >= 0; } } }
codereview_java_data_7345
} @Test void testSelectNull() { String query = "SELECT NULL AS DUMMY FROM \"product\""; - final String expected = "SELECT CAST(NULL AS NULL) AS \"DUMMY\"\n" + "FROM \"foodmart\".\"product\""; sql(query).ok(expected); } Can we promote the `CAST(NULL AS NULL)` to just `NULL` ? } @Test void testSelectNull() { + String query = "SELECT NULL FROM \"product\""; + final String expected = "SELECT NULL\n" + + "FROM \"foodmart\".\"product\""; + sql(query).ok(expected); + } + + @Test void testSelectNullWithAlias() { String query = "SELECT NULL AS DUMMY FROM \"product\""; + final String expected = "SELECT NULL AS \"DUMMY\"\n" + "FROM \"foodmart\".\"product\""; sql(query).ok(expected); }
codereview_java_data_7348
import org.apache.iceberg.actions.Actions; import org.apache.iceberg.actions.RemoveOrphanFilesAction; import org.apache.iceberg.spark.procedures.SparkProcedures.ProcedureBuilder; import org.apache.spark.sql.catalyst.InternalRow; import org.apache.spark.sql.catalyst.util.DateTimeUtils; import org.apache.spark.sql.connector.catalog.TableCatalog; I usually think a ternary expression is easier to read in situations like this, rather than trying to think about negating `isNullAt`: ```java boolean dryRun = args.isNullAt(4) ? false : args.getBoolean(4); ``` import org.apache.iceberg.actions.Actions; import org.apache.iceberg.actions.RemoveOrphanFilesAction; import org.apache.iceberg.spark.procedures.SparkProcedures.ProcedureBuilder; +import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.catalyst.InternalRow; import org.apache.spark.sql.catalyst.util.DateTimeUtils; import org.apache.spark.sql.connector.catalog.TableCatalog;
codereview_java_data_7350
try { asyncHttpClient .post(url, Header.newInstance().addParam(Constants.NACOS_SERVER_HEADER, VersionUtils.version), - Query.EMPTY, getSelf(), reference.getType(), new AbstractCallback<String>() { @Override public void onReceive(RestResult<String> result) { if (result.getCode() == HttpStatus.NOT_IMPLEMENTED.value() Why not use interface rather than Abstract class? try { asyncHttpClient .post(url, Header.newInstance().addParam(Constants.NACOS_SERVER_HEADER, VersionUtils.version), + Query.EMPTY, getSelf(), reference.getType(), new Callback<String>() { @Override public void onReceive(RestResult<String> result) { if (result.getCode() == HttpStatus.NOT_IMPLEMENTED.value()
codereview_java_data_7358
deregisterVersionUsage(txCounter); } } }; } finally { deregisterVersionUsage(txCounter); How about `read(byte[])`, `read()`, `skip()`? They can be used through JDBC, even more, JDBC layer can use `skip()` by itself. deregisterVersionUsage(txCounter); } } + + @Override + public int read() throws IOException { + MVStore.TxCounter txCounter = initialize(); + try { + return super.read(); + } finally { + deregisterVersionUsage(txCounter); + } + } }; } finally { deregisterVersionUsage(txCounter);
codereview_java_data_7362
"ibft_getPendingVotes", emptyList(), web3jService, ProposalsResponse.class); } - public Request<?, SignersBlockResponse> getValidators(final String blockNumber) { return new Request<>( "ibft_getValidatorsByBlockNumber", singletonList(blockNumber), probably should be called getProposals given the name of the functions below. "ibft_getPendingVotes", emptyList(), web3jService, ProposalsResponse.class); } + public Request<?, SignersBlockResponse> validatorsAtBlock(final String blockNumber) { return new Request<>( "ibft_getValidatorsByBlockNumber", singletonList(blockNumber),
codereview_java_data_7364
} private void displayYouWontSeeNearbyMessage() { - ViewUtil.showLongToast(getActivity(), "You wont see narby place since you didn't gave permission"); } Please make this a string resource and change it to "Unable to display nearest place that needs pictures without location permissions". } private void displayYouWontSeeNearbyMessage() { + ViewUtil.showLongToast(getActivity(), getResources().getString(R.string.unable_to_display_nearest_place)); }
codereview_java_data_7380
input.endObject(); - return new NodeSummary(nodeId, uri, up, maxSessionCount, stereotypes, used, null); } private static Map<Capabilities, Integer> readCapabilityCounts(JsonInput input) { Pass in an empty set rather than `null` and you'll avoid null pointer exceptions later input.endObject(); + return new NodeSummary(nodeId, uri, up, maxSessionCount, stereotypes, used, activeSessions); } private static Map<Capabilities, Integer> readCapabilityCounts(JsonInput input) {
codereview_java_data_7381
PUT, REMOVE } - class It<K, V> extends AbstractIterator<LeafNode<K, V>> { - private final static int MAX_LEVELS = Integer.SIZE / AbstractNode.SIZE + 1; private final int total; private final Object[] nodes = new Object[MAX_LEVELS]; Please name it `LeafNodeIterator` PUT, REMOVE } + class LeafNodeIterator<K, V> extends AbstractIterator<LeafNode<K, V>> { + // buckets levels + leaf level = (Integer.SIZE / AbstractNode.SIZE + 1) + 1 + private final static int MAX_LEVELS = Integer.SIZE / AbstractNode.SIZE + 2; private final int total; private final Object[] nodes = new Object[MAX_LEVELS];
codereview_java_data_7382
txtvSeek.setText(Converter.getDurationStringLong(position)); } } else if (controller.getDuration() != controller.getMedia().getDuration()) { updateUi(controller.getMedia()); } } Doesn't this mean that it will update the UI every single second when the progress is updated? txtvSeek.setText(Converter.getDurationStringLong(position)); } } else if (controller.getDuration() != controller.getMedia().getDuration()) { + controller.getMedia().setDuration(controller.getDuration()); updateUi(controller.getMedia()); } }
codereview_java_data_7395
import org.openqa.selenium.grid.data.DistributorStatus; import org.openqa.selenium.grid.distributor.Distributor; -import org.openqa.selenium.grid.sessionmap.SessionMap; import org.openqa.selenium.internal.Require; import java.net.URI; I think that this is an unused import import org.openqa.selenium.grid.data.DistributorStatus; import org.openqa.selenium.grid.distributor.Distributor; import org.openqa.selenium.internal.Require; import java.net.URI;
codereview_java_data_7396
// since the first call to binRanges clipped the ranges to within a tablet, we should not get only // bin to the set of failed tablets - if (!locator.isValid()) - locator = new TimeoutTabletLocator(TabletLocator.getLocator(instance, new Text(table)), timeout); binRanges(locator, allRanges, binnedRanges); doLookups(binnedRanges, receiver, columns); Since TabletServerBatchReaderIterator#lookup is synchronized, the reassignment is thread-safe for other accesses that respect the instance's lock. This reassignment, in processFailures, only ever occurs though a branch from a QueryTask, which doesn't do the reassignment in a synchronized block (it does use a semaphore inside of the QueryTask, but that's separate from the TSBI instance lock). So, where I'm going with this: is it safe to do these re-assignments outside of a synchronized block? It's implied to me that these updates can happen in different threads, since the QueryTasks are executed via an ExecutorService. // since the first call to binRanges clipped the ranges to within a tablet, we should not get only // bin to the set of failed tablets binRanges(locator, allRanges, binnedRanges); doLookups(binnedRanges, receiver, columns);
codereview_java_data_7397
package net.sourceforge.pmd.renderers; import java.io.IOException; import java.io.Writer; import java.nio.file.Path; any reason to not use `File.separator` directly? package net.sourceforge.pmd.renderers; +import java.io.File; import java.io.IOException; import java.io.Writer; import java.nio.file.Path;
codereview_java_data_7400
try { // role should not be created if fails to process tags.. - Role dbRole = zmsTest.getRole(mockDomRsrcCtx, domainName, roleName, false, false, false); fail(); } catch(ResourceException ex) { assertEquals(ex.getCode(), ResourceException.NOT_FOUND); No need to have the "Role dbRole =" part since we expect the call throw an exception. this is usually tagged as unused variable in code analyzers. try { // role should not be created if fails to process tags.. + zmsTest.getRole(mockDomRsrcCtx, domainName, roleName, false, false, false); fail(); } catch(ResourceException ex) { assertEquals(ex.getCode(), ResourceException.NOT_FOUND);
codereview_java_data_7401
@Bean @Qualifier("zipkinElasticsearchHttp") @Conditional(isBasicAuthRequired.class) - Interceptor basicAuthInterceptor(ZipkinElasticsearchHttpStorageProperties es) {return new BasicAuthInterceptor(es);} @Bean @ConditionalOnMissingBean revert unnecessary reformatting pls @Bean @Qualifier("zipkinElasticsearchHttp") @Conditional(isBasicAuthRequired.class) + Interceptor basicAuthInterceptor(ZipkinElasticsearchHttpStorageProperties es) { + return new BasicAuthInterceptor(es); + } @Bean @ConditionalOnMissingBean
codereview_java_data_7404
log.trace("\'none - no action\' or invalid value provided: {}", action); } - long actionComplete = System.currentTimeMillis(); - log.info("gc post action {} completed in {} seconds", action, - String.format("%.2f", ((actionComplete - actionStart) / 1000.0))); } catch (Exception e) { log.warn("{}", e.getMessage(), e); Best to use nanos when computing time durations within a process, since it's not dependent on system clock changes. log.trace("\'none - no action\' or invalid value provided: {}", action); } + final long actionComplete = System.nanoTime(); + log.info("gc post action {} completed in {} seconds", action, String.format("%.2f", + (TimeUnit.NANOSECONDS.toMillis(actionComplete - actionStart) / 1000.0))); } catch (Exception e) { log.warn("{}", e.getMessage(), e);
codereview_java_data_7414
@Override public Comparator<? super T> getComparator() { - return null; } } return new SpliteratorProxy(original.spliterator()); The super impl Spliterator.getComparator() throws an IllegalStateException by default. Is it really necessary to return null? If null is used somewhere it will throw a NPE, which is roughly the same as throwing an IllegalStateException. I'm just curious - I'm sure there is a reason! @Override public Comparator<? super T> getComparator() { + if (hasCharacteristics(Spliterator.SORTED)) { + return null; + } + throw new IllegalStateException(); } } return new SpliteratorProxy(original.spliterator());
codereview_java_data_7416
} private static TomlParseResult readToml(final String filepath) throws Exception { - TomlParseResult nodePermissioningToml; try { - nodePermissioningToml = TomlConfigFileParser.loadConfigurationFromFile(filepath); } catch (Exception e) { throw new Exception( "Unable to read permissioning TOML config file : " + filepath + " " + e.getMessage()); } - return nodePermissioningToml; } } I think this method is used for both node and account permissioning - can take 'node' out of variable name } private static TomlParseResult readToml(final String filepath) throws Exception { + TomlParseResult toml; try { + toml = TomlConfigFileParser.loadConfigurationFromFile(filepath); } catch (Exception e) { throw new Exception( "Unable to read permissioning TOML config file : " + filepath + " " + e.getMessage()); } + return toml; } }
codereview_java_data_7433
import java.util.concurrent.CompletableFuture; import com.google.common.annotations.VisibleForTesting; import org.apache.logging.log4j.Logger; public class DetermineCommonAncestorTask<C> extends AbstractEthTask<BlockHeader> { - private static final Logger LOG = getLogger(); private final EthContext ethContext; private final ProtocolSchedule<C> protocolSchedule; private final ProtocolContext<C> protocolContext; in some of these classes I'd put `LogManager.getLogger()`, in the future would it be better if I just out `getLogger()`? import java.util.concurrent.CompletableFuture; import com.google.common.annotations.VisibleForTesting; +import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class DetermineCommonAncestorTask<C> extends AbstractEthTask<BlockHeader> { + private static final Logger LOG = LogManager.getLogger(); private final EthContext ethContext; private final ProtocolSchedule<C> protocolSchedule; private final ProtocolContext<C> protocolContext;
codereview_java_data_7434
return log; } - if (checkApacheCommonsLoggingExists()) { log = new ApacheCommonsLogging(logTag); - } else if (checkAndroidLoggingMocked()) { - log = new AndroidLog(logTag); } else { - log = new ConsoleLog(logTag); } logMap.put(logTag, log); return log; I would just get of any semblance of support for Apache. return log; } + if (Environment.isJUnitTest()) { + log = new ConsoleLog(logTag); + } else if (checkApacheCommonsLoggingExists()) { log = new ApacheCommonsLogging(logTag); } else { + log = new AndroidLog(logTag); } logMap.put(logTag, log); return log;
codereview_java_data_7436
public static final String TYPE_RSS2 = "rss"; public static final String TYPE_ATOM1 = "atom"; public static final String PREFIX_LOCAL_FOLDER = "antennapod_local:"; - public static final String SUPPORT_INTERNAL_SPLIT = "\n"; - public static final String SUPPORT_INTERNAL_EQUAL = "\t"; public static final String TAG = "Feed.java"; /* title as defined by the feed */ How about using less common characters here, like the ASCII record separator (`\u001e`) and unit separator (`\u001f`)? Those can then be safely removed from the input string, so feed creators cannot cause issues in AntennaPod. public static final String TYPE_RSS2 = "rss"; public static final String TYPE_ATOM1 = "atom"; public static final String PREFIX_LOCAL_FOLDER = "antennapod_local:"; public static final String TAG = "Feed.java"; /* title as defined by the feed */
codereview_java_data_7447
* to determine whether the accumulator is now "empty" (i.e., equal to a * fresh instance), which signals that the current window contains no more * items with the associated grouping key and the entry must be removed - * from the results. I.e.: * <pre> * acc = create(); * combine(acc, x); ```suggestion * from the results. For example: ``` * to determine whether the accumulator is now "empty" (i.e., equal to a * fresh instance), which signals that the current window contains no more * items with the associated grouping key and the entry must be removed + * from the results. For example: * <pre> * acc = create(); * combine(acc, x);
codereview_java_data_7453
*/ public Schema findSchema(String schemaName) { if (schemaName == null) { - throw DbException.get(ErrorCode.SCHEMA_NOT_FOUND_1, schemaName); } Schema schema = schemas.get(schemaName); if (schema == infoSchema) { This method returns `null` for unknown schemes, why an exception is required for a `null` name? */ public Schema findSchema(String schemaName) { if (schemaName == null) { + return null; } Schema schema = schemas.get(schemaName); if (schema == infoSchema) {
codereview_java_data_7454
/** - * Iterator that walks through ModuleDefinitions in deployment order, that is, from downstream (sink, if present) - * to upstream (source) module. * Also prevents mutation of its backing data structure. */ public class DeploymentOrderIterator implements Iterator<ModuleDefinition> { should this be static?, taking modules as a constructor arg /** + * Iterator that traverses ModuleDefinitions in deployment order, that is, from downstream (sink, if present) + * to upstream (source, if present) module. * Also prevents mutation of its backing data structure. */ public class DeploymentOrderIterator implements Iterator<ModuleDefinition> {
codereview_java_data_7459
} /** - * Shortcut for {@code filterTry(predicate::test, throwableSupplier)}, see {@link #filterTry(CheckedPredicate)}}. * * @param predicate A predicate * @return a {@code Try} instance should rather be ``` Java Objects.requireNonNull(throwableSupplier, "throwableSupplier is null"); ``` } /** + * Shortcut for {@code filterTry(predicate::test, throwableSupplier)}, see + * {@link #filterTry(CheckedPredicate, Supplier)}}. * * @param predicate A predicate * @return a {@code Try} instance
codereview_java_data_7463
*/ @Nonnull public SinkBuilder<W, T> preferredLocalParallelism(int preferredLocalParallelism) { - checkPositive(preferredLocalParallelism, "Preferred local parallelism should be a positive number"); this.preferredLocalParallelism = preferredLocalParallelism; return this; } You should use `Vertex.checkLocalParallelism` here */ @Nonnull public SinkBuilder<W, T> preferredLocalParallelism(int preferredLocalParallelism) { + Vertex.checkLocalParallelism(preferredLocalParallelism); this.preferredLocalParallelism = preferredLocalParallelism; return this; }
codereview_java_data_7472
/** * Position2Accessor and Position3Accessor here is an optimization. For a nested schema like: - * * root * |-- a: struct (nullable = false) * | |-- b: struct (nullable = false) * | | -- c: string (containsNull = false) - * * Then we will use Position3Accessor to access nested field 'c'. It can be accessed like this: * {@code row.get(p0, StructLike.class).get(p1, StructLike.class).get(p2, javaClass)}. * Commonly, Nested fields with depth=1 or 2 or 3 are the fields that will be accessed frequently, thank you very much for the update, sorry for the back and forth, just one last thing: the example block here needs to be in `<pre></pre>`, otherwise they will collapse. /** * Position2Accessor and Position3Accessor here is an optimization. For a nested schema like: + * <pre> * root * |-- a: struct (nullable = false) * | |-- b: struct (nullable = false) * | | -- c: string (containsNull = false) + * </pre> * Then we will use Position3Accessor to access nested field 'c'. It can be accessed like this: * {@code row.get(p0, StructLike.class).get(p1, StructLike.class).get(p2, javaClass)}. * Commonly, Nested fields with depth=1 or 2 or 3 are the fields that will be accessed frequently,
codereview_java_data_7484
public void beforeStory(Story story, boolean givenStory) { String name = bddRunContext.getRunningStory().getName(); - if (!configuration.dryRun() && !givenStory && !"BeforeStories".equals(name) && !"AfterStories".equals(name) - && (proxyEnabled || isProxyEnabledInStoryMeta())) { proxy.start(); } Does it make sense to refactor this complex condition to something like: `if (!configuration.dryRun() && !givenStory && notPrecodition(name) && proxyEnabled()) ` public void beforeStory(Story story, boolean givenStory) { String name = bddRunContext.getRunningStory().getName(); + if (!configuration.dryRun() && !givenStory && isNotSystemStory(name) && isProxyEnabled()) { proxy.start(); }
codereview_java_data_7485
import java.util.Properties; import java.util.concurrent.TimeUnit; -import static com.alibaba.nacos.test.naming.NamingBase.TEST_IP_4_DOM_1; -import static com.alibaba.nacos.test.naming.NamingBase.TEST_NEW_CLUSTER_4_DOM_1; -import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT; - /** * Created by wangtong.wt on 2018/6/20. * Merge into `import static com.alibaba.nacos.test.naming.NamingBase;` and make follow constants with `NamingBase.XXX` import java.util.Properties; import java.util.concurrent.TimeUnit; /** * Created by wangtong.wt on 2018/6/20. *
codereview_java_data_7486
* @return map that contains accessToken , null if acessToken is empty. */ protected Map<String, String> getSecurityHeaders() { - String accessToken = (String) this.securityProxy.getLoginIdentityContext().getParameter(Constants.ACCESS_TOKEN); - if (StringUtils.isBlank(accessToken)) { return null; } - Map<String, String> spasHeaders = new HashMap<String, String>(2); - spasHeaders.put(Constants.ACCESS_TOKEN, accessToken); return spasHeaders; } Why not use `getAccessToken` method? * @return map that contains accessToken , null if acessToken is empty. */ protected Map<String, String> getSecurityHeaders() { + Map<String, String> spasHeaders = this.securityProxy.getAccessToken(); + if (spasHeaders.isEmpty()) { return null; } return spasHeaders; }
codereview_java_data_7488
} } while (batch != null && batch.size() == 0); return batch == null ? Collections.emptyList() : batch; } Is it possible to consume all the threads in the pool while waiting for ThriftScanner to close? Like if I were to call close in a loop. } } while (batch != null && batch.size() == 0); + if (batch != null) { + reporter.readBatch(this); + } + return batch == null ? Collections.emptyList() : batch; }
codereview_java_data_7492
* Generate initial json for the root tablet metadata. */ public static byte[] getInitialJson(String dirName, String file) { - Preconditions.checkArgument(!dirName.contains("/"), "Invalid dir name %s", dirName); Mutation mutation = RootTable.EXTENT.getPrevRowUpdateMutation(); ServerColumnFamily.DIRECTORY_COLUMN.put(mutation, new Value(dirName.getBytes(UTF_8))); Is there a stricter check we can do? Like if it starts with, and contains only one, slash? * Generate initial json for the root tablet metadata. */ public static byte[] getInitialJson(String dirName, String file) { + ServerColumnFamily.validateDirCol(dirName); Mutation mutation = RootTable.EXTENT.getPrevRowUpdateMutation(); ServerColumnFamily.DIRECTORY_COLUMN.put(mutation, new Value(dirName.getBytes(UTF_8)));
codereview_java_data_7494
} catch (final NotAuthorizedException nae) { clearCachedTokens(); throw new CognitoNotAuthorizedException("User is not authenticated", nae); - } catch (final Exception e) { clearCachedTokens(); throw new CognitoInternalErrorException("Failed to authenticate user", e); } } What scenario are you hitting that requires the tokens to be cleared? } catch (final NotAuthorizedException nae) { clearCachedTokens(); throw new CognitoNotAuthorizedException("User is not authenticated", nae); + } catch (final UserNotFoundException unfe) { clearCachedTokens(); + throw new CognitoNotAuthorizedException("User does not exist", unfe); + }catch (final Exception e) { throw new CognitoInternalErrorException("Failed to authenticate user", e); } }
codereview_java_data_7503
protected TransactionPoolConfiguration transactionPoolConfiguration; protected BigInteger networkId; protected MiningParameters miningParameters; - protected MetricsSystem metricsSystem; protected PrivacyParameters privacyParameters; protected Path dataDirectory; protected Clock clock; Instead of a type `Function` field I think we should consider a special case `GasLimitCalculator` functional interface. It will make it more obvious what the type does. Here and the other places in the code we us it (the compiler errors should tell you where, one advantage of a strongly typed language). It will also give a home to the eth spec standard 'no more than 1/1024th per block` adjustment code. protected TransactionPoolConfiguration transactionPoolConfiguration; protected BigInteger networkId; protected MiningParameters miningParameters; + protected ObservableMetricsSystem metricsSystem; protected PrivacyParameters privacyParameters; protected Path dataDirectory; protected Clock clock;
codereview_java_data_7511
return WORKER_POOL; } - /** - * Return parallelism for "worker" thread-pool. - * In default, we submit 2 tasks per worker at a time. - * @return the parallelism of the worker pool. - */ - public static int getPoolParallelism() { - return WORKER_THREAD_POOL_SIZE * 2; - } - private static int getPoolSize(String systemProperty, int defaultSize) { String value = System.getProperty(systemProperty); if (value != null) { I am wondering if it is better to define a constant as ``` public static final int DEFAULT_WORKER_THREAD_POOL_PARALLELISM = WORKER_THREAD_POOL_SIZE * 2; ``` return WORKER_POOL; } private static int getPoolSize(String systemProperty, int defaultSize) { String value = System.getProperty(systemProperty); if (value != null) {
codereview_java_data_7512
JID userJid = new JID(user); if (XMPPServer.getInstance().isLocal(userJid)) { String username = userJid.getNode(); - synchronized (username.intern()) { groupMetaCache.remove(username); } } I'm not crazy about synchronizing on an interned string. Was the lack of a lock a problem before? JID userJid = new JID(user); if (XMPPServer.getInstance().isLocal(userJid)) { String username = userJid.getNode(); + synchronized ((getClass().getSimpleName() + username).intern()) { groupMetaCache.remove(username); } }
codereview_java_data_7517
if (intent.resolveActivity(packageManager)!= null) { startActivity(intent); - Toast.makeText(getContext(), R.string.set_location_mode_high_accuracy, Toast.LENGTH_LONG).show(); } else { Toast.makeText(getContext(), R.string.cannot_open_location_settings, Toast.LENGTH_LONG).show(); } Looks like you've forgot to update this after updating the strings file. ```suggestion Toast.makeText(getContext(), R.string.recommend_high_accuracy_mode, Toast.LENGTH_LONG).show(); ``` if (intent.resolveActivity(packageManager)!= null) { startActivity(intent); + Toast.makeText(getContext(), R.string.recommend_high_accuracy_mode, Toast.LENGTH_LONG).show(); } else { Toast.makeText(getContext(), R.string.cannot_open_location_settings, Toast.LENGTH_LONG).show(); }
codereview_java_data_7520
@SuppressWarnings("unchecked") static <T> Bucket<T> get(Type type, int numBuckets) { Preconditions.checkArgument(numBuckets > 0, - "The number of bucket must larger than zero,but is %s", numBuckets); switch (type.typeId()) { case DATE: nits: Missing a space after the comma number of bucket(s) @SuppressWarnings("unchecked") static <T> Bucket<T> get(Type type, int numBuckets) { Preconditions.checkArgument(numBuckets > 0, + "The number of bucket(s) must be larger than zero, but is %s", numBuckets); switch (type.typeId()) { case DATE:
codereview_java_data_7531
* for use it chooses a new tablet directory. */ public static TabletFiles updateTabletVolumes(AccumuloServerContext context, ZooLock zooLock, - VolumeManager vm, KeyExtent extent, TabletFiles tabletFiles, boolean replicate, - List<Pair<Path,Path>> replacements) throws IOException { log.trace("Using volume replacements: " + replacements); List<LogEntry> logsToRemove = new ArrayList<>(); Would it make more sense to keep the replacements assignment in this method, but short-circuit the method with a `if (replacements.isEmpty()) { return; }` line? It seems like this is a smaller change and would keep the logic all together that handles the updates, rather than place the special case of no replacements outside the method. * for use it chooses a new tablet directory. */ public static TabletFiles updateTabletVolumes(AccumuloServerContext context, ZooLock zooLock, + VolumeManager vm, KeyExtent extent, TabletFiles tabletFiles, boolean replicate) + throws IOException { + List<Pair<Path,Path>> replacements = ServerConstants.getVolumeReplacements(); + if (replacements.isEmpty()) + return tabletFiles; log.trace("Using volume replacements: " + replacements); List<LogEntry> logsToRemove = new ArrayList<>();
codereview_java_data_7549
// Node whitelist errors NODE_WHITELIST_NOT_SET(-32000, "Node whitelist has not been set"), - NODE_WHITELIST_DUPLICATED_ENTRY(-32000, "Request cannot contain duplicated node entries"), - NODE_WHITELIST_EXISTING_ENTRY(-32000, "Node whitelist cannot contain duplicated node entries"), NODE_WHITELIST_MISSING_ENTRY(-32000, "Node whitelist does not contain a specified node"), NODE_WHITELIST_INVALID_ENTRY(-32000, "Unable to add invalid node to the node whitelist"); cannot vs can't? match L54 or make it match this? // Node whitelist errors NODE_WHITELIST_NOT_SET(-32000, "Node whitelist has not been set"), + NODE_WHITELIST_DUPLICATED_ENTRY(-32000, "Request can't contain duplicated node entries"), + NODE_WHITELIST_EXISTING_ENTRY(-32000, "Node whitelist can't contain duplicated node entries"), NODE_WHITELIST_MISSING_ENTRY(-32000, "Node whitelist does not contain a specified node"), NODE_WHITELIST_INVALID_ENTRY(-32000, "Unable to add invalid node to the node whitelist");
codereview_java_data_7554
int port = getPort(); try { - if (isSecure()) { - return new URI("https", null, host, port, null, null, null); - } else { - return new URI("http", null, host, port, null, null, null); - } } catch (URISyntaxException e) { throw new ConfigException("Cannot determine external URI: " + e.getMessage()); } Consider: `return new URI(isSecure() ? "https" : "http", null, host, port, null, null, null)` to emphasise that the only thing that changes is the scheme. int port = getPort(); try { + return new URI(isSecure() ? "https" : "http", null, host, port, null, null, null); } catch (URISyntaxException e) { throw new ConfigException("Cannot determine external URI: " + e.getMessage()); }
codereview_java_data_7556
// Handle item selection switch (item.getItemId()) { case R.id.action_display_list: - if(!opened){ bottomSheetBehaviorForDetails.setState(BottomSheetBehavior.STATE_HIDDEN); bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); - opened=true; - }else{ bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); - opened=false; } return true; I would remove "opened" variable at all, since someone else may forgot to set it, and everything can be a mess. Instead you can use bottomSheetBehavior.getState(), to check if it is opened or not. // Handle item selection switch (item.getItemId()) { case R.id.action_display_list: + if(bottomSheetBehavior.getState()==BottomSheetBehavior.STATE_COLLAPSED || bottomSheetBehavior.getState()==BottomSheetBehavior.STATE_HIDDEN){ bottomSheetBehaviorForDetails.setState(BottomSheetBehavior.STATE_HIDDEN); bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); + }else if(bottomSheetBehavior.getState()==BottomSheetBehavior.STATE_EXPANDED){ bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } return true;
codereview_java_data_7569
@Deprecated public static void setConnectorInfo(JobConf job, String principal, AuthenticationToken token) throws AccumuloSecurityException { - if (token instanceof KerberosToken) { - log.info("Received KerberosToken, attempting to fetch DelegationToken"); - try { - Connector conn = Connector.builder().usingClientInfo(getClientInfo(job)) - .usingToken(principal, token).build(); - token = conn.securityOperations().getDelegationToken(new DelegationTokenConfig()); - } catch (Exception e) { - log.warn("Failed to automatically obtain DelegationToken, " - + "Mappers/Reducers will likely fail to communicate with Accumulo", e); - } - } // DelegationTokens can be passed securely from user to task without serializing insecurely in // the configuration if (token instanceof DelegationTokenImpl) { I don't think this behavior is needed. There's no reason to expect the keytab *won't* be on the worker nodes. If the user wants to use a delegation token, they can create one and pass it in. This auto-allocation of delegation tokens without user explicit acknowledgement is probably a bit dangerous anyway and may not be what users intend. If `getClientInfo` was added solely to support this feature, it is probably not needed. @Deprecated public static void setConnectorInfo(JobConf job, String principal, AuthenticationToken token) throws AccumuloSecurityException { // DelegationTokens can be passed securely from user to task without serializing insecurely in // the configuration if (token instanceof DelegationTokenImpl) {
codereview_java_data_7571
Map<String, Object> aclAccessConfigMap = AclUtils.getYamlDataObject(fileHome + File.separator + fileName, Map.class); if (aclAccessConfigMap == null || aclAccessConfigMap.isEmpty()) { - throw new AclException(String.format("%s file not found or empty", fileHome + File.separator + fileName)); } List<Map<String, Object>> accounts = (List<Map<String, Object>>) aclAccessConfigMap.get(AclConstants.CONFIG_ACCOUNTS); Map<String, Object> updateAccountMap = null; "the xxx file **is** not found or empty " seems better. Map<String, Object> aclAccessConfigMap = AclUtils.getYamlDataObject(fileHome + File.separator + fileName, Map.class); if (aclAccessConfigMap == null || aclAccessConfigMap.isEmpty()) { + throw new AclException(String.format("the %s file is not found or empty", fileHome + File.separator + fileName)); } List<Map<String, Object>> accounts = (List<Map<String, Object>>) aclAccessConfigMap.get(AclConstants.CONFIG_ACCOUNTS); Map<String, Object> updateAccountMap = null;
codereview_java_data_7575
*/ public boolean contains(TokenRange that) { // Empty ranges never contain any other range - if (this.isEmpty() || that.isEmpty()) return false; - return this.contains(that.start, true) - && this.contains(that.end, false); } /** This doesn't work if the other range has both ends inside but wraps around, for example `]4,8].contains(]7,5])` should be false. A straightforward way to implement `contains` is ```java this.intersects(that) && this.intersectWith(that).equals(that) ``` If we add it, we can inline and maybe simplify the code. */ public boolean contains(TokenRange that) { // Empty ranges never contain any other range + if (this.isEmpty() || that.isEmpty() || !this.intersects(that)) return false; + List<TokenRange> intersection = this.intersectWith(that); + return intersection.size() == 1 && intersection.get(0).equals(that); } /**
codereview_java_data_7576
private final NacosRestTemplate nacosRestTemplate; - private volatile LoginIdentityContext loginIdentityContext; - public HttpLoginProcessor(NacosRestTemplate nacosRestTemplate) { this.nacosRestTemplate = nacosRestTemplate; } @Override - public Boolean getResponse(Properties properties) { String contextPath = ContextPathUtil .normalizeContextPath(properties.getProperty(PropertyKeyConst.CONTEXT_PATH, webContext)); Why cache loginIdentityContext in processor? Is it duplicated with AbstractClientAuthService? private final NacosRestTemplate nacosRestTemplate; public HttpLoginProcessor(NacosRestTemplate nacosRestTemplate) { this.nacosRestTemplate = nacosRestTemplate; } @Override + public LoginIdentityContext getResponse(Properties properties) { String contextPath = ContextPathUtil .normalizeContextPath(properties.getProperty(PropertyKeyConst.CONTEXT_PATH, webContext));
codereview_java_data_7584
// If the deployer implementation handles the deployment request synchronously, log warning message if // any exception is thrown out of the deployment and proceed to the next deployment. catch (Exception e) { - loggger.warn(String.format("Exception when deploying the app %s:%s", currentModule, e.getMessage())); } } } should add a space after the colon // If the deployer implementation handles the deployment request synchronously, log warning message if // any exception is thrown out of the deployment and proceed to the next deployment. catch (Exception e) { + loggger.warn(String.format("Exception when deploying the app %s: %s", currentModule, e.getMessage())); } } }
codereview_java_data_7588
POLICY, SERVICE, ENTITY, - USER } private String domainName; Not sure if this is the right object since we don't manage USERs. When we manage users, it's typically to delete members from roles/groups, etc. So I don't expect any notifications where a user object was modified. The correct events would be either a role or a group was modified in a given domain. POLICY, SERVICE, ENTITY, + TEMPLATE } private String domainName;
codereview_java_data_7590
return; } - handleNewPartitions(topicIndex, newPartitionCount); } nextMetadataCheck = System.nanoTime() + METADATA_CHECK_INTERVAL_NANOS; } - private void handleNewPartitions(int topicIndex, int newPartitionCount) { String topicName = topics.get(topicIndex); long[] oldTopicOffsets = offsets.get(topicName); if (oldTopicOffsets.length >= newPartitionCount) { ```suggestion getLogger().info("New partition(s) assigned: " + newAssignments); ``` return; } + handleNewPartitions(topicIndex, newPartitionCount, false); } nextMetadataCheck = System.nanoTime() + METADATA_CHECK_INTERVAL_NANOS; } + private void handleNewPartitions(int topicIndex, int newPartitionCount, boolean isRestoring) { String topicName = topics.get(topicIndex); long[] oldTopicOffsets = offsets.get(topicName); if (oldTopicOffsets.length >= newPartitionCount) {
codereview_java_data_7600
/* - * Copyright 2019-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. please put some message here so that users can understand the error /* + * Copyright 2019-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
codereview_java_data_7608
import org.junit.Test; import software.amazon.awssdk.core.internal.batchutilities.BatchAndSendFunction; import software.amazon.awssdk.core.internal.batchutilities.BatchManager; import software.amazon.awssdk.core.internal.batchutilities.BatchResponseMapperFunction; import software.amazon.awssdk.core.internal.batchutilities.GetBatchGroupIdFunction; import software.amazon.awssdk.core.internal.batchutilities.IdentifiableResponse; We should use the test credentials from `IntegrationTestBase` instead of using the default credentials from `create()` because it will fail in our CI. import org.junit.Test; import software.amazon.awssdk.core.internal.batchutilities.BatchAndSendFunction; import software.amazon.awssdk.core.internal.batchutilities.BatchManager; +import software.amazon.awssdk.core.internal.batchutilities.BatchOverrideConfiguration; import software.amazon.awssdk.core.internal.batchutilities.BatchResponseMapperFunction; import software.amazon.awssdk.core.internal.batchutilities.GetBatchGroupIdFunction; import software.amazon.awssdk.core.internal.batchutilities.IdentifiableResponse;
codereview_java_data_7617
package net.sourceforge.pmd.lang.java.ast; /** - * Marker interface for type body declarations. * * @author Clément Fournier */ Maybe add short example list: .... type body declarations, such as AnnotationMembers, Methods, Fields package net.sourceforge.pmd.lang.java.ast; /** + * Marker interface for type body declarations, such as annotation members, field or method declarations. * * @author Clément Fournier */
codereview_java_data_7623
"task schedule create --name \"%s\" --definitionName \"%s\" --expression \"%s\" --properties \"%s\" --arguments \"%s\"", name, definition, expression, properties, args); CommandResult cr = dataFlowShell.executeCommand(wholeCommand); - verify(schedule).schedule(name, definition, Collections.singletonMap("scheduler.cron.expression", expression), Collections.emptyList(), null); - assertEquals("Created schedule 'schedName'", cr.getResult()); } public void createWithPropertiesFile(String name, String definition, String expression, String propertiesFile, String args) throws IOException { Probably want to use the `name` parameter that was passed into the method to do this assertion instead of hardcoding `schedName`. "task schedule create --name \"%s\" --definitionName \"%s\" --expression \"%s\" --properties \"%s\" --arguments \"%s\"", name, definition, expression, properties, args); CommandResult cr = dataFlowShell.executeCommand(wholeCommand); + verify(schedule).schedule(name, definition, Collections.singletonMap(TaskSchedule.CRON_EXPRESSION_KEY, expression), Collections.emptyList(), null); + assertEquals("Created schedule '" + name + "'", cr.getResult()); } public void createWithPropertiesFile(String name, String definition, String expression, String propertiesFile, String args) throws IOException {
codereview_java_data_7624
accessTokenResponseClient.ifPresent(client -> this.accessTokenResponseClient = client); } } - - @Configuration(proxyBeanMethods = false) - static class OAuth2ClientRegistrationsConfiguration { - - @Autowired - @Qualifier(OAuth2ClientBeanNames.REST_OPERATIONS) - void configure(RestOperations restOperations) { - ClientRegistrations.setRestOperations(restOperations); - } - } } Setting a static method from a bean definition is not a typical pattern I find in Spring. Instead, I'd expect to be able to provide the RestOperations to the builder. A few concerns around this design: First, it is not easy to provide different ``RestOperation``s for different issuers in a thread safe way. The builders should ideally be thread safe. This is especially true, given the performance improvements being made to Spring and talks around making bean creation multi-threaded. Another and more immediate concern is that it appears that there is likely a bean ordering issue here. What guarantees this will happen before `ClientRegistrations` is used to create a client registration? accessTokenResponseClient.ifPresent(client -> this.accessTokenResponseClient = client); } } }
codereview_java_data_7628
private RandomUtil() { } - private static final Random NEGATIVE_VALUES = new Random(); - - private static boolean negate() { - return NEGATIVE_VALUES.nextInt(2) == 1; } @SuppressWarnings("RandomModInteger") All tests need to use the `Random` that is passed in so that the values that are generated are deterministic and repeatable. That's what allows us to generated an iterator instead of a list in some cases, and makes it so if we do have a problem, we can repeat the test and debug. private RandomUtil() { } + private static boolean negate(int num) { + return num % 2 == 1; } @SuppressWarnings("RandomModInteger")
codereview_java_data_7633
InputConfigurator.setConnectionInfo(CLASS, job, inputInfo); } protected static ConnectionInfo getConnectionInfo(JobConf job) { return InputConfigurator.getConnectionInfo(CLASS, job); } if its protected, then its in public API and should have a since tag InputConfigurator.setConnectionInfo(CLASS, job, inputInfo); } + /** + * Retrieves {@link ConnectionInfo} from the configuration + * + * @param job + * Hadoop job instance configuration + * @return {@link ConnectionInfo} object + * @since 2.0.0 + */ protected static ConnectionInfo getConnectionInfo(JobConf job) { return InputConfigurator.getConnectionInfo(CLASS, job); }
codereview_java_data_7635
import android.util.Log; import de.danoeh.antennapod.core.ClientConfig; import de.danoeh.antennapod.core.preferences.UserPreferences; -import de.danoeh.antennapod.core.storage.DBTasks; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public class FeedUpdateJobService extends JobService { This `JobScheduler` version of feed update does not obey mobile update user preference. In contrast, the `AlarmManager` version in `FeedUpdateReceiver` does the check: ```java if (NetworkUtils.networkAvailable() && NetworkUtils.isDownloadAllowed()) { ``` In fact, I'd suggest consolidate the actual refresh logic used by `FeedUpdateReceiver` and `FeedUpdateJobService` into a common method. import android.util.Log; import de.danoeh.antennapod.core.ClientConfig; import de.danoeh.antennapod.core.preferences.UserPreferences; +import de.danoeh.antennapod.core.util.FeedUpdateUtils; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public class FeedUpdateJobService extends JobService {
codereview_java_data_7646
viewBinding.subscribeButton.setEnabled(true); viewBinding.subscribeButton.setText(R.string.subscribe_label); if (UserPreferences.isEnableAutodownload()) { - LinearLayout.LayoutParams layoutParams - = (LinearLayout.LayoutParams) viewBinding.subscribeButton.getLayoutParams(); - layoutParams.setMargins(16, 16, 16, 0); - viewBinding.subscribeButton.setLayoutParams(layoutParams); viewBinding.autoDownloadCheckBox.setChecked(true); viewBinding.autoDownloadCheckBox.setVisibility(View.VISIBLE); } This still modifies the margins from Java code, which is not really elegant (and does not work correctly, depending on screen resolution). Could you please try to find a way to do this from XML? viewBinding.subscribeButton.setEnabled(true); viewBinding.subscribeButton.setText(R.string.subscribe_label); if (UserPreferences.isEnableAutodownload()) { viewBinding.autoDownloadCheckBox.setChecked(true); viewBinding.autoDownloadCheckBox.setVisibility(View.VISIBLE); }
codereview_java_data_7657
: OptionalLong.empty(); } - public static BigInteger getBigInteger(final JsonObject jsonObject, final String key) { final Number value = (Number) jsonObject.getMap().get(key); if (value == null) { return null; `Optional<BigInteger>` for consistency with the other method in this class : OptionalLong.empty(); } + public static Optional<BigInteger> getOptionalBigInteger( + final JsonObject jsonObject, final String key) { + return jsonObject.containsKey(key) + ? Optional.ofNullable(getBigInteger(jsonObject, key)) + : Optional.empty(); + } + + private static BigInteger getBigInteger(final JsonObject jsonObject, final String key) { final Number value = (Number) jsonObject.getMap().get(key); if (value == null) { return null;
codereview_java_data_7664
-/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ -/* Generated By:JJTree: Do not edit this line. ASTAttribute.java */ package net.sourceforge.pmd.lang.jsp.ast; public class ASTAttribute extends AbstractJspNode { private String name; * We need to deprecate/internalize first on master. * We should directly make the AST node final now * The setter `setName()` can be package-private. +/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; +import net.sourceforge.pmd.annotation.InternalApi; + public class ASTAttribute extends AbstractJspNode { private String name;
codereview_java_data_7667
if (LaunchIntent != null) { startActivity(LaunchIntent); }else{ - Toast.makeText(this, "App Disabled", Toast.LENGTH_SHORT).show(); } } else { try { This needs to be a string resource > Application is not installed if (LaunchIntent != null) { startActivity(LaunchIntent); }else{ + Toast.makeText(this, R.string.app_disabled_text, Toast.LENGTH_SHORT).show(); } } else { try {
codereview_java_data_7668
backupLevel += start ? 1 : -1; } - public synchronized void setMaxMemory(int size) { cache.setMaxMemory(size); } can that method have more specific name like "setMaxCacheMemory" backupLevel += start ? 1 : -1; } + public synchronized void setMaxCacheMemory(int size) { cache.setMaxMemory(size); }
codereview_java_data_7674
if (registrationId == null) { return null; } - String[] params = new String[0]; - if (registrationId.contains("?")) { - String[] explodedURI = registrationId.split("\\?"); - registrationId = registrationId.split("\\?")[0]; - params = explodedURI[1].split("&"); - } ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); if (clientRegistration == null) { Parsing URLs is hard. Any fixes should avoid manually parsing the URL. if (registrationId == null) { return null; } ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); if (clientRegistration == null) {
codereview_java_data_7684
public void showDuplicatePicturePopup() { String uploadTitleFormat = getString(R.string.upload_title_duplicate); DialogUtil.showAlertDialog(getActivity(), - getString(R.string.warning), String.format(Locale.getDefault(), uploadTitleFormat, uploadItem.getFileName()), getString(R.string.cancel), - getString(R.string.upload_image), () -> { }, Are these in the wrong order? `Upload` should be on the right. If you could post a picture of the changes you made that would be very helpful public void showDuplicatePicturePopup() { String uploadTitleFormat = getString(R.string.upload_title_duplicate); DialogUtil.showAlertDialog(getActivity(), + getString(R.string.duplicate_image_found), String.format(Locale.getDefault(), uploadTitleFormat, uploadItem.getFileName()), getString(R.string.cancel), + getString(R.string.upload_proceed), () -> { },