id
stringlengths
23
26
content
stringlengths
182
2.49k
codereview_java_data_1788
assertEquals(2, requests.size()); AppDeploymentRequest logRequest = requests.get(0); assertThat(logRequest.getDefinition().getName(), is("log")); - assertEquals(logRequest.getDeploymentProperties().get(AppDeployer.INDEXED_PROPERTY_KEY), "true"); AppDeploymentRequest timeRequest = requests.get(1); assertThat(timeRequest.getDefinition().getName(), is("time")); } nitpick: all of these `assertEquals` should have the expected value ("true") on the left hand side assertEquals(2, requests.size()); AppDeploymentRequest logRequest = requests.get(0); assertThat(logRequest.getDefinition().getName(), is("log")); + assertEquals("true", logRequest.getDeploymentProperties().get(AppDeployer.INDEXED_PROPERTY_KEY)); AppDeploymentRequest timeRequest = requests.get(1); assertThat(timeRequest.getDefinition().getName(), is("time")); }
codereview_java_data_1792
// Do nothing. } - public void beforeChangeValueOf(WebElement element, WebDriver driver, CharSequence[] value) { // Do nothing. } - public void afterChangeValueOf(WebElement element, WebDriver driver, CharSequence[] value) { // Do nothing. } change 'value' to keysToSend, here and in other references in this commit. 'value' implies the user is getting the value of the element, rather than just the keys we're sending to it. // Do nothing. } + public void beforeChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend) { // Do nothing. } + public void afterChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend) { // Do nothing. }
codereview_java_data_1801
ldapfilter.substring(ldapfilter.indexOf("=", ldapfilter.indexOf(searchRangeStr)+searchRangeStr.length())); } - - if (Log.isDebugEnabled()) { - Log.debug("Trying to find group names using query: " + ldapfilter); - } // Perform the LDAP query return manager.retrieveList( While you're at it, you might as well use parameters: Log.debug("Trying to find group names using query: {}", ldapfilter); With that, I don't think that there's a point in keeping the `if (Log.isDebugEnabled())` check. ldapfilter.substring(ldapfilter.indexOf("=", ldapfilter.indexOf(searchRangeStr)+searchRangeStr.length())); } + + Log.debug("Trying to find group names using query: {}", ldapfilter); // Perform the LDAP query return manager.retrieveList(
codereview_java_data_1806
} private void throwUnknownLanguageVersionException(String minOrMax, String unknownVersion) { - throw new IllegalArgumentException("Unknown " + minOrMax + " Language Version '" + unknownVersion - + "' for Language '" + language.getTerseName() - + "' for Rule " + name - + "; supported Language Versions are: " - + language.getVersions().stream().map(LanguageVersion::getTerseName).collect(Collectors.joining(", "))); } public Rule build() throws ClassNotFoundException, IllegalAccessException, InstantiationException { Lol! I just realized this message has always been incorrect. If a user's rule is configured as: ```xml <rule name="MyRule" language="java" minimumLanguageVersion="8"> <!-- Java 8 rule! --> ``` We are printing something such as: > Unknown minimum Language Version 8 for Language 'java' for Rule MyRule; supported Language Versions are: java 1.3, java 1.4, java 1.5, java 1.6, java 1.7, java 1.8, java 9, So, a user would understand, that instead of `8`, they should write `java 1.8` as: ```xml <rule name="MyRule" language="java" minimumLanguageVersion="java 1.8"> ``` which would not be valid. We should probably just do: ```java language.getVersions().stream().map(LanguageVersion::getVersion).collect(Collectors.joining(", "))); ``` to produce: > Unknown minimum Language Version 8 for Language 'java' for Rule MyRule; supported Language Versions are: 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 9, } private void throwUnknownLanguageVersionException(String minOrMax, String unknownVersion) { + throw new IllegalArgumentException("Unknown " + minOrMax + " language version '" + unknownVersion + + "' for language '" + language.getTerseName() + + "' for rule " + name + + "; supported language versions are: " + + language.getVersions().stream().map(LanguageVersion::getVersion).collect(Collectors.joining(", "))); } public Rule build() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
codereview_java_data_1818
import com.github.javaparser.symbolsolver.model.resolution.TypeSolver; import com.google.common.collect.ImmutableList; -import java.util.EnumSet; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; -import static com.github.javaparser.symbolsolver.javaparser.Navigator.getParentNode; - /** * @author Federico Tomassetti */ We may still need this as the AccessSpecifier is different that the modifiers. Some modifiers have nothing to do with access and the default access is not represented by modifiers import com.github.javaparser.symbolsolver.model.resolution.TypeSolver; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * @author Federico Tomassetti */
codereview_java_data_1840
return mockPrivateTransactionProcessor; } - private Enclave brokenMockEnclave() throws Exception { Enclave mockEnclave = mock(Enclave.class); when(mockEnclave.receive(any(ReceiveRequest.class))).thenThrow(EnclaveException.class); return mockEnclave; } @Before - public void setUp() throws Exception { WorldStateArchive worldStateArchive; worldStateArchive = mock(WorldStateArchive.class); MutableWorldState mutableWorldState = mock(MutableWorldState.class); throws Exception shouldn't be needed now it's throwing the runtime EnclaveException return mockPrivateTransactionProcessor; } + private Enclave brokenMockEnclave() { Enclave mockEnclave = mock(Enclave.class); when(mockEnclave.receive(any(ReceiveRequest.class))).thenThrow(EnclaveException.class); return mockEnclave; } @Before + public void setUp() { WorldStateArchive worldStateArchive; worldStateArchive = mock(WorldStateArchive.class); MutableWorldState mutableWorldState = mock(MutableWorldState.class);
codereview_java_data_1856
import com.fasterxml.jackson.databind.node.ArrayNode; -import static org.assertj.core.api.Assertions.*; - /** * @author Tom Baeyens * @author Falko Menge Thanks for the PR. Project formatting standards are not to use package imports but rather enumerate them all. In addition static imports are at the top of the list of import statements. import com.fasterxml.jackson.databind.node.ArrayNode; /** * @author Tom Baeyens * @author Falko Menge
codereview_java_data_1858
class ZKSecurityTool { private static final Logger log = LoggerFactory.getLogger(ZKSecurityTool.class); private static final int SALT_LENGTH = 8; - private static final Charset CRYPT_CHARSET = UTF_8; // Generates a byte array salt of length SALT_LENGTH private static byte[] generateSalt() { Could inline this constant, to avoid the extra `CRYPT_CHARSET` variable and corresponding Charset import. class ZKSecurityTool { private static final Logger log = LoggerFactory.getLogger(ZKSecurityTool.class); private static final int SALT_LENGTH = 8; // Generates a byte array salt of length SALT_LENGTH private static byte[] generateSalt() {
codereview_java_data_1862
this.entityId = entityId; this.assertionConsumerServiceLocation = assertionConsumerServiceLocation; this.assertionConsumerServiceBinding = assertionConsumerServiceBinding; - this.singleLogoutServiceLocation = singleLogoutServiceLocation; - this.singleLogoutServiceResponseLocation = singleLogoutServiceResponseLocation; - this.singleLogoutServiceBinding = singleLogoutServiceBinding; this.providerDetails = providerDetails; this.credentials = Collections.unmodifiableList(new LinkedList<>(credentials)); this.decryptionX509Credentials = Collections.unmodifiableList(new LinkedList<>(decryptionX509Credentials)); It's been over a year, so you know better than me. Are these two different locations in the Metadata spec? I was under the impression that `<SingleLogoutService>` was for both requests and responses. That an IDP/SP handles both requests and responses on the same endpoint this.entityId = entityId; this.assertionConsumerServiceLocation = assertionConsumerServiceLocation; this.assertionConsumerServiceBinding = assertionConsumerServiceBinding; this.providerDetails = providerDetails; this.credentials = Collections.unmodifiableList(new LinkedList<>(credentials)); this.decryptionX509Credentials = Collections.unmodifiableList(new LinkedList<>(decryptionX509Credentials));
codereview_java_data_1863
* @param <RequestT> The request */ @SdkProtectedApi -public class IdentifiableRequest<RequestT> { private final String id; private final RequestT request; Backlog item: Will do in a separate PR. * @param <RequestT> The request */ @SdkProtectedApi +public final class IdentifiableRequest<RequestT> { private final String id; private final RequestT request;
codereview_java_data_1864
if (CryptoHelper.isPgpInlineEncrypted(message) || CryptoHelper.isPgpMimeEncrypted(message) || CryptoHelper.isSMimeEncrypted(message)) { - return "*Encrypted*"; } getViewablesIfNecessary(); return MessagePreviewExtractor.extractPreview(context, viewables); I think this string needs to be externalized so it can be translated if (CryptoHelper.isPgpInlineEncrypted(message) || CryptoHelper.isPgpMimeEncrypted(message) || CryptoHelper.isSMimeEncrypted(message)) { + return context.getString(R.string.openpgp_message_preview); } getViewablesIfNecessary(); return MessagePreviewExtractor.extractPreview(context, viewables);
codereview_java_data_1867
void testSameType() { validator() .addInputLines( - "Test.java", "public class Test {", " public void badMethod(Integer a, Integer b) {}", "}") .expectUnchanged() .doTestExpectingFailure(TEST_MODE); } can put a `//` after `"Test.java",` to make the formatter align these one per line void testSameType() { validator() .addInputLines( + "Test.java", // + "public class Test {", + " public void badMethod(Integer a, Integer b) {}", + "}") .expectUnchanged() .doTestExpectingFailure(TEST_MODE); }
codereview_java_data_1875
return isJUnit3Class && method.isVoid() && method.getName().startsWith("test"); } - protected boolean isJUnit3Class(ASTCompilationUnit node) { ASTClassOrInterfaceDeclaration cid = node.getFirstDescendantOfType(ASTClassOrInterfaceDeclaration.class); if (cid == null) { return false; I'd not expose these methods. These methods are called already when visiting CompilationUnit and the result is stored in fields, see lines 38-40 above. I'd make these fields protected, so that you can use it in the rule. return isJUnit3Class && method.isVoid() && method.getName().startsWith("test"); } + private boolean isJUnit3Class(ASTCompilationUnit node) { ASTClassOrInterfaceDeclaration cid = node.getFirstDescendantOfType(ASTClassOrInterfaceDeclaration.class); if (cid == null) { return false;
codereview_java_data_1877
return RelDistributionTraitDef.INSTANCE.canonize(trait); } - public static RelDistribution with(RelDistribution.Type type, ImmutableIntList keys) { return new RelDistributionImpl(type, keys); } maybe `of()` to be consistent with `RelCollatioins`? return RelDistributionTraitDef.INSTANCE.canonize(trait); } + public static RelDistribution of(RelDistribution.Type type, ImmutableIntList keys) { return new RelDistributionImpl(type, keys); }
codereview_java_data_1883
return; } - for (Entry<Object, Object> keyEntry : properties.entrySet()) { - System.out.printf("%-50s= %s\n", keyEntry.getKey(), keyEntry.getValue()); } System.out.printf("%n"); keyEntry could be renamed to entry, and so is the obove return; } + for (Entry<Object, Object> entry : properties.entrySet()) { + System.out.printf("%-50s= %s\n", entry.getKey(), entry.getValue()); } System.out.printf("%n");
codereview_java_data_1884
if (iconColor != null) { try { mBuilder.setColor(Color.parseColor(iconColor)); - } catch (Exception ex) { - call.error("The iconColor string was not able to be parsed. Please provide a valid string hexidecimal color code.", ex); return; } } For consistency, better use the same error message as Status Bar plugin ```suggestion call.error("Invalid color provided. Must be a hex string (ex: #ff0000"); ``` if (iconColor != null) { try { mBuilder.setColor(Color.parseColor(iconColor)); + } catch (IllegalArgumentException ex) { + call.error("Invalid color provided. Must be a hex string (ex: #ff0000"); return; } }
codereview_java_data_1888
fatalException = new TableDeletedException(tableId.canonical()); } catch (SampleNotPresentException e) { fatalException = e; - } catch (Throwable t) { if (queryThreadPool.isShutdown()) log.debug("Caught exception, but queryThreadPool is shutdown", t); else log.warn("Caught exception, but queryThreadPool is not shutdown", t); fatalException = t; } finally { semaphore.release(); Thread.currentThread().setName(threadName); I like the simplicity of this earlier solution. If the user is providing their own thread pools, why wouldn't they be able to provide their own uncaught exception handler to receive these and handle them on their own, if they wish? fatalException = new TableDeletedException(tableId.canonical()); } catch (SampleNotPresentException e) { fatalException = e; + } catch (Exception t) { if (queryThreadPool.isShutdown()) log.debug("Caught exception, but queryThreadPool is shutdown", t); else log.warn("Caught exception, but queryThreadPool is not shutdown", t); fatalException = t; + } catch (Throwable t) { + fatalException = t; + log.error("QueryTask::run encountered throwable: {}", t.getMessage()); + throw t; // let uncaught exception handler deal with the Error } finally { semaphore.release(); Thread.currentThread().setName(threadName);
codereview_java_data_1895
return cs; } - public boolean getDisableAudioTrackSorting() { - return getBoolean(KEY_DISABLE_AUDIO_TRACK_SORTING, false); } public boolean isDynamicPls() { ```suggestion public boolean isSortAudioTracksByAlbumPosition() { return getBoolean(KEY_SORT_AUDIO_TRACKS_BY_ALBUM_POSITION, true); ``` return cs; } + public boolean isSortAudioTracksByAlbumPosition() { + return getBoolean(KEY_SORT_AUDIO_TRACKS_BY_ALBUM_POSITION, true); } public boolean isDynamicPls() {
codereview_java_data_1897
import org.kie.kogito.Application; import org.kie.kogito.tracing.decision.event.explainability.PredictInput; import org.kie.kogito.tracing.decision.explainability.ExplainabilityService; @Path("/predict") public class QuarkusExplainableResource { private final Application application; private final ExplainabilityService explainabilityService = ExplainabilityService.INSTANCE; What about log the exception too? import org.kie.kogito.Application; import org.kie.kogito.tracing.decision.event.explainability.PredictInput; import org.kie.kogito.tracing.decision.explainability.ExplainabilityService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @Path("/predict") public class QuarkusExplainableResource { + private static final Logger LOGGER = LoggerFactory.getLogger(QuarkusExplainableResource.class); private final Application application; private final ExplainabilityService explainabilityService = ExplainabilityService.INSTANCE;
codereview_java_data_1902
break; } } - if (name != null && !name.trim().isEmpty()) { - nameNode.put(locale, name); } - if (documentation != null && !documentation.trim().isEmpty()) { - descriptionNode.put(locale, documentation); } } } If you are expecting leading/trailing spaces (the use of trim()); wouldn't you want to store the trimmed value too? break; } } + if (StringUtils.isNotBlank(name)) { + nameNode.put(locale, name.trim()); } + if (StringUtils.isNotBlank(documentation)) { + descriptionNode.put(locale, documentation.trim()); } } }
codereview_java_data_1911
TableMetadata lastMetadata = ops.current(); try { if (lastMetadata == null) { - LOG.error("Not an iceberg table: %s", identifier); return false; } else { if (purge) { This is not an error. The API states that if the table doesn't exist, then the catalog should return false. If you want to add a debug log, that's fine. But this should not be info or error level. TableMetadata lastMetadata = ops.current(); try { if (lastMetadata == null) { + LOG.debug("Not an iceberg table: %s", identifier); return false; } else { if (purge) {
codereview_java_data_1912
@Test public void shouldCreateSeparateObservationsForEachCounterLabelValue() { final LabelledMetric<Counter> counter = - metricsSystem.createCounter(PEERS, "connected", "Some help string", "labelName"); counter.labels("value1").inc(); counter.labels("value2").inc(); Should we make one of these timer tests a try with resources? That would validate the Closable interface on them. @Test public void shouldCreateSeparateObservationsForEachCounterLabelValue() { final LabelledMetric<Counter> counter = + metricsSystem.createLabelledCounter(PEERS, "connected", "Some help string", "labelName"); counter.labels("value1").inc(); counter.labels("value2").inc();
codereview_java_data_1922
public class NewSessionRequest { - private final UUID requestId; private final CountDownLatch latch; private HttpResponse sessionResponse; - public NewSessionRequest(UUID requestId, CountDownLatch latch) { this.requestId = requestId; this.latch = latch; } We may want a `RequestId` class. Passing around `UUID` is getting confusing :) public class NewSessionRequest { + private final RequestId requestId; private final CountDownLatch latch; private HttpResponse sessionResponse; + public NewSessionRequest(RequestId requestId, CountDownLatch latch) { this.requestId = requestId; this.latch = latch; }
codereview_java_data_1942
/** * @author Julio Vilmar Gesser */ -public final class ClassOrInterfaceType extends Type implements NamedNode { private ClassOrInterfaceType scope; that is not the name of the node, that is a "reference by name"... I think this shouldn't be a `NamedNode` /** * @author Julio Vilmar Gesser */ +public final class ClassOrInterfaceType extends Type { private ClassOrInterfaceType scope;
codereview_java_data_1951
this.config = config.initialize(); - if (Boolean.TRUE.equals(Boolean - .valueOf(this.config.getSiteConfig().get(Property.TSERV_NATIVEMAP_ENABLED.name())))) { if (!NativeMap.isLoaded()) throw new RuntimeException( "MAC configured to use native maps, but unable to load the library."); I wouldn't expect this to work. The native maps are loaded by adding LD_LIBRARY_PATH environment to the tserver Process before it is launched. There's no reason to expect the native map to be loaded inside the MiniAccumuloClusterImpl... only for the processes it launches. (Also, no need to do `if (Boolean.TRUE.equals(someBoolExpr))` when you can just do `if (someBoolExpr)`) this.config = config.initialize(); + if (Boolean.valueOf(this.config.getSiteConfig().get(Property.TSERV_NATIVEMAP_ENABLED.name()))) { if (!NativeMap.isLoaded()) throw new RuntimeException( "MAC configured to use native maps, but unable to load the library.");
codereview_java_data_1952
private static final double RATIO_OF_DESCRIBE_STREAM_RATE_UTILIZED = 0.1; private final AtomicInteger shardCount; - private final RandomizedRateTracker descriteStreamRateTracker; private final RetryTracker describeStreamRetryTracker; private Future<DescribeStreamSummaryResult> describeStreamResult; private long nextDescribeStreamTime; public ShardCountMonitor( - AtomicInteger shardCount, int totalInstances, AmazonKinesisAsync kinesis, String stream, can we rename this to something ending with `Future`. I think we can also drop the `describeStream` prefix for this and other fields. The only thing we are really interested is the shard-count I guess private static final double RATIO_OF_DESCRIBE_STREAM_RATE_UTILIZED = 0.1; private final AtomicInteger shardCount; + private final RandomizedRateTracker describeStreamRateTracker; private final RetryTracker describeStreamRetryTracker; private Future<DescribeStreamSummaryResult> describeStreamResult; private long nextDescribeStreamTime; public ShardCountMonitor( int totalInstances, AmazonKinesisAsync kinesis, String stream,
codereview_java_data_1955
// Mark as stopped context.component._setStartStop(StartStop.STOP); - return State.UNDEFINED; } } If the inverter is stopped, it is a defined state. Why is the next state undefined? // Mark as stopped context.component._setStartStop(StartStop.STOP); + return State.STOPPED; } }
codereview_java_data_1956
new ThreeColumnRecord(1, "b c", "data"), new ThreeColumnRecord(2, "ab", "data")); - File location = temp.newFolder("partitioned_table"); String tableName = "external_table"; spark.createDataFrame(records, ThreeColumnRecord.class) I suppose we cannot use Java9 factory methods in Spark2 project new ThreeColumnRecord(1, "b c", "data"), new ThreeColumnRecord(2, "ab", "data")); String tableName = "external_table"; spark.createDataFrame(records, ThreeColumnRecord.class)
codereview_java_data_1961
return taskExecution; } - public TaskExecutionManifest sanitizeTaskManifest(TaskExecutionManifest taskManifest) { - if (taskManifest == null) { return null; } TaskExecutionManifest sanitizedTaskExecutionManifest = new TaskExecutionManifest(); TaskExecutionManifest.Manifest sanitizedManifest = sanitizedTaskExecutionManifest.getManifest(); - TaskExecutionManifest.Manifest dirtyTaskManifest = taskManifest.getManifest(); sanitizedManifest.setPlatformName(dirtyTaskManifest.getPlatformName()); AppDeploymentRequest existingAppDeploymentRequest = dirtyTaskManifest.getTaskDeploymentRequest(); // Sanitize App Properties We can rename this method as well (to have TaskExecutionManifest) return taskExecution; } + public TaskExecutionManifest sanitizeTaskExecutionManifest(TaskExecutionManifest taskExecutionManifest) { + if (taskExecutionManifest == null) { return null; } TaskExecutionManifest sanitizedTaskExecutionManifest = new TaskExecutionManifest(); TaskExecutionManifest.Manifest sanitizedManifest = sanitizedTaskExecutionManifest.getManifest(); + TaskExecutionManifest.Manifest dirtyTaskManifest = taskExecutionManifest.getManifest(); sanitizedManifest.setPlatformName(dirtyTaskManifest.getPlatformName()); AppDeploymentRequest existingAppDeploymentRequest = dirtyTaskManifest.getTaskDeploymentRequest(); // Sanitize App Properties
codereview_java_data_1968
* Start the timer to make sure processing doesn't take too long. */ public void start() { - stopAt = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(MAX_PROCESSING_TIME); } /** rename stopAt to stopAtNs * Start the timer to make sure processing doesn't take too long. */ public void start() { + stopAtNs = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(MAX_PROCESSING_TIME); } /**
codereview_java_data_1976
Utils.idLock.lock(); try { tableInfo.tableId = Utils.getNextId(tableInfo.tableName, master.getInstance(), Table.ID::of); - if (tableInfo.props.containsKey(Property.TABLE_OFFLINE_OPTS + "create.initial.splits") - && this.splitFile != null) { - storeSplitFileNameInZooKeeper(); - } return new SetupPermissions(tableInfo); } finally { Utils.idLock.unlock(); } - } @Override I don't think this needs to be stored in ZK explicitly. The way FATE works, each step of a FATE op is serialized to ZK. Therefore if you store any info you want to keep around in the TableInfo object, then the TableInfo object will be serialized in subsequent steps. Utils.idLock.lock(); try { tableInfo.tableId = Utils.getNextId(tableInfo.tableName, master.getInstance(), Table.ID::of); return new SetupPermissions(tableInfo); } finally { Utils.idLock.unlock(); } } @Override
codereview_java_data_1984
int size = mb.readInt(); currentReaders = new ArrayList<>(size); - deepCopies = new ArrayList<>(); for (int i = 0; i < size; i++) { LocalityGroupMetadata lgm = new LocalityGroupMetadata(ver, rdr); We only ever do `add()` on this, which can cause problems on certain system patterns which use a lot of deepCopies, if it results in array resizing. `LinkedList` is probably better here for those use cases, and not worse for other use cases. I'd leave this one the way it was. int size = mb.readInt(); currentReaders = new ArrayList<>(size); + deepCopies = new LinkedList<>(); for (int i = 0; i < size; i++) { LocalityGroupMetadata lgm = new LocalityGroupMetadata(ver, rdr);
codereview_java_data_1987
metricsSystem.createCounter( MetricCategory.SYNCHRONIZER, "inboundQueueCounter", - "parallel download pipeline metric"); this.outboundQueueCounter = metricsSystem.createCounter( MetricCategory.SYNCHRONIZER, "outboundQueueCounter", - "parallel download pipeline metric"); } @Override More descriptive, such as "count of queue items that started processing" metricsSystem.createCounter( MetricCategory.SYNCHRONIZER, "inboundQueueCounter", + "count of queue items that started processing"); this.outboundQueueCounter = metricsSystem.createCounter( MetricCategory.SYNCHRONIZER, "outboundQueueCounter", + "count of queue items that finished processing"); } @Override
codereview_java_data_1993
*/ public interface OpenFoodAPIService { - String PRODUCT_API_COMMENT = "new android app"; @GET("api/v0/product/{barcode}.json?fields=image_small_url,vitamins_tags,minerals_tags,amino_acids_tags,other_nutritional_substances_tags,image_front_url,image_ingredients_url,image_nutrition_url,url,code,traces_tags,ingredients_that_may_be_from_palm_oil_tags,additives_tags,allergens_hierarchy,manufacturing_places,nutriments,ingredients_from_palm_oil_tags,brands_tags,traces,categories_tags,ingredients_text,product_name,generic_name,ingredients_from_or_that_may_be_from_palm_oil_n,serving_size,allergens,origins,stores,nutrition_grade_fr,nutrient_levels,countries,countries_tags,brands,packaging,labels_tags,labels_hierarchy,cities_tags,quantity,ingredients_from_palm_oil_n,image_url,link,emb_codes_tags,states_tags,creator,created_t,last_modified_t,last_modified_by,editors_tags,nova_groups,lang,purchase_places,nutrition_data_per") Call<State> getFullProductByBarcode(@Path("barcode") String barcode); Can we put the version number as well ? */ public interface OpenFoodAPIService { + String PRODUCT_API_COMMENT = "Official Android app"; @GET("api/v0/product/{barcode}.json?fields=image_small_url,vitamins_tags,minerals_tags,amino_acids_tags,other_nutritional_substances_tags,image_front_url,image_ingredients_url,image_nutrition_url,url,code,traces_tags,ingredients_that_may_be_from_palm_oil_tags,additives_tags,allergens_hierarchy,manufacturing_places,nutriments,ingredients_from_palm_oil_tags,brands_tags,traces,categories_tags,ingredients_text,product_name,generic_name,ingredients_from_or_that_may_be_from_palm_oil_n,serving_size,allergens,origins,stores,nutrition_grade_fr,nutrient_levels,countries,countries_tags,brands,packaging,labels_tags,labels_hierarchy,cities_tags,quantity,ingredients_from_palm_oil_n,image_url,link,emb_codes_tags,states_tags,creator,created_t,last_modified_t,last_modified_by,editors_tags,nova_groups,lang,purchase_places,nutrition_data_per") Call<State> getFullProductByBarcode(@Path("barcode") String barcode);
codereview_java_data_2002
package com.palantir.gradle.junit; import org.gradle.api.NamedDomainObjectSet; import org.gradle.api.Project; import org.gradle.api.model.ObjectFactory; import org.immutables.value.Value.Immutable; public class JunitTaskResultExtension { Please can we have test for this PR - would also make it more obvious how it's meant to be used/what it will produced. package com.palantir.gradle.junit; +import java.nio.file.Path; +import java.util.List; import org.gradle.api.NamedDomainObjectSet; import org.gradle.api.Project; import org.gradle.api.model.ObjectFactory; +import org.gradle.api.provider.Provider; import org.immutables.value.Value.Immutable; public class JunitTaskResultExtension {
codereview_java_data_2004
} private static int killLoadData(String stmt, int offset) { - if (stmt.length() > offset + 5) { char c1 = stmt.charAt(++offset); char c2 = stmt.charAt(++offset); char c3 = stmt.charAt(++offset); Incorrect boundary check } private static int killLoadData(String stmt, int offset) { + if (stmt.length() > offset + "oadData".length()) { char c1 = stmt.charAt(++offset); char c2 = stmt.charAt(++offset); char c3 = stmt.charAt(++offset);
codereview_java_data_2005
.load(media.getImageLocation()) .apply(RequestOptions.diskCacheStrategyOf(ApGlideSettings.AP_DISK_CACHE_STRATEGY)) .submit(iconSize, iconSize) - .get(); views.setImageViewBitmap(R.id.imgvCover, icon); } catch (Throwable tr) { Log.e(TAG, "Error loading the media icon for the widget", tr); If you use something like `.get(500, TimeUnit.MILLISECONDS)`, you can make sure that loading the icon does not cause "Application not responding" errors. I think 500ms are a reasonable maximum duration because the widget is updated every 1 second. .load(media.getImageLocation()) .apply(RequestOptions.diskCacheStrategyOf(ApGlideSettings.AP_DISK_CACHE_STRATEGY)) .submit(iconSize, iconSize) + .get(500, TimeUnit.MILLISECONDS); views.setImageViewBitmap(R.id.imgvCover, icon); } catch (Throwable tr) { Log.e(TAG, "Error loading the media icon for the widget", tr);
codereview_java_data_2011
return true; } public void discoverChildren() { if (isDiscovered()) { return; } @valib why remove the `isAddGlobally`? It is what prevents the startup scan from taking up memory that is never released return true; } + @Override public void discoverChildren() { + discoverChildren(true); + } + + public void discoverChildren(boolean isAddGlobally) { if (isDiscovered()) { return; }
codereview_java_data_2020
private final boolean isUp; private final int maxSession; private final String capabilities; public Node(UUID id, URI uri, Nit: Make this a private constant in the class, as some of the state picked up by reflection is stored. private final boolean isUp; private final int maxSession; private final String capabilities; + private static final Json JSON = new Json(); + public Node(UUID id, URI uri,
codereview_java_data_2023
* checkpointed files were actually committed or not. {@code --allowNonRestoredState} can lead to data loss if the * Iceberg commit failed in the last completed checkpoints. * - * @param newPrefix defines the iceberg table's key. * @return {@link Builder} to connect the iceberg table. */ public Builder uidPrefix(String newPrefix) { > @param newPrefix defines the iceberg table's key. I think we will need a correct parameter doc for this. * checkpointed files were actually committed or not. {@code --allowNonRestoredState} can lead to data loss if the * Iceberg commit failed in the last completed checkpoints. * + * @param newPrefix UID prefix for Flink sink operators * @return {@link Builder} to connect the iceberg table. */ public Builder uidPrefix(String newPrefix) {
codereview_java_data_2027
} int p = 0; int result = -1; - while (t.length() >= p + slice.length()) { - int r = findSlice(t, p, slice); if (r < 0) { return result; } we do not need to check this whole if - we've already done it in lastIndexOfSlice, right? } int p = 0; int result = -1; + final int maxPtr = t.length() - slice.length(); + while (p <= maxPtr) { + int r = findSlice(t, p, maxPtr, slice); if (r < 0) { return result; }
codereview_java_data_2028
* @return {@code true} if {@code find()} implementation performs scan over all * index, {@code false} if {@code find()} performs the fast lookup */ - boolean isFindSlow(); /** * Find a row or a list of rows and create a cursor to iterate over the isFindSlow -> isFindUsingFullTableScan * @return {@code true} if {@code find()} implementation performs scan over all * index, {@code false} if {@code find()} performs the fast lookup */ + boolean isFindUsingFullTableScan(); /** * Find a row or a list of rows and create a cursor to iterate over the
codereview_java_data_2030
@Override public Capabilities getCapabilities() { - return this.capabilities; } @Override This `this` isn't needed. Generally, we only use the `this` keyword where it makes code unambiguous. @Override public Capabilities getCapabilities() { + return capabilities; } @Override
codereview_java_data_2032
&& subclassDescription.getXmlLang() != null) { description = subclassDescription.getValue(); } - subItems.add(new DepictedItem(label, description, "", false,entityId )); Timber.e(label); } } formatting a tiny bit off in this line, spaces after `,`, no space before `)` && subclassDescription.getXmlLang() != null) { description = subclassDescription.getValue(); } + subItems.add(new DepictedItem(label, description, "", false, entityId)); Timber.e(label); } }
codereview_java_data_2036
@Override protected void configure() { - install(new SingularityServiceModule()); } @Provides side note to bringing in this dep, installing this module would also likely start up a number of pollers/db connections/zk connections/etc which we don't want @Override protected void configure() { } @Provides
codereview_java_data_2044
flatModules.add(toFlatModule(m)); } - scala.collection.Set<Module> koreModules = FlatModule.toModule(immutable(flatModules), Set()); return Constructors.Definition( koreModules.find(x -> x.name().equals(mainModuleName)) .getOrElse(() -> { throw new AssertionError("Could not find main module name: " + mainModuleName); }), Will this assertion error print out the JSON file that was being parsed or other source location information? Is it possible to? IIRC, assertion errors only produce stack dumps? flatModules.add(toFlatModule(m)); } + scala.collection.Set<Module> koreModules = FlatModule.toModules(immutable(flatModules), Set()); return Constructors.Definition( koreModules.find(x -> x.name().equals(mainModuleName)) .getOrElse(() -> { throw new AssertionError("Could not find main module name: " + mainModuleName); }),
codereview_java_data_2049
*/ public final void setClockSkew(Duration clockSkew) { Assert.notNull(clockSkew, "clockSkew cannot be null"); - Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0"); this.clockSkew = clockSkew; } Let's remove `MINIMUM_CLOCK_SKEW` and update the assertion as follows: `Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");` */ public final void setClockSkew(Duration clockSkew) { Assert.notNull(clockSkew, "clockSkew cannot be null"); this.clockSkew = clockSkew; }
codereview_java_data_2051
final JsonRpcRequest request = new JsonRpcRequest(JSON_RPC_VERSION, TXPOOL_PENDING_TRANSACTIONS_METHOD, new Object[] {}); - TransactionInfo local = createTransactionInfo(true); - TransactionInfo secondLocal = createTransactionInfo(true); - TransactionInfo remote = createTransactionInfo(false); when(pendingTransactions.maxSize()).thenReturn(123L); when(pendingTransactions.getTransactionInfo()) .thenReturn(Sets.newHashSet(local, secondLocal, remote)); nit: These should all be final. final JsonRpcRequest request = new JsonRpcRequest(JSON_RPC_VERSION, TXPOOL_PENDING_TRANSACTIONS_METHOD, new Object[] {}); + final TransactionInfo local = createTransactionInfo(true); + final TransactionInfo secondLocal = createTransactionInfo(true); + final TransactionInfo remote = createTransactionInfo(false); when(pendingTransactions.maxSize()).thenReturn(123L); when(pendingTransactions.getTransactionInfo()) .thenReturn(Sets.newHashSet(local, secondLocal, remote));
codereview_java_data_2052
/** * MediaSource based on local image files. Currently, this MediaSource expects - * a series of H264 frames located somewhere within an Android Assets folder. */ public class ImageFileMediaSource implements MediaSource { // Codec private data could be extracted using gstreamer plugin android samples folder and link to that sample would be nice! /** * MediaSource based on local image files. Currently, this MediaSource expects + * a series of H264 frames located within an Android Assets folder. + * See https://github.com/awslabs/aws-sdk-android-samples/tree/main/AmazonKinesisVideoDemoApp/src/main/assets/sample_frames */ public class ImageFileMediaSource implements MediaSource { // Codec private data could be extracted using gstreamer plugin
codereview_java_data_2053
log.error("ScheduledTask updateNameServerAddressList exception", e); } } - }, 1, 1, TimeUnit.MINUTES); } if (this.brokerConfig.getNamesrvAddr() != null) { It would be better to keep consistent with the scheduled tasks in org.apache.rocketmq.broker.BrokerController#initialize(fetchNameServerAddr task) log.error("ScheduledTask updateNameServerAddressList exception", e); } } + }, 1000 * 10, 1000 * 60 * 2, TimeUnit.MILLISECONDS); } if (this.brokerConfig.getNamesrvAddr() != null) {
codereview_java_data_2061
String.format(selectExprFormat, URI_DETAIL, FILE_PATH_ONLY, FILE_PATH_ONLY), // file path only String.format(selectExprFormat, URI_DETAIL, FILE_PATH, FILE_PATH)); // fully qualified path } - - static StructType fileDetailStructType() { - StructType customStructType = new StructType(); - customStructType = customStructType.add(FILE_PATH_ONLY, DataTypes.StringType, false); - customStructType = customStructType.add(FILE_PATH, DataTypes.StringType, false); - - return customStructType; - } } This should probably be a final private static field String.format(selectExprFormat, URI_DETAIL, FILE_PATH_ONLY, FILE_PATH_ONLY), // file path only String.format(selectExprFormat, URI_DETAIL, FILE_PATH, FILE_PATH)); // fully qualified path } }
codereview_java_data_2062
import com.hazelcast.nio.IOUtil; import javax.annotation.Nonnull; -import java.io.IOException; import java.util.Map.Entry; import static com.hazelcast.jet.Util.entry; you can move `IOUtil.decompress` out and call it with uncheckCall, this way it's more explicit. import com.hazelcast.nio.IOUtil; import javax.annotation.Nonnull; import java.util.Map.Entry; import static com.hazelcast.jet.Util.entry;
codereview_java_data_2064
"com.fsck.k9.activity.MessageCompose.quotedTextFormat"; private static final String STATE_KEY_NUM_ATTACHMENTS_LOADING = "numAttachmentsLoading"; private static final String STATE_KEY_WAITING_FOR_ATTACHMENTS = "waitingForAttachments"; - private static final String STATE_FIRST_TIME_EMPTY_SUBJECT = "firstTimeEmpySubject"; private static final String LOADER_ARG_ATTACHMENT = "attachment"; private static final String FRAGMENT_WAITING_FOR_ATTACHMENT = "waitingForAttachment"; Typo, should read `firstTimeEmptySubject` "com.fsck.k9.activity.MessageCompose.quotedTextFormat"; private static final String STATE_KEY_NUM_ATTACHMENTS_LOADING = "numAttachmentsLoading"; private static final String STATE_KEY_WAITING_FOR_ATTACHMENTS = "waitingForAttachments"; + private static final String STATE_FIRST_TIME_EMPTY_SUBJECT = "firstTimeEmptySubject"; private static final String LOADER_ARG_ATTACHMENT = "attachment"; private static final String FRAGMENT_WAITING_FOR_ATTACHMENT = "waitingForAttachment";
codereview_java_data_2076
cleanImmediately = false; { - String[] storePaths; String commitLogStorePath = DefaultMessageStore.this.getMessageStoreConfig().getStorePathCommitLog(); - if (commitLogStorePath.contains(MessageStoreConfig.MULTI_PATH_SPLITTER)) { - storePaths = commitLogStorePath.trim().split(MessageStoreConfig.MULTI_PATH_SPLITTER); - } else { - storePaths = new String[]{commitLogStorePath}; - } - Set<String> fullStorePath = new HashSet<>(); double minPhysicRatio = 100; String minStorePath = null; not necessary if branch, could use the same code with MULTI_PATH branch cleanImmediately = false; { String commitLogStorePath = DefaultMessageStore.this.getMessageStoreConfig().getStorePathCommitLog(); + String[] storePaths = commitLogStorePath.trim().split(MessageStoreConfig.MULTI_PATH_SPLITTER); Set<String> fullStorePath = new HashSet<>(); double minPhysicRatio = 100; String minStorePath = null;
codereview_java_data_2101
import org.springframework.context.annotation.Configuration; /** - * Creates TaskPlatform implementations to launch tasks on cloud foundry * @author Mark Pollack */ @Configuration update the docs to state `launch or schedule tasks` import org.springframework.context.annotation.Configuration; /** + * Creates TaskPlatform implementations to launch/schedule tasks on Cloud Foundry. * @author Mark Pollack */ @Configuration
codereview_java_data_2136
private static AdminApplication application; - private static JLineShellComponent shell; - private static CloudDataShell cloudDataShell; /** It's worth adding a delegating stop() in the CloudDataShell, thus no need to have both the shell and cloudDataShell fields? (could just have the CloudDataShell assigned to a 'shell' field instead) private static AdminApplication application; private static CloudDataShell cloudDataShell; /**
codereview_java_data_2142
transactions = new Transactions(accounts); web3 = new Web3(new Web3Transactions()); pantheon = new PantheonNodeFactory(); - contract = new ContractVerifier(accounts.getPrimaryBenefactor()); } @After NIT: naming this variable as `contract` can be misleading. Shouldn't we name it `contractVerifier`? transactions = new Transactions(accounts); web3 = new Web3(new Web3Transactions()); pantheon = new PantheonNodeFactory(); + contractVerifier = new ContractVerifier(accounts.getPrimaryBenefactor()); } @After
codereview_java_data_2149
final boolean devMode, final GenesisConfigProvider genesisConfigProvider, final Boolean p2pEnabled, - final boolean discovery) { this.name = name; this.miningParameters = miningParameters; this.jsonRpcConfiguration = jsonRpcConfiguration; Nitpick: Field that's being set is `Boolean`, this is `boolean`. Should probably be the former. final boolean devMode, final GenesisConfigProvider genesisConfigProvider, final Boolean p2pEnabled, + final Boolean discoveryEnabled) { this.name = name; this.miningParameters = miningParameters; this.jsonRpcConfiguration = jsonRpcConfiguration;
codereview_java_data_2154
Timber.d("Contributions tab selected"); tabLayout.getTabAt(CONTRIBUTIONS_TAB_POSITION).select(); isContributionsFragmentVisible = true; - ((NearbyParentFragment)contributionsActivityPagerAdapter.getItem(NEARBY_TAB_POSITION)).hideKeyboard(); updateMenuItem(); break; case NEARBY_TAB_POSITION: Why not make a function in utils & call it from the activity and not involve the NearbyFragment? Timber.d("Contributions tab selected"); tabLayout.getTabAt(CONTRIBUTIONS_TAB_POSITION).select(); isContributionsFragmentVisible = true; + ViewUtil.hideKeyboard(tabLayout.getRootView()); updateMenuItem(); break; case NEARBY_TAB_POSITION:
codereview_java_data_2157
sortOrder = select.getSortOrder(); } item = table.getBestPlanItem(s, masks, filters, filter, sortOrder); // The more index conditions, the earlier the table. // This is to ensure joins without indexes run quickly: // x (x.a=10); y (x.b=y.b) - see issue 113 Probably there was a bug because `join.getBestPlanItem` was called with the same level. As far as I understand it must be called with its own level. sortOrder = select.getSortOrder(); } item = table.getBestPlanItem(s, masks, filters, filter, sortOrder); + item.setMasks(masks); // The more index conditions, the earlier the table. // This is to ensure joins without indexes run quickly: // x (x.a=10); y (x.b=y.b) - see issue 113
codereview_java_data_2202
throw new RuntimeException(e); } } - if (pass != null) { - return new PasswordToken(pass.value); - } - - return null; } @Parameter(names = {"-z", "--keepers"}, description = "Comma separated list of zookeeper hosts (host:port,host:port)") This becomes simpler too. Either we throw an RTE from the attempt to get a password, or we create a `PasswordToken` with the results. This method always gets to return a non-null value (woo!). throw new RuntimeException(e); } } + return new PasswordToken(pass.value); } @Parameter(names = {"-z", "--keepers"}, description = "Comma separated list of zookeeper hosts (host:port,host:port)")
codereview_java_data_2208
try { wallpaperManager.setBitmap(bitmap); ViewUtil.showLongToast(context, context.getString(R.string.wallpaper_set_successfully)); - if (progressDialog.isShowing() && progressDialog != null) { progressDialog.dismiss(); } } catch (IOException e) { flip the conditions, null check should be done before try { wallpaperManager.setBitmap(bitmap); ViewUtil.showLongToast(context, context.getString(R.string.wallpaper_set_successfully)); + if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } } catch (IOException e) {
codereview_java_data_2212
@Override protected void onPostExecute(Contribution contribution) { super.onPostExecute(contribution); - //temporarily disabled for debugging - //uploadService.queue(UploadService.ACTION_UPLOAD_FILE, contribution); onComplete.onUploadStarted(contribution); } }); I don't think we want to commit this. @Override protected void onPostExecute(Contribution contribution) { super.onPostExecute(contribution); + uploadService.queue(UploadService.ACTION_UPLOAD_FILE, contribution); onComplete.onUploadStarted(contribution); } });
codereview_java_data_2214
import net.sourceforge.pmd.cpd.internal.JavaCCTokenizer; import net.sourceforge.pmd.lang.TokenManager; import net.sourceforge.pmd.lang.vf.ast.VfTokenManager; /** * @author sergey.gorbaty We need to skip the BOM to preserve same behavior... import net.sourceforge.pmd.cpd.internal.JavaCCTokenizer; import net.sourceforge.pmd.lang.TokenManager; import net.sourceforge.pmd.lang.vf.ast.VfTokenManager; +import net.sourceforge.pmd.util.IOUtil; /** * @author sergey.gorbaty
codereview_java_data_2220
public final class TypeInferenceResolver { - public static class ResolutionFailed extends RuntimeException { } It's a best practice to finish all exception names with `Exception`... this hsould probably be `ResolutionFailedException` public final class TypeInferenceResolver { + public static class ResolutionFailedException extends RuntimeException { }
codereview_java_data_2221
package tech.pegasys.pantheon.consensus.ibft.jsonrpc.methods; import tech.pegasys.pantheon.consensus.ibft.IbftBlockInterface; -import tech.pegasys.pantheon.ethereum.chain.Blockchain; import tech.pegasys.pantheon.ethereum.core.BlockHeader; import tech.pegasys.pantheon.ethereum.jsonrpc.internal.JsonRpcRequest; import tech.pegasys.pantheon.ethereum.jsonrpc.internal.methods.AbstractBlockParameterMethod; Having both BlockChainQueries AND Blockchain is a smell - i.e. I'm assuming the queries should hide the underlying blockchain. I _suspect_ the smell is that AbstractBlockParameterMethod should actually be 2 things: 1. AbstractJsonParameterHandler 2.BlockchainQuerier That way, this class can re-use the AbstractJsonParameterHandler to do the json bits, but then wouldn't need both a BlockchainQuery AND Blockchain... package tech.pegasys.pantheon.consensus.ibft.jsonrpc.methods; import tech.pegasys.pantheon.consensus.ibft.IbftBlockInterface; import tech.pegasys.pantheon.ethereum.core.BlockHeader; import tech.pegasys.pantheon.ethereum.jsonrpc.internal.JsonRpcRequest; import tech.pegasys.pantheon.ethereum.jsonrpc.internal.methods.AbstractBlockParameterMethod;
codereview_java_data_2226
"Archive any files/directories instead of moving to the HDFS trash or deleting."), GC_TRACE_PERCENT("gc.trace.percent", "0.01", PropertyType.FRACTION, "Percent of gc cycles to trace"), - GC_USE_FULL_COMPACTION("gc.use.full.compaction", "true", PropertyType.BOOLEAN, - "When gc completes, initiate a full compaction of the metadata table if set," - + " otherwise flush"), // properties that are specific to the monitor server behavior MONITOR_PREFIX("monitor.", null, PropertyType.PREFIX, It might be better to make this more like the durability setting, with three options: `COMPACT`, `FLUSH`, `NONE` It could be called `gc.post.action` or similar. "Archive any files/directories instead of moving to the HDFS trash or deleting."), GC_TRACE_PERCENT("gc.trace.percent", "0.01", PropertyType.FRACTION, "Percent of gc cycles to trace"), + GC_USE_FULL_COMPACTION("gc.post.metadata.action", "compact", PropertyType.GC_POST_ACTION, + "When the gc runs it can make a lot of changes to the metadata, on completion, " + + " to force the changes to be written to disk, the metadata and root tables can be flushed" + + " and possibly compacted. Legal values are: compact - which both flushes and compacts the" + + " metadata; flush - which flushes only (compactions may be triggered if required); or none"), // properties that are specific to the monitor server behavior MONITOR_PREFIX("monitor.", null, PropertyType.PREFIX,
codereview_java_data_2236
this.project = project; project.getPluginManager().withPlugin("java", plugin -> { - project.getTasks().register("formatDiff", FormatDiffTask.class, task -> { - task.setDescription("Format only chunks of files that appear in git diff"); - task.setGroup("Formatting"); - task.onlyIf(t -> palantirJavaFormatterEnabled(project)); - }); project.getPluginManager().apply("com.diffplug.gradle.spotless"); Path eclipseXml = eclipseConfigFile(project); Are we able to put these in the `FormatDiffTask` itself? this.project = project; project.getPluginManager().withPlugin("java", plugin -> { + project.getTasks().register("formatDiff", FormatDiffTask.class); project.getPluginManager().apply("com.diffplug.gradle.spotless"); Path eclipseXml = eclipseConfigFile(project);
codereview_java_data_2237
@Override public boolean isUserCompaction() { return userCompaction; } A sanity check like the one in `isFullMajorCompaction()` that checks if `scope` is `majc` would be nice. @Override public boolean isUserCompaction() { + if (scope != IteratorScope.majc) + throw new IllegalStateException( + "Asked about user initiated compaction type when scope is " + scope); return userCompaction; }
codereview_java_data_2242
/** Execution context for draining queued ibft events and applying them to a maintained state */ public class IbftProcessor implements Runnable { - private static final Logger LOG = LogManager.getLogger(IbftEventQueue.class); private final IbftEventQueue incomingQueue; private final ScheduledExecutorService roundTimerExecutor; Sometimes we are using getLogger(), getLogger(\<this class\>), and getLogger(\<some other class\>). Are the two calls to getLogger(\<some other class\>) mistakes? (this one and BlockTransactionSelector). Is there any reason we shouldn't just settle on getLogger() as it protects us from copy paste errors? /** Execution context for draining queued ibft events and applying them to a maintained state */ public class IbftProcessor implements Runnable { + private static final Logger LOG = LogManager.getLogger(); private final IbftEventQueue incomingQueue; private final ScheduledExecutorService roundTimerExecutor;
codereview_java_data_2244
private void analyzeTables() { // take a local copy and clear because in rare cases we can call - // back into markTableForAnalyzer while iterating here HashSet<Table> tablesToAnalyzeLocal = tablesToAnalyze; tablesToAnalyze = null; int rowCount = getDatabase().getSettings().analyzeSample / 10; `markTableForAnalyze` (without r) private void analyzeTables() { // take a local copy and clear because in rare cases we can call + // back into markTableForAnalyze while iterating here HashSet<Table> tablesToAnalyzeLocal = tablesToAnalyze; tablesToAnalyze = null; int rowCount = getDatabase().getSettings().analyzeSample / 10;
codereview_java_data_2247
/*case ONEDRIVE: signInOneDrive(); break;*/ - default://do nothing } } else { AlertDialog alertDialog = new AlertDialog.Builder(this) Please don't leave an empty default /*case ONEDRIVE: signInOneDrive(); break;*/ } } else { AlertDialog alertDialog = new AlertDialog.Builder(this)
codereview_java_data_2249
@Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - return isSensibleDirectoryToEnter(dir)?CONTINUE:SKIP_SUBTREE; } }); return this; I would add a few spaces around operators here @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + return isSensibleDirectoryToEnter(dir) ? CONTINUE : SKIP_SUBTREE; } }); return this;
codereview_java_data_2261
public String toString() { return String.format( "Top rising stocks:%n%s\nTop falling stocks:%n%s", - topIncrease.stream().map(kwr -> String.format(" %s by %.5f", kwr.key(), kwr.result())) .collect(joining("\n")), - topDecrease.stream().map(kwr -> String.format(" %s by %.5f", kwr.key(), kwr.result())) .collect(joining("\n")) ); } Can't we make the price differences larger instead of adding decimals? public String toString() { return String.format( "Top rising stocks:%n%s\nTop falling stocks:%n%s", + topIncrease.stream().map(kwr -> String.format(" %s by %.2f%%", kwr.key(), 100d * kwr.result())) .collect(joining("\n")), + topDecrease.stream().map(kwr -> String.format(" %s by %.2f%%", kwr.key(), 100d * kwr.result())) .collect(joining("\n")) ); }
codereview_java_data_2265
} @Override - public void unSubscriber(Subscriber subscriber) { subscribers.remove(subscriber); } rename to remove maybe better? } @Override + public void removeSubscriber(Subscriber subscriber) { subscribers.remove(subscriber); }
codereview_java_data_2268
@Override public OverloadSelectionResult getOverloadSelectionInfo() { - getTypeMirror(); // force evaluation - return Objects.requireNonNull(result, "null result"); } void setOverload(OverloadSelectionResult result) { I think, we should be careful to add such side effects.... getTypeMirror() sounds innocent, but obviously it calls back setOverload... so it really does resolve types+overloads and then returns the resolved type... that's probably a result of doing lazy typeres, isn't it? btw: this method throw a NPE, if no overloadselectionresult could be resolved, but the previous class returns null (with an assert check). Is this intended? @Override public OverloadSelectionResult getOverloadSelectionInfo() { + forceTypeResolution(); + return assertNonNullAfterTypeRes(result); } void setOverload(OverloadSelectionResult result) {
codereview_java_data_2269
/** - * Retrieves the body of the declaration. * - * @return The body of the declaration */ List<ASTAnyTypeBodyDeclaration> getDeclarations(); Not sure: what is "the body of the declaration" I guess, it's something like: Gets all the declarations declared within the body of this type. Not so clear either... /** + * Retrieves the member declarations (fields, methods, classes, etc.) from the body of this type declaration. * + * @return The member declarations declared in this type declaration */ List<ASTAnyTypeBodyDeclaration> getDeclarations();
codereview_java_data_2270
*/ updater.updateState(upload.id, TransferState.WAITING_FOR_NETWORK); LOGGER.debug("Network Connection Interrupted: " + "Moving the TransferState to WAITING_FOR_NETWORK"); progressListener.progressChanged(new ProgressEvent(0)); return false; } Same as above. If `eventCode` is not being used anywhere should we consider removing it altogether from the `ProgressEvent` class? */ updater.updateState(upload.id, TransferState.WAITING_FOR_NETWORK); LOGGER.debug("Network Connection Interrupted: " + "Moving the TransferState to WAITING_FOR_NETWORK"); + ProgressEvent resetEvent = new ProgressEvent(0); + resetEvent.setEventCode(ProgressEvent.RESET_EVENT_CODE); progressListener.progressChanged(new ProgressEvent(0)); return false; }
codereview_java_data_2272
} ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, alternateUrlsTitleList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); - binding.spinnerAlternateUrls.setAdapter(adapter); - binding.spinnerAlternateUrls.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { selectedDownloadUrl = alternateUrlsList.get(position); What do you think about `alternateUrlsSpinner`? } ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, alternateUrlsTitleList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + viewBinding.spinnerAlternateUrls.setAdapter(adapter); + viewBinding.spinnerAlternateUrls.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { selectedDownloadUrl = alternateUrlsList.get(position);
codereview_java_data_2274
} inflater.inflate(R.menu.conversation, menu); - if(isSingleConversation()){ inflater.inflate(R.menu.conversation_new_group,menu); } There should be spaces between `if` and `(isSingle...)` and between `...Conversation())` and `{` So it should read as: `if (isSingleConversation()) {` } inflater.inflate(R.menu.conversation, menu); + if (isSingleConversation()) { inflater.inflate(R.menu.conversation_new_group,menu); }
codereview_java_data_2285
if (wasDST(cal)) { LoopPlugin loopPlugin = LoopPlugin.getPlugin(); - if (loopPlugin.isSuspended()) { warnUser(Notification.DST_LOOP_DISABLED, MainApp.gs(R.string.dst_loop_disabled_warning)); } else { log.debug("Loop already suspended"); I think it should be: ```suggestion if (!loopPlugin.isSuspended()) { ``` if (wasDST(cal)) { LoopPlugin loopPlugin = LoopPlugin.getPlugin(); + if (!loopPlugin.isSuspended()) { warnUser(Notification.DST_LOOP_DISABLED, MainApp.gs(R.string.dst_loop_disabled_warning)); } else { log.debug("Loop already suspended");
codereview_java_data_2295
return value + " " + this.symbol; case ON_OFF: boolean booleanValue = (Boolean) value; - return booleanValue ? "ON" : "OFF"; - case HOUR_DATE: - case MINUTE_SECOND: - case MONTH_YEAR: } return "FORMAT_ERROR"; // should never happen, if 'switch' is complete } This method will always resturn "FORMAT_ERROR" for those types, instead of the value... return value + " " + this.symbol; case ON_OFF: boolean booleanValue = (Boolean) value; + return booleanValue ? "ON" : "OFF"; } return "FORMAT_ERROR"; // should never happen, if 'switch' is complete }
codereview_java_data_2303
package com.hazelcast.jet.cdc.impl; import com.hazelcast.function.FunctionEx; -import com.hazelcast.jet.cdc.ChangeEvent; import com.hazelcast.jet.core.Processor; import com.hazelcast.jet.pipeline.SourceBuilder; import com.hazelcast.jet.pipeline.StreamSource; this is a private class but extended by a public one. You can just convert this class to non-abstract and use it inside the actual builders, then you don't need this `SELF` either. package com.hazelcast.jet.cdc.impl; import com.hazelcast.function.FunctionEx; +import com.hazelcast.jet.cdc.ChangeRecord; import com.hazelcast.jet.core.Processor; import com.hazelcast.jet.pipeline.SourceBuilder; import com.hazelcast.jet.pipeline.StreamSource;
codereview_java_data_2305
* @param file a DataFile to remove from the table * @return this for method chaining */ - DeleteFiles deleteFile(DataFile file); /** * Delete files that match an {@link Expression} on data rows from the table. I don't think it is necessary to remove the default implementation. Overriding it in `StreamingDelete` should work just fine without causing a binary compatibility change. * @param file a DataFile to remove from the table * @return this for method chaining */ + default DeleteFiles deleteFile(DataFile file) { + deleteFile(file.path()); + return this; + } /** * Delete files that match an {@link Expression} on data rows from the table.
codereview_java_data_2306
return false; } - MetricOptions version = (MetricOptions) o; - return options.equals(version.options); } rename version to "other" - the version might be confusing in the future :) return false; } + MetricOptions other = (MetricOptions) o; + return options.equals(other.options); }
codereview_java_data_2314
package org.flowable.editor.language.xml; import java.util.List; -import org.assertj.core.api.Assertions; import org.flowable.bpmn.converter.BpmnXMLConverter; import org.flowable.bpmn.model.Activity; import org.flowable.bpmn.model.BpmnModel; If you staticly import `assertThat` then lines like this can be written as `assertThat(dataInputAssociations),isNotEmpty()`. There are 2 other occurrences in this test. package org.flowable.editor.language.xml; +import static org.assertj.core.api.Assertions.assertThat; + import java.util.List; import org.flowable.bpmn.converter.BpmnXMLConverter; import org.flowable.bpmn.model.Activity; import org.flowable.bpmn.model.BpmnModel;
codereview_java_data_2318
JsonNode rootNode = objectMapper.readTree(response.getEntity().getContent()); closeResponse(response); assertThatJson(rootNode) - .when(Option.IGNORING_EXTRA_FIELDS, Option.IGNORING_EXTRA_ARRAY_ITEMS) .isEqualTo("{" + "data: [ {" + " id: '" + processInstance3.getId() + "'" Why ignoring extra array items, when we have to have 3 only? JsonNode rootNode = objectMapper.readTree(response.getEntity().getContent()); closeResponse(response); assertThatJson(rootNode) + .when(Option.IGNORING_EXTRA_FIELDS) .isEqualTo("{" + "data: [ {" + " id: '" + processInstance3.getId() + "'"
codereview_java_data_2323
longitude.setValue(JsonHelper.safeGetDouble(d, "longitude")); distance.setValue(JsonHelper.safeGetDouble(d, "distance")); name.setValue(JsonHelper.safeGetString(d, "name")); - mode.setValue(JsonHelper.safeGetString(d, "mode")); lastRun = JsonHelper.safeGetLong(d, "lastRun"); } catch (Exception e) { e.printStackTrace(); as thi is upgrading current class you must provide default value here longitude.setValue(JsonHelper.safeGetDouble(d, "longitude")); distance.setValue(JsonHelper.safeGetDouble(d, "distance")); name.setValue(JsonHelper.safeGetString(d, "name")); + mode.setValue(JsonHelper.safeGetString(d, "mode", modeEntered)); lastRun = JsonHelper.safeGetLong(d, "lastRun"); } catch (Exception e) { e.printStackTrace();
codereview_java_data_2327
.build(); ScheduledExecutorService scheduledExecutor = builder.scheduledExecutor; ThreadFactory threadFactory = new ThreadFactoryBuilder().threadNamePrefix("DefaultSqsBatchManager").build(); - this.executor = createDefaultExecutor(threadFactory); this.sendMessageBatchManager = BatchManager.builder(SendMessageRequest.class, SendMessageResponse.class, SendMessageBatchResponse.class) .batchFunction(sendMessageBatchFunction(client, executor)) We probably should only create a default executor if `builder.executor` is null and only close the executor if it's the default one created by the class .build(); ScheduledExecutorService scheduledExecutor = builder.scheduledExecutor; ThreadFactory threadFactory = new ThreadFactoryBuilder().threadNamePrefix("DefaultSqsBatchManager").build(); + if (builder.executor == null) { + this.executor = createDefaultExecutor(threadFactory); + this.createdExecutor = true; + } else { + this.executor = builder.executor; + this.createdExecutor = false; + } this.sendMessageBatchManager = BatchManager.builder(SendMessageRequest.class, SendMessageResponse.class, SendMessageBatchResponse.class) .batchFunction(sendMessageBatchFunction(client, executor))
codereview_java_data_2344
* If true, a default {@link OAuth2AuthorizedClient} can be discovered from the current Authentication. It is * recommended to be cautious with this feature since all HTTP requests will receive the access token if it can be * resolved from the current Authentication. - * * @param defaultOAuth2AuthorizedClient true if a default {@link OAuth2AuthorizedClient} should be used, else false. * Default is false. */ There are no code changes in this file - only formatting changes. Or am I missing something? * If true, a default {@link OAuth2AuthorizedClient} can be discovered from the current Authentication. It is * recommended to be cautious with this feature since all HTTP requests will receive the access token if it can be * resolved from the current Authentication. * @param defaultOAuth2AuthorizedClient true if a default {@link OAuth2AuthorizedClient} should be used, else false. * Default is false. */
codereview_java_data_2348
* <img src="doc-files/binaryExpr_60x.svg" /> * </figure> */ -public class ASTInfixExpression extends AbstractJavaExpr implements InternalInterfaces.JSingleChildNode<ASTExpression>, LeftRecursiveNode, InternalInterfaces.BinaryExpressionLike { private BinaryOp operator; Removing final opens up this class for subclassing (which we need for the InstanceOfExpression). Maybe we can introduce a common "AbstractInfixExpression" and have ASTInfixExpression and ASTInstanceOfExpression both subclass this one and be final again? * <img src="doc-files/binaryExpr_60x.svg" /> * </figure> */ +public final class ASTInfixExpression extends AbstractJavaExpr implements InternalInterfaces.JSingleChildNode<ASTExpression>, LeftRecursiveNode, InternalInterfaces.BinaryExpressionLike { private BinaryOp operator;
codereview_java_data_2349
public class ObservableRepository { - public static final String COMPLETED_OBSERVABLES_LIST_NAME = INTERNAL_JET_OBJECTS_PREFIX + "completedObservables"; private static final int MAX_CLEANUP_ATTEMPTS_AT_ONCE = 10; private final JetInstance jet; private final IList<Tuple2<String, Long>> completedObservables; private final long expirationTime; Does the user have a way to manually delete the observable? They can have non-negligible size and you can't get rid of them. When the client is done processing it, it should be able to delete it. This is akin to file processing: they will be closed in `finalize`, but you should close them early when you're done. public class ObservableRepository { + private static final String COMPLETED_OBSERVABLES_LIST_NAME = INTERNAL_JET_OBJECTS_PREFIX + "completedObservables"; private static final int MAX_CLEANUP_ATTEMPTS_AT_ONCE = 10; + private final JetInstance jet; private final IList<Tuple2<String, Long>> completedObservables; private final long expirationTime;
codereview_java_data_2352
public static final SqlFunction CURRENT_TIMESTAMP = new SqlAbstractTimeFunction("CURRENT_TIMESTAMP", SqlTypeName.TIMESTAMP); - /** - * The <code>CURRENT_DATETIME [(<i>precision</i>)]</code> function. - */ - public static final SqlFunction CURRENT_DATETIME = - new SqlAbstractTimeFunction("CURRENT_DATETIME", SqlTypeName.TIMESTAMP); - /** * The <code>CURRENT_DATE</code> function. */ Does `CURRENT_DATETIME` belong to the SQL standard ? public static final SqlFunction CURRENT_TIMESTAMP = new SqlAbstractTimeFunction("CURRENT_TIMESTAMP", SqlTypeName.TIMESTAMP); /** * The <code>CURRENT_DATE</code> function. */
codereview_java_data_2355
TableScan scan, int numRowsPerRoot, int expectedTotalRows, - int numExtraCallsToHasNext) throws IOException { int totalRows = 0; try (VectorizedTableScanIterable itr = new VectorizedTableScanIterable(scan, numRowsPerRoot, false)) { CloseableIterator<ColumnarBatch> iterator = itr.iterator(); How does this test that the iterator is idempotent? It looks like this just tests that the batch size is correct. I think that this should also call `checkAllVectorValues` to ensure that the expected rows are the ones produced rather than relying on the total number of rows. TableScan scan, int numRowsPerRoot, int expectedTotalRows, + int numExtraCallsToHasNext, + List<String> columns) throws IOException { + Set<String> columnSet = ImmutableSet.copyOf(columns); + int rowIndex = 0; int totalRows = 0; try (VectorizedTableScanIterable itr = new VectorizedTableScanIterable(scan, numRowsPerRoot, false)) { CloseableIterator<ColumnarBatch> iterator = itr.iterator();
codereview_java_data_2385
public void sendBeat() throws IOException, InterruptedException { RaftPeer local = peers.local(); - if (ApplicationUtils.getStandaloneMode() || local.state != RaftPeer.State.LEADER){ return; } if (Loggers.RAFT.isDebugEnabled()) { There should be one blank between `)` and `{` please public void sendBeat() throws IOException, InterruptedException { RaftPeer local = peers.local(); + if (ApplicationUtils.getStandaloneMode() || local.state != RaftPeer.State.LEADER) { return; } if (Loggers.RAFT.isDebugEnabled()) {
codereview_java_data_2396
* The method {@link #upgradeRelativePaths(ServerContext, Ample.DataLevel)} was added for resolving * and replacing all relative tablet file paths found in metadata tables with absolute paths during * upgrade. Absolute paths are resolved by prefixing relative paths with a volume configured by the - * user in a the instance.volumes.upgrade.relative property, which is only used during an upgrade. * If any relative paths are found and this property is not configured, or if any resolved absolute * path does not correspond to a file that actually exists, the upgrade step fails and aborts * without making changes. See the property {@link Property#INSTANCE_VOLUMES_UPGRADE_RELATIVE} and ```suggestion * user in the instance.volumes.upgrade.relative property, which is only used during an upgrade. ``` * The method {@link #upgradeRelativePaths(ServerContext, Ample.DataLevel)} was added for resolving * and replacing all relative tablet file paths found in metadata tables with absolute paths during * upgrade. Absolute paths are resolved by prefixing relative paths with a volume configured by the + * user in the instance.volumes.upgrade.relative property, which is only used during an upgrade. * If any relative paths are found and this property is not configured, or if any resolved absolute * path does not correspond to a file that actually exists, the upgrade step fails and aborts * without making changes. See the property {@link Property#INSTANCE_VOLUMES_UPGRADE_RELATIVE} and
codereview_java_data_2400
Logger.verbose(Logger.tags("Plugin"), "To native (Cordova plugin): callbackId: " + callbackId + ", service: " + service + ", action: " + action + ", actionArgs: " + actionArgs); this.callCordovaPluginMethod(callbackId, service, action, actionArgs); - } else if (type != null && type.equals("js.error")) { Logger.error("JavaScript Error: " + jsonStr); } else { String pluginId = postData.getString("pluginId"); Did you mean to use the new `isJavaScriptError` bool here? Logger.verbose(Logger.tags("Plugin"), "To native (Cordova plugin): callbackId: " + callbackId + ", service: " + service + ", action: " + action + ", actionArgs: " + actionArgs); this.callCordovaPluginMethod(callbackId, service, action, actionArgs); + } else if (isJavaScriptError) { Logger.error("JavaScript Error: " + jsonStr); } else { String pluginId = postData.getString("pluginId");
codereview_java_data_2412
return visitor.union(schema, options); case ARRAY: - if (schema.getLogicalType() instanceof LogicalMap && AvroSchemaUtil.isKeyValueSchema(schema.getElementType())) { return visitor.array(schema, visit(schema.getElementType(), visitor)); } else { return visitor.array(schema, visitWithName("element", schema.getElementType(), visitor)); I think the solution should be a better check in `isKeyValueSchema`. If the logical type is `LogicalMap`, then it should not need additional requirements for the element type. return visitor.union(schema, options); case ARRAY: + if (schema.getLogicalType() instanceof LogicalMap) { return visitor.array(schema, visit(schema.getElementType(), visitor)); } else { return visitor.array(schema, visitWithName("element", schema.getElementType(), visitor));
codereview_java_data_2414
toInit = (Processor) initialized; } catch (ClassCastException e) { throw new IllegalArgumentException(String.format( - "The initialized object(%s) should be an instance of %s", initialized, Processor.class)); } if (processor instanceof ProcessorWrapper) { ((ProcessorWrapper) processor).setWrapped(toInit); do we want to pass the cause here, just in case? toInit = (Processor) initialized; } catch (ClassCastException e) { throw new IllegalArgumentException(String.format( + "The initialized object(%s) should be an instance of %s", initialized, Processor.class), e); } if (processor instanceof ProcessorWrapper) { ((ProcessorWrapper) processor).setWrapped(toInit);
codereview_java_data_2429
// Carry over the type from the declaration Class<?> nodeType = ((TypeNode) node.getNameDeclaration().getNode()).getType(); // FIXME : generic classes and class with generic super types could have the wrong type assigned here - if (nodeType != null && !isGeneric(nodeType)) { node.setType(nodeType); return super.visit(node, data); } is this fixme still valid after this added condition? // Carry over the type from the declaration Class<?> nodeType = ((TypeNode) node.getNameDeclaration().getNode()).getType(); // FIXME : generic classes and class with generic super types could have the wrong type assigned here + if (nodeType != null) { node.setType(nodeType); return super.visit(node, data); }