id
stringlengths
23
26
content
stringlengths
182
2.49k
codereview_java_data_6539
receivedMessages .values() .stream() - .map(message -> message.getSignedPayload()) .collect(Collectors.toList())); } else { throw new IllegalStateException("Unable to create RoundChangeCertificate at this time."); nit: can use method reference receivedMessages .values() .stream() + .map(RoundChange::getSignedPayload) .collect(Collectors.toList())); } else { throw new IllegalStateException("Unable to create RoundChangeCertificate at this time.");
codereview_java_data_6542
*/ package tech.pegasys.pantheon.metrics; public interface MetricCategory { String getName(); - boolean isApplicationSpecific(); } Instead of having a `boolean` here + the `applicationPrefix` configured on the `MetricsSystem`, what about just storing an `Optional<String> applicationPrefix` on `MetricsCategory`? */ package tech.pegasys.pantheon.metrics; +import java.util.Optional; + public interface MetricCategory { String getName(); + Optional<String> getAppliationPrefix(); }
codereview_java_data_6543
} private T readInternal(T struct, ColumnVector[] columnVectors, int row) { - for (int c = 0; c < readers.length; ++c) { - set(struct, c, reader(c).read(columnVectors[c], row)); } return struct; } Is `ColumnVector` still materialized? Is it possible to avoid reading that entirely? } private T readInternal(T struct, ColumnVector[] columnVectors, int row) { + for (int c = 0, vectorIndex = 0; c < readers.length; ++c) { + ColumnVector vector = isConstantField[c] ? null : columnVectors[vectorIndex++]; + set(struct, c, reader(c).read(vector, row)); } return struct; }
codereview_java_data_6547
import java.io.File; import java.net.URI; import java.util.List; import java.util.stream.Collectors; Should this be more explicit that the file doesn't exist at the specified location? I feel like this could be interpreted as "something went wrong", not "it wasn't there." import java.io.File; import java.net.URI; +import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors;
codereview_java_data_6549
// eth_sendTransaction specific error message ETH_SEND_TX_NOT_AVAILABLE( -32604, - "The method eth_sendTransaction is not supported. Use eth_sendRawTransaction with a supported signer, e.g. ethsigner."), // P2P related errors P2P_DISABLED(-32000, "P2P has been disabled. This functionality is not available"), I don't think this is quite right. Your options are: * Use eth_sendRawTransaction with Pantheon * Use eth_sendTransaction with a supported signer (eg, EthSigner) You can send eth_sendRawTransaction through EthSigner but there's no benefit because the transaction would already be signed. // eth_sendTransaction specific error message ETH_SEND_TX_NOT_AVAILABLE( -32604, + "The method eth_sendTransaction is not supported. Use eth_sendRawTransaction to send a signed transaction to Pantheon."), // P2P related errors P2P_DISABLED(-32000, "P2P has been disabled. This functionality is not available"),
codereview_java_data_6559
/** * Creates a key with the specified row, empty column family, empty column qualifier, empty column * visibility, timestamp {@link Long#MAX_VALUE}, and delete marker false. This constructor creates - * a copy of row. If you don't want to create a copy of row, you should call - * {@link Key#Key(byte[] row, byte[] cf, byte[] cq, byte[] cv, long ts, boolean deleted, boolean copy)} - * instead. * * @param row * row ID Could be made a bit shorter w/o loss of information. Something like : ``` To avoid copying, use {@link Key#Key(byte[] row, byte[] cf, byte[] cq, byte[] cv, long ts, boolean deleted, boolean copy)}. ``` /** * Creates a key with the specified row, empty column family, empty column qualifier, empty column * visibility, timestamp {@link Long#MAX_VALUE}, and delete marker false. This constructor creates + * a copy of row. + * + * To avoid copying, use {@link Key#Key(byte[] row, byte[] cf, byte[] cq, byte[] cv, + * long ts, boolean deleted, boolean copy)} instead. * * @param row * row ID
codereview_java_data_6563
long dateValue = fieldDateAndTime[0]; long timeNanosRetrieved = fieldDateAndTime[1]; - // Variable that contains the number of nanoseconds in 'hour', 'minute', - // etc. - long nanoInHour = 3_600_000_000_000l; - long nanoInMinute = 60_000_000_000l; - long nanoInSecond = 1_000_000_000l; - long nanoInMilliSecond = 1_000_000l; - long nanoInMicroSecond = 1_000l; - // Variable used to the time in nanoseconds of the date truncated. long timeNanos; There are two possibilities. 1. Use `switch` over string here, Java can do it and such switch should be more readable. 2. Use `getDatePart()` in caller to get a numeric constant. Use switch with these constants here. This should be even better. In this case you will need to add a mappings for `DECADE` and `CENTURY` later to common mappings like it was done for `EPOCH`. I'm not sure about `DECADE`, but mapping for `CENTURY` may be useful in another similar functions. Of course, if you're planning to implement these cases, it's not necessary to support all possible values right now. long dateValue = fieldDateAndTime[0]; long timeNanosRetrieved = fieldDateAndTime[1]; // Variable used to the time in nanoseconds of the date truncated. long timeNanos;
codereview_java_data_6564
final String topic = ClassUtils.getCanonicalName(subscribeType); EventPublisher eventPublisher = INSTANCE.publisherMap.get(topic); - if (eventPublisher == null) { - return false; } - eventPublisher.removeSubscriber(consumer); - return true; } /** I think the old implementation is better for readablilty final String topic = ClassUtils.getCanonicalName(subscribeType); EventPublisher eventPublisher = INSTANCE.publisherMap.get(topic); + if (eventPublisher != null) { + eventPublisher.removeSubscriber(consumer); + return true; } + return false; } /**
codereview_java_data_6574
import com.hazelcast.config.SerializerConfig; import com.hazelcast.jet.Observable; import com.hazelcast.jet.SimpleTestInClusterSupport; import com.hazelcast.jet.config.JetConfig; import com.hazelcast.jet.config.JobConfig; import com.hazelcast.jet.pipeline.Pipeline; We should not register the serializer for the cluster: the test is supposed to test that even if it's not set for the cluster, it works if it's set for the job. import com.hazelcast.config.SerializerConfig; import com.hazelcast.jet.Observable; import com.hazelcast.jet.SimpleTestInClusterSupport; +import com.hazelcast.jet.config.JetClientConfig; import com.hazelcast.jet.config.JetConfig; import com.hazelcast.jet.config.JobConfig; import com.hazelcast.jet.pipeline.Pipeline;
codereview_java_data_6577
final Object updateSync = new Object(); - public enum CHARTTYPE {PRE, BAS, IOB, COB, DEV, SEN} - ; private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor(); private static ScheduledFuture<?> scheduledUpdate = null; ... here the semicolon wanted to run away from the enum ;) final Object updateSync = new Object(); + public enum CHARTTYPE {PRE, BAS, IOB, COB, DEV, SEN}; private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor(); private static ScheduledFuture<?> scheduledUpdate = null;
codereview_java_data_6581
return commitSeal; } @Override public boolean equals(final Object o) { if (this == o) { what about the roundIdentifier stored in the baseclass? return commitSeal; } + @Override + public ConsensusRoundIdentifier getRoundIdentifier() { + return roundIdentifier; + } + @Override public boolean equals(final Object o) { if (this == o) {
codereview_java_data_6584
} else { final View notification=menu.findItem(R.id.notifications).getActionView(); txtViewCount=notification.findViewById(R.id.notification_count_badge); - txtViewCount.setText(String.valueOf(1)); } this.menu = menu; is this value hardcoded? } else { final View notification=menu.findItem(R.id.notifications).getActionView(); txtViewCount=notification.findViewById(R.id.notification_count_badge); + txtViewCount.setText(getNotificationCount()); } this.menu = menu;
codereview_java_data_6589
// log to standard Linux log location if (Platform.isLinux()) - if (checkCreateLogFileFolder(DEFAILT_LOG_FOLDER_LINUX)) return defaultLogFileDir; // log to profile directory if it is writable. Why having set `DEFAILT` ? typo ? // log to standard Linux log location if (Platform.isLinux()) + if (checkCreateLogFileFolder(DEFAULT_LOG_FOLDER_LINUX)) return defaultLogFileDir; // log to profile directory if it is writable.
codereview_java_data_6590
SymbolTable(5, "Symbol table"), DFA(6, "DFA"), TypeResolution(7, "Type resolution"), - MetricsVisitor(8, "Metrics visitor"), RuleChainVisit(9, "RuleChain visit"), Reporting(10, "Reporting"), RuleTotal(11, "Rule total"), Just a minor thing: I think, I wouldn't name this here Metrics*Visitor* - maybe just Metrics? Since "Visitor" is just an implementation detail... SymbolTable(5, "Symbol table"), DFA(6, "DFA"), TypeResolution(7, "Type resolution"), + MetricsVisitor(8, "Metrics"), RuleChainVisit(9, "RuleChain visit"), Reporting(10, "Reporting"), RuleTotal(11, "Rule total"),
codereview_java_data_6592
} } - private void queueLoad(HostAndPort server, KeyExtent extent, Map<String,MapFileInfo> thriftImports) { if (!thriftImports.isEmpty()) { loadMsgs.increment(server, 1); This is a confusing name, since we have different meanings for the term "load". I assume you are "loading the queue" here but perhaps a name like addToQueue may be less confusing. } } + private void addToQueue(HostAndPort server, KeyExtent extent, Map<String,MapFileInfo> thriftImports) { if (!thriftImports.isEmpty()) { loadMsgs.increment(server, 1);
codereview_java_data_6593
} /** - * Gets the coordinates of the file. - * </p> - * Presumably indicates upload location. * @return file coordinates as a LatLng */ public @Nullable It is actually the location where the picture was taken :-) } /** + * Gets the coordinates of where the file was created. * @return file coordinates as a LatLng */ public @Nullable
codereview_java_data_6596
public static void validate(Iterable<Entry<String,String>> entries) { String instanceZkTimeoutValue = null; boolean usingVolumes = false; - String cipherSuite = null; - String keyAlgorithm = null; - String secretKeyEncryptionStrategy = null; - String cryptoModule = null; for (Entry<String,String> entry : entries) { String key = entry.getKey(); String value = entry.getValue(); Should these values be set to the new constants above? public static void validate(Iterable<Entry<String,String>> entries) { String instanceZkTimeoutValue = null; boolean usingVolumes = false; + String cipherSuite = NULL_CIPHER; + String keyAlgorithm = NULL_CIPHER; + String secretKeyEncryptionStrategy = NULL_SECRET_KEY_ENCRYPTION_STRATEGY; + String cryptoModule = NULL_CRYPTO_MODULE; for (Entry<String,String> entry : entries) { String key = entry.getKey(); String value = entry.getValue();
codereview_java_data_6599
if (isAnyDistinct()) { rows = distinctRows.values(); } - if (sort != null) { - if (offset > 0 || limit > 0) { - sort.sort(rows, offset, limit < 0 || withTies ? rows.size() : limit); } else { sort.sort(rows); } this check looks like it should be part of the if statement on the previous line Also that limit < 0 in combination with the limit > 0 on the previous line looks very dodgy if (isAnyDistinct()) { rows = distinctRows.values(); } + if (sort != null && limit != 0) { + boolean withLimit = limit > 0 && !withTies; + if (offset > 0 || withLimit) { + sort.sort(rows, offset, withLimit ? limit : rows.size()); } else { sort.sort(rows); }
codereview_java_data_6606
@NonNull @Override public Constraint<Boolean> isSMBModeEnabled(@NonNull Constraint<Boolean> value) { Constraint<Boolean> closedLoop = constraintChecker.isClosedLoopAllowed(); if (!closedLoop.value()) value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.smbnotallowedinopenloopmode), this); but this removes message passed to UI @NonNull @Override public Constraint<Boolean> isSMBModeEnabled(@NonNull Constraint<Boolean> value) { + boolean enabled = sp.getBoolean(R.string.key_use_smb, false); + if (!enabled) + value.addReason(getResourceHelper().gs(R.string.smbdisabledinpreferences), this); Constraint<Boolean> closedLoop = constraintChecker.isClosedLoopAllowed(); if (!closedLoop.value()) value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.smbnotallowedinopenloopmode), this);
codereview_java_data_6608
assertEquals("00000000-0000-4000-8000-000000000000", min.getString()); // Test conversion from ValueJavaObject to ValueUuid - ValueJavaObject vo_uuid = ValueJavaObject.getNoCopy(UUID.randomUUID(), null, null); - assertTrue(vo_uuid.convertTo(Value.UUID) instanceof ValueUuid); ValueJavaObject vo_string = ValueJavaObject.getNoCopy(new String("This is not a ValueUuid object"), null, null); assertThrows(DbException.class, vo_string).convertTo(Value.UUID); I guess here we have to assert that UUID you will get from ValueUuid instance will equal to the initially passed value. assertEquals("00000000-0000-4000-8000-000000000000", min.getString()); // Test conversion from ValueJavaObject to ValueUuid + ValueJavaObject valObj = ValueJavaObject.getNoCopy(UUID.fromString("12345678-1234-4321-8765-123456789012"), null, null); + Value valUUID = valObj.convertTo(Value.UUID); + assertTrue(valUUID instanceof ValueUuid); + assertTrue((valUUID.getString().equals("12345678-1234-4321-8765-123456789012"))); ValueJavaObject vo_string = ValueJavaObject.getNoCopy(new String("This is not a ValueUuid object"), null, null); assertThrows(DbException.class, vo_string).convertTo(Value.UUID);
codereview_java_data_6614
return jgrafana.serialize(); } catch (IOException e) { logger.error("Could not serialize the grafana dashboard"); - throw new RuntimeException("Could not serialize the grafana dashboard.", e); } } ```suggestion throw new UncheckedIOException("Could not serialize the grafana dashboard.", e); ``` return jgrafana.serialize(); } catch (IOException e) { logger.error("Could not serialize the grafana dashboard"); + throw new UncheckedIOException("Could not serialize the grafana dashboard.", e); } }
codereview_java_data_6624
return false; } ClientAuthenticationMethod that = (ClientAuthenticationMethod) obj; - return this.getValue().toLowerCase(Locale.ROOT).equals(that.getValue().toLowerCase(Locale.ROOT)); } @Override public int hashCode() { - return this.getValue().toLowerCase(Locale.ROOT).hashCode(); } } Please remove `toLowerCase()` and use `equals()` for exact matching. return false; } ClientAuthenticationMethod that = (ClientAuthenticationMethod) obj; + return this.getValue().equals(that.getValue()); } @Override public int hashCode() { + return this.getValue().hashCode(); } }
codereview_java_data_6625
* This method should be called while committing non-idempotent overwrite operations. * If a concurrent operation commits a new file after the data was read and that file might * contain rows matching the specified conflict detection filter, the overwrite operation - * will detect this during retries and fail. * <p> * Calling this method with a correct conflict detection filter is required to maintain * serializable isolation for overwrite operations. Otherwise, the isolation level Shouldn't we be using this return value with validateNoConflictingDataFiles? * This method should be called while committing non-idempotent overwrite operations. * If a concurrent operation commits a new file after the data was read and that file might * contain rows matching the specified conflict detection filter, the overwrite operation + * will detect this and fail. * <p> * Calling this method with a correct conflict detection filter is required to maintain * serializable isolation for overwrite operations. Otherwise, the isolation level
codereview_java_data_6635
else if(collectionType == DataType.Name.SET) return ImmutableSet.of(SAMPLE_DATA.get(dataType)); else if(collectionType == DataType.Name.MAP) - if(dataType.getName() == DataType.Name.BLOB) - return new HashMap<Object, Object>().put(SAMPLE_DATA.get(DataType.ascii()), SAMPLE_DATA.get(dataType)); - else return new HashMap<Object, Object>().put(SAMPLE_DATA.get(dataType), SAMPLE_DATA.get(dataType)); else if(collectionType == DataType.Name.TUPLE) { TupleType t = TupleType.of(dataType, dataType); Let's remove this now that we know this is not needed for the java tests. else if(collectionType == DataType.Name.SET) return ImmutableSet.of(SAMPLE_DATA.get(dataType)); else if(collectionType == DataType.Name.MAP) return new HashMap<Object, Object>().put(SAMPLE_DATA.get(dataType), SAMPLE_DATA.get(dataType)); else if(collectionType == DataType.Name.TUPLE) { TupleType t = TupleType.of(dataType, dataType);
codereview_java_data_6642
// When BatchStage<String> mapped = stage.mapUsingService(bidirectionalStreaming(port), (service, key, item) -> { HelloRequest req = HelloRequest.newBuilder().setName(item).build(); - try { - return service.call(req).get().getMessage(); - } catch (Exception ex) { - throw new RuntimeException(ex); - } }); // Then Do we need the catch blocks here? // When BatchStage<String> mapped = stage.mapUsingService(bidirectionalStreaming(port), (service, key, item) -> { HelloRequest req = HelloRequest.newBuilder().setName(item).build(); + return service.call(req).thenApply(HelloReply::getMessage).get(); }); // Then
codereview_java_data_6645
// cached because calling clazz.getTypeParameters().length create a new array every time private final int typeParameterCount; private final boolean isGeneric; private final JavaTypeDefinition enclosingClass; protected JavaTypeDefinitionSimple(Class<?> clazz, JavaTypeDefinition... boundGenerics) { why is this not public if `JavaTypeDefinitionIntersection` is? Either both should be or none. // cached because calling clazz.getTypeParameters().length create a new array every time private final int typeParameterCount; private final boolean isGeneric; + private final boolean isRawType; private final JavaTypeDefinition enclosingClass; protected JavaTypeDefinitionSimple(Class<?> clazz, JavaTypeDefinition... boundGenerics) {
codereview_java_data_6655
*/ package javaslang.collection.euler; import javaslang.collection.List; import javaslang.collection.Stream; import static javaslang.collection.euler.Utils.isPrime; we could omit the reverse by providing a comparator: ``` java sorted(Comparator.reverseOrder()) ``` (does that compile?) */ package javaslang.collection.euler; +import static java.util.Comparator.reverseOrder; import javaslang.collection.List; import javaslang.collection.Stream; import static javaslang.collection.euler.Utils.isPrime;
codereview_java_data_6664
} private void check(@Nullable StatementTree tree, VisitorState state) { - if (tree != null && tree.getKind() == Tree.Kind.EXPRESSION_STATEMENT) { state.reportMatch(buildDescription(tree) .addFix(SuggestedFix.replace(tree, "{" + state.getSourceForNode(tree) + "}")) .build()); seems a little odd to always return NO_MATCH and rely on a side effect of check to actually do the fix } private void check(@Nullable StatementTree tree, VisitorState state) { + if (tree != null + && tree.getKind() != Tree.Kind.BLOCK + && tree.getKind() != Tree.Kind.EMPTY_STATEMENT) { state.reportMatch(buildDescription(tree) .addFix(SuggestedFix.replace(tree, "{" + state.getSourceForNode(tree) + "}")) .build());
codereview_java_data_6667
@Test public void testRuleEvaluation() { - KieSession ksession = runtimeBuilder.newKieSession("canDrinkKS"); Result result = new Result(); ksession.insert(result); Why this change? As far as I can see `canDrinkKS` is marked as default session so it should work also without the explicit name. Is this a limitation of `KieRuntimeBuilder`? @Test public void testRuleEvaluation() { + // canDrinkKS is the default session + KieSession ksession = runtimeBuilder.newKieSession(); + + List<String> pkgNames = ksession.getKieBase().getKiePackages().stream().map(KiePackage::getName).collect(Collectors.toList()); + assertEquals(2, pkgNames.size()); + assertTrue(pkgNames.contains("org.kie.kogito.quarkus.drools")); + assertTrue(pkgNames.contains("org.drools.simple.candrink")); Result result = new Result(); ksession.insert(result);
codereview_java_data_6680
progressBar.setVisibility(View.GONE); }, error -> Log.e(TAG, Log.getStackTraceString(error))); - if (UserPreferences.getSubscriptionsFilter().areSubscriptionsFiltered()) { feedsFilteredMsg.setText("{md-info-outline} " + getString(R.string.subscriptions_are_filtered)); Iconify.addIcons(feedsFilteredMsg); feedsFilteredMsg.setVisibility(View.VISIBLE); The method name sounds a bit strange to me (having the words "subscription filter" twice). I currently do not have a better name in mind, though. progressBar.setVisibility(View.GONE); }, error -> Log.e(TAG, Log.getStackTraceString(error))); + if (UserPreferences.getSubscriptionsFilter().isEnabled()) { feedsFilteredMsg.setText("{md-info-outline} " + getString(R.string.subscriptions_are_filtered)); Iconify.addIcons(feedsFilteredMsg); feedsFilteredMsg.setVisibility(View.VISIBLE);
codereview_java_data_6685
public class K9MailLib { private static DebugStatus debugStatus = new DefaultDebugStatus(); - private static ImapExtensionStatus imapExtensionStatus = new DefaultImapExtensionStatus(); private K9MailLib() { } I'm not a big fan of making this a super object in terms of configuration. `ImapConfig` would be a good name for a class that could house the new stuff being added here. public class K9MailLib { private static DebugStatus debugStatus = new DefaultDebugStatus(); private K9MailLib() { }
codereview_java_data_6691
} // Return null as secret hash if clientSecret is null or "". - // We receive clientSecret as "" if we create cognitoUserPool from awsConfiguration file with "AppClientSecret": " if (TextUtils.isEmpty(clientSecret)) { return null; } nit: could you close the last quote? :) } // Return null as secret hash if clientSecret is null or "". + // We receive clientSecret as "" if we create cognitoUserPool from awsConfiguration file with "AppClientSecret": "" if (TextUtils.isEmpty(clientSecret)) { return null; }
codereview_java_data_6694
@Nonnull DistributedFunction<ConsumerRecord<K, V>, T> projectionFn, @Nonnull WatermarkGenerationParams<T> wmGenParams ) { - return new CloseableProcessorSupplier<StreamKafkaP>(() -> new StreamKafkaP<>( properties, topics, projectionFn, wmGenParams )); } We've lost the preferred local parallelism of 2 here. And the explicit type parameter is not needed. @Nonnull DistributedFunction<ConsumerRecord<K, V>, T> projectionFn, @Nonnull WatermarkGenerationParams<T> wmGenParams ) { + return new CloseableProcessorSupplier<>(() -> new StreamKafkaP<>( properties, topics, projectionFn, wmGenParams )); }
codereview_java_data_6695
private void initializePebbleNotificationSupport() { - Cursor c = getContentResolver().query(Uri.parse("content://com.getpebble.android.provider/state"), - null, null, null, null); - if (c == null || !c.moveToNext()) { - this.findPreference(PEBBLE_NOTIFICATION_PREF).setEnabled(false); } } This would happen on the UI thread. Please move into an AsyncTask. private void initializePebbleNotificationSupport() { + if (!PebbleNotifier.isPebbleAppInstalled(this)) { + Preference pebble_pref = this.findPreference(PEBBLE_NOTIFICATION_PREF); + ((PreferenceCategory)this.findPreference(NOTIFICATION_CATEGORY_PREF)).removePreference(pebble_pref); } }
codereview_java_data_6700
* Because the data is of an unknown length, we cannot know the block size. To avoid corrupt RFiles, we throw an exception. This should be addressed by * whatever object is putting data into the stream to ensure this condition is never reached. */ - if (size() == Integer.MAX_VALUE) { throw new IOException("Unknown block size of at least " + Integer.MAX_VALUE + " bytes."); } return size() & 0x00000000ffffffffL; :+1: Seems like a reasonable strategy here. * Because the data is of an unknown length, we cannot know the block size. To avoid corrupt RFiles, we throw an exception. This should be addressed by * whatever object is putting data into the stream to ensure this condition is never reached. */ + if (size() >= Integer.MAX_VALUE) { throw new IOException("Unknown block size of at least " + Integer.MAX_VALUE + " bytes."); } return size() & 0x00000000ffffffffL;
codereview_java_data_6703
} } - public CompletableFuture<Void> getSlaveUsage(SingularitySlave slave) { return usageCollectionSemaphore.call(() -> - CompletableFuture.runAsync(() -> { - collectSlaveUsage( slave, System.currentTimeMillis(), new ConcurrentHashMap<>(), For the individual method, not sure we want to make it completely async like the larger ones. This method will likely not be called from the same context as the poller itself, so it should probably fall under a different semaphore (e.g. the offer scoring one) if we want it to be async } } + public CompletableFuture<SingularitySlaveUsage> getSlaveUsage(SingularitySlave slave) { return usageCollectionSemaphore.call(() -> + CompletableFuture.supplyAsync(() -> { + return collectSlaveUsage( slave, System.currentTimeMillis(), new ConcurrentHashMap<>(),
codereview_java_data_6718
*/ Map<String, E> mappings(); - - /** - * Returns a set of choice tuples if available. This is kept for compatibility with the eclipse plugin, even - * though it returns the same information as {@link #mappings()} (only it returns them ordered). - * - * @return An array of the label value mappings. The first column is the labels, the second is the value. - */ - Object[][] choices(); } why not drop this altogether and update the plugin to use the new APIs? */ Map<String, E> mappings(); }
codereview_java_data_6719
Locale getLanguage(); /** - * Returns all software version as reported by the peer on this connection, * as obtained through XEP-0092. - * @return The Software version information */ Map<String,String> getSoftwareVersion(); } Returns all Software Version data as.. Locale getLanguage(); /** + * Returns all Software Version data as reported by the peer on this connection, * as obtained through XEP-0092. + * @return The Software Version information */ Map<String,String> getSoftwareVersion(); }
codereview_java_data_6720
for (int i = 0; i < indent; i++) { System.out.print(" "); } - System.out.printf((fmtString) + "%n", args); } } ```suggestion System.out.printf(fmtString + "%n", args); ``` for (int i = 0; i < indent; i++) { System.out.print(" "); } + System.out.printf(fmtString, args); } }
codereview_java_data_6728
Types.NestedField sourceColumn = findSourceColumn(sourceName); PartitionField field = new PartitionField( sourceColumn.fieldId(), nextFieldId(), targetName, Transforms.year(sourceColumn.type())); - checkForRedundantPartitions(field, "dates"); fields.add(field); return this; } nit: "dates" has shown up multiple times, move to static variable Types.NestedField sourceColumn = findSourceColumn(sourceName); PartitionField field = new PartitionField( sourceColumn.fieldId(), nextFieldId(), targetName, Transforms.year(sourceColumn.type())); + checkForRedundantPartitions(field); fields.add(field); return this; }
codereview_java_data_6731
package org.apache.iceberg.mr.hive.serde.objectinspector; /** - * Interface for converting the Hive primitive objects for to the objects which could be added to an Iceberg Record. * If the IcebergObjectInspector does not implement this then the default Hive primitive objects will be used without * conversion. */ typo: ... for to ... package org.apache.iceberg.mr.hive.serde.objectinspector; /** + * Interface for converting the Hive primitive objects for the objects which could be added to an Iceberg Record. * If the IcebergObjectInspector does not implement this then the default Hive primitive objects will be used without * conversion. */
codereview_java_data_6734
Row row = rows.get(0); assertEquals(row.getInt("a"), 0); - assertEquals(row.getUDTValue("alldatatypes"), alldatatypes); } catch (Exception e) { errorOut(); Should be `row.getUDTValue("b")` (you want the name of the column here, not the name of the type). Row row = rows.get(0); assertEquals(row.getInt("a"), 0); + assertEquals(row.getUDTValue("b"), alldatatypes); } catch (Exception e) { errorOut();
codereview_java_data_6742
AccumuloConfiguration acuconf = options.getTableConfiguration(); long blockSize = acuconf.getAsBytes(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE); - if (blockSize >= Integer.MAX_VALUE || blockSize < 0) { - throw new IllegalArgumentException("table.file.compress.blocksize must be greater than 0 and less than " + Integer.MAX_VALUE); - } long indexBlockSize = acuconf.getAsBytes(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE_INDEX); - if (indexBlockSize >= Integer.MAX_VALUE || indexBlockSize < 0) { - throw new IllegalArgumentException("table.file.compress.blocksize.index must be greater than 0 and less than " + Integer.MAX_VALUE); - } SamplerConfigurationImpl samplerConfig = SamplerConfigurationImpl.newSamplerConfig(acuconf); Sampler sampler = null; I think there might be a Guava `Preconditions.checkArgument(boolean check, String message)` which would simplify these IllegalArgumentException checks and throws. AccumuloConfiguration acuconf = options.getTableConfiguration(); long blockSize = acuconf.getAsBytes(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE); + Preconditions.checkArgument((blockSize < Integer.MAX_VALUE && blockSize > 0), "table.file.compress.blocksize must be greater than 0 and less than " + + Integer.MAX_VALUE); long indexBlockSize = acuconf.getAsBytes(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE_INDEX); + Preconditions.checkArgument((indexBlockSize < Integer.MAX_VALUE && indexBlockSize > 0), + "table.file.compress.blocksize.index must be greater than 0 and less than " + Integer.MAX_VALUE); SamplerConfigurationImpl samplerConfig = SamplerConfigurationImpl.newSamplerConfig(acuconf); Sampler sampler = null;
codereview_java_data_6746
return CliqueBlockHashing.recoverProposerAddress(header, extraData); } - public static Optional<List<Address>> getValidatorsForBlockNumber( final long blockNumber, final EpochManager epochManager, final BlockchainQueries blockchainQueries) { rename this, it actually returns the validators from the past epoch block, not the supplied block number. return CliqueBlockHashing.recoverProposerAddress(header, extraData); } + public static Optional<List<Address>> getValidatorsForLastEpochBlock( final long blockNumber, final EpochManager epochManager, final BlockchainQueries blockchainQueries) {
codereview_java_data_6752
/** * The canonical ID */ - public String canonicalID() { return canonical; } Why make this non-final? Given how important this method is for its serialization/internal representation, it's pretty important that it not be overridden. /** * The canonical ID */ + public final String canonicalID() { return canonical; }
codereview_java_data_6757
// The sibling before the operator is the left hand side JavaNode lhs = assignment.getParent().getChild(assignment.getIndexInParent() - 1); - ASTName name = lhs.getFirstDescendantOfType(ASTName.class); - if (name != null) { - NameDeclaration statementVariable = name.getNameDeclaration(); - if (statementVariable != null && statementVariable.equals(variable.getVariableId().getNameDeclaration())) { - return true; - } } } Not sure if this is important, but this `descendants` check could misinterpret `array[...] = ...`, because it will fetch the name of the array. Might be worth figuring out a test case // The sibling before the operator is the left hand side JavaNode lhs = assignment.getParent().getChild(assignment.getIndexInParent() - 1); + if (isVariableAccess(lhs, variable.getName())) { + return true; } }
codereview_java_data_6758
*/ package org.kie.kogito.codegen.unit; -import org.drools.ruleunits.impl.EventListDataStream; import org.kie.kogito.codegen.data.StockTick; import org.kie.kogito.codegen.data.ValueDrop; import org.kie.kogito.rules.DataSource; import org.kie.kogito.rules.DataStore; import org.kie.kogito.rules.DataStream; This should become part of the API (or hidden with a factory method) given that users access it */ package org.kie.kogito.codegen.unit; import org.kie.kogito.codegen.data.StockTick; import org.kie.kogito.codegen.data.ValueDrop; +import org.kie.kogito.drools.core.data.EventListDataStream; import org.kie.kogito.rules.DataSource; import org.kie.kogito.rules.DataStore; import org.kie.kogito.rules.DataStream;
codereview_java_data_6761
return new Nutriment(additionalProperties.get(nutrimentName).toString(), get100g(nutrimentName), getServing(nutrimentName), getUnit(nutrimentName)); }catch (NullPointerException e){ // In case one of the getters was unable to get data as string } return null; } You should print something to the log here for troubleshooting issues. Even `e.printStackTrace()` would be fine. return new Nutriment(additionalProperties.get(nutrimentName).toString(), get100g(nutrimentName), getServing(nutrimentName), getUnit(nutrimentName)); }catch (NullPointerException e){ // In case one of the getters was unable to get data as string + Log.e("NUTRIMENTS-MODEL",e.printStackTrace()); } return null; }
codereview_java_data_6762
@Override public String toString() { return ToString.builder("ExecutionAttributes") - .add("attributes", attributes) .build(); } Should we just log the keys in case there's sensitive information in the values? @Override public String toString() { return ToString.builder("ExecutionAttributes") + .add("attributes", attributes.keySet()) .build(); }
codereview_java_data_6765
// Assert there are three tasks with the default category List<org.flowable.task.api.Task> tasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list(); for (org.flowable.task.api.Task task : tasks) { - assertEquals("approval", task.getCategory()); Map<String, Object> taskVariables = new HashMap<>(); taskVariables.put("outcome", "approve"); FWIW, this is based on an older version of the file as line 68/69 is now: <pre> assertThat(task.getCategory()).isEqualTo("approval"); </pre> but it is still possible to merge your changes. There is at least on other such file in this PR. // Assert there are three tasks with the default category List<org.flowable.task.api.Task> tasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list(); for (org.flowable.task.api.Task task : tasks) { + assertThat(task.getCategory()).isEqualTo("approval"); Map<String, Object> taskVariables = new HashMap<>(); taskVariables.put("outcome", "approve");
codereview_java_data_6772
int maxZoom = params.getMaxZoom(); int zoom = params.getZoom(); float newDist = getFingerSpacing(event); - if (newDist > mDist) { //zoom in - if (zoom < maxZoom) zoom+=6; - } else if (newDist < mDist) { //zoom out - if (zoom > 0) zoom-=6; } mDist = newDist; This condition can be combined int maxZoom = params.getMaxZoom(); int zoom = params.getZoom(); float newDist = getFingerSpacing(event); + if (newDist > mDist && zoom < maxZoom) { //zoom in zoom+=6; + } else if (newDist < mDist && zoom > 0) { //zoom out zoom-=6; } mDist = newDist;
codereview_java_data_6778
} } @Test public void testIllegalTableTransitionExceptionEmptyMessage() { try { In addition to `""`, could also try null. } } + @Test + public void testIllegalTableTransitionExceptionWithNull() { + try { + throw new TableManager.IllegalTableTransitionException(oldState, newState, null); + } catch (IllegalTableTransitionException e) { + assertEquals(defaultMsg, e.getMessage()); + } + } + @Test public void testIllegalTableTransitionExceptionEmptyMessage() { try {
codereview_java_data_6780
level.setMaximumUniqueImagesUsed(5); if(achievements.getImagesUploaded() >= 100 && achievements.getUniqueUsedImages() >= 45){ level.setLevel(10); level.setLevelStyle(R.style.LevelFive); } else if (achievements.getImagesUploaded() >= 90 && achievements.getUniqueUsedImages() >= 40){ level.setLevel(9); Moreover, the `level` object is playing with a lot of magic numbers right now. These could very well be part of a `static` `enum` inside the `Level` object. ``` public class Level { // some properties public LevelInfo levelInfo; public enum LevelInfo { LEVEL_1(1, 2121, 0, 0), LEVEL_2(2, 2122, 20, 5), LEVEL_3(3, 2122, 30, 10), LEVEL_4(4, 2122, 40, 15); private int levelNumber; private int levelStyle; private int maxUniqueImages; private int maxUploadCount; LevelInfo(int levelNumber, int levelStyle, int maxUniqueImages, int maxUploadCount) { this.levelNumber = levelNumber; this.levelStyle = levelStyle; this.maxUniqueImages = maxUniqueImages; this.maxUploadCount = maxUploadCount; } public static LevelInfo from(int imagesUploaded, int uniqueImagesUsed) { LevelInfo level = LEVEL_1; for (LevelInfo levelInfo : LevelInfo.values()) { if (imagesUploaded > levelInfo.maxUploadCount && uniqueImagesUsed > levelInfo.maxUniqueImages) { level = levelInfo; } } return level; } } } ``` level.setMaximumUniqueImagesUsed(5); if(achievements.getImagesUploaded() >= 100 && achievements.getUniqueUsedImages() >= 45){ level.setLevel(10); + level.setMaximumUniqueImagesUsed(50); + level.setMaximumUploadCount(110); level.setLevelStyle(R.style.LevelFive); } else if (achievements.getImagesUploaded() >= 90 && achievements.getUniqueUsedImages() >= 40){ level.setLevel(9);
codereview_java_data_6783
if (newValue.equals("page")) { final Context context = ui.getActivity(); final String[] navTitles = context.getResources().getStringArray(R.array.back_button_go_to_pages); - final String[] navTags = { MainActivity.NAV_DRAWER_TAGS[0], MainActivity.NAV_DRAWER_TAGS[1], MainActivity.NAV_DRAWER_TAGS[2] }; final String choice[] = { UserPreferences.getBackButtonGoToPage() }; AlertDialog.Builder builder = new AlertDialog.Builder(context); I think it would be better to directly reference the tags here. Relying on array indices might confuse future developers when changing `MainActivity.NAV_DRAWER_TAGS`. I suggest using `QueueFragment.TAG` etc. if (newValue.equals("page")) { final Context context = ui.getActivity(); final String[] navTitles = context.getResources().getStringArray(R.array.back_button_go_to_pages); + final String[] navTags = context.getResources().getStringArray(R.array.back_button_go_to_pages_tags); final String choice[] = { UserPreferences.getBackButtonGoToPage() }; AlertDialog.Builder builder = new AlertDialog.Builder(context);
codereview_java_data_6785
if (version != null) { this.checkAndWriteString(basePath, KVPathUtil.VERSION, version); } else { - Stat stat = this.getCurator().checkExists().forPath(basePath + KVPathUtil.SEPARATOR + KVPathUtil.VERSION); - if (stat != null) { this.getCurator().delete().forPath(basePath + KVPathUtil.SEPARATOR + KVPathUtil.VERSION); } } can replace by checkPathExists() ? if (version != null) { this.checkAndWriteString(basePath, KVPathUtil.VERSION, version); } else { + if (this.checkPathExists(basePath + KVPathUtil.SEPARATOR + KVPathUtil.VERSION)) { this.getCurator().delete().forPath(basePath + KVPathUtil.SEPARATOR + KVPathUtil.VERSION); } }
codereview_java_data_6787
public class IncrementalRuleCodegenTest { @BeforeEach - public void blah() { DecisionTableFactory.setDecisionTableProvider(ServiceRegistry.getInstance().get(DecisionTableProvider.class)); } maybe not the best method name? public class IncrementalRuleCodegenTest { @BeforeEach + public void setup() { DecisionTableFactory.setDecisionTableProvider(ServiceRegistry.getInstance().get(DecisionTableProvider.class)); }
codereview_java_data_6807
* * @return an object to modify replication configuration */ - @Deprecated ReplicationOperations replicationOperations(); /** I think we can add a `since = "2.1.0"` here. (new optional parameter in Java 9) This could be done for any public API and property deprecations. I wouldn't bother doing this with internal deprecations. * * @return an object to modify replication configuration */ + @Deprecated(since = "2.1.0") ReplicationOperations replicationOperations(); /**
codereview_java_data_6814
/** Test case for * <a href="https://issues.apache.org/jira/browse/CALCITE-4690">[CALCITE-4690] - * Error when when executing query with CHARACTER SET in Redshift</a>. */ @Test void testRedshiftCharacterSet() { String query = "select \"hire_date\", cast(\"hire_date\" as varchar(10))\n" + "from \"foodmart\".\"reserve_employee\""; code annotation has repeated when word? "Error when exe....." /** Test case for * <a href="https://issues.apache.org/jira/browse/CALCITE-4690">[CALCITE-4690] + * Error when executing query with CHARACTER SET in Redshift</a>. */ @Test void testRedshiftCharacterSet() { String query = "select \"hire_date\", cast(\"hire_date\" as varchar(10))\n" + "from \"foodmart\".\"reserve_employee\"";
codereview_java_data_6844
* * @param name the name of the processor * @param createFn the function to create the sink context, given a - * processor context. It must be stateless * @param <C> type of the context object * * @since 3.0 ```suggestion * processor context. It must be stateless. ``` * * @param name the name of the processor * @param createFn the function to create the sink context, given a + * processor context. It must be stateless. * @param <C> type of the context object * * @since 3.0
codereview_java_data_6854
private final AllocateMappedFileService allocateMappedFileService; /** - * Flush offset within the queue. */ - private long flushOffset = 0; - private long committedWhere = 0; private volatile long storeTimestamp = 0; Consider the abuse of `offset` in rocketmq-store, so we use `flushedWhere` and `committedWhere`. `flushedWhere` means the offset of all mappedFile, while `offset` means the offset of one mappedFile in general. private final AllocateMappedFileService allocateMappedFileService; /** + * 'Flushed' position within the queue. */ + private long flushedPosition = 0; + private long committedPosition = 0; private volatile long storeTimestamp = 0;
codereview_java_data_6856
import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; -import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; Import is not used. import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet;
codereview_java_data_6857
* * See https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-metrics.html */ -@UsesJava8 public final class ActuateCollectorMetrics implements CollectorMetrics, PublicMetrics { private final CounterBuffers counterBuffers; mentioned offline, this is perfectly fine as our server is java 8 since the beginning * * See https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-metrics.html */ public final class ActuateCollectorMetrics implements CollectorMetrics, PublicMetrics { private final CounterBuffers counterBuffers;
codereview_java_data_6859
if (enableOCSP) { // See https://stackoverflow.com/questions/49904935/jetty-9-enable-ocsp-stapling-for-domain-validated-certificate - Security.setProperty("ocsp.enable", "true"); - System.setProperty("jdk.tls.server.enableStatusRequestExtension", "true"); - System.setProperty("com.sun.net.ssl.checkRevocation", "true"); sslContextFactory.setEnableOCSP(true); sslContextFactory.setValidateCerts(true); // not sure what this does... OCSP works even without this - but it is recommended. } other than sslContextFactory.setEnableOCSP(true); I'm not sure why we have the other settings or why we're setting them in the first place. So let's remove those from our code. if the organization wants to enable those, they can do so by adding them to the server startup script as just regular system properties. if (enableOCSP) { // See https://stackoverflow.com/questions/49904935/jetty-9-enable-ocsp-stapling-for-domain-validated-certificate + // Note that for OCSP-Stapling to actually work - these commands must also be performed: + // Security.setProperty("ocsp.enable", "true"); + // System.setProperty("jdk.tls.server.enableStatusRequestExtension", "true"); + // System.setProperty("com.sun.net.ssl.checkRevocation", "true"); sslContextFactory.setEnableOCSP(true); sslContextFactory.setValidateCerts(true); // not sure what this does... OCSP works even without this - but it is recommended. }
codereview_java_data_6863
return new RemoteWebDriverBuilder(); } - private void init(Capabilities capabilities) { - this.capabilities = capabilities == null ? new ImmutableCapabilities() : capabilities; logger.addHandler(LoggingHandler.getInstance()); Assigning capabilities to the field here is not the best idea. Semantically this field contains the capabilities returned by the browser after session start. So here we sould better amend capabilities and return them from `init` method to pass later to `startSession` method (that will assign the capabilities returned by the browser to the field). return new RemoteWebDriverBuilder(); } + private Capabilities init(Capabilities capabilities) { + capabilities = capabilities == null ? new ImmutableCapabilities() : capabilities; logger.addHandler(LoggingHandler.getInstance());
codereview_java_data_6882
bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() { @Override - public void onStateChanged(View bottomSheet, int newState) { prepareViewsForSheetPosition(); } To let other collaborators know that `newState` is intentionally unused: rename to `unusedNewState`. bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() { @Override + public void onStateChanged(View bottomSheet, int unusedNewState) { prepareViewsForSheetPosition(); }
codereview_java_data_6888
} @Override - public Value atomize() throws XPathException { if (value == null) { - final Object v = attribute.getValue(); - value = SaxonXPathRuleQuery.getAtomicRepresentation(v); } return value; } Maybe inline that variable } @Override + public Value atomize() { if (value == null) { + value = SaxonXPathRuleQuery.getAtomicRepresentation(attribute.getValue()); } return value; }
codereview_java_data_6891
// we have guarantees about the format of the output and thus we can apply the // normal selector if (numeric && extractionFunction == null) { return new JsonCompositeFilter(JsonFilter.Type.AND, - new JsonBound(dimName, tr(e, posConstant), true, - tr(e, posConstant), true, numeric, extractionFunction)); } return new JsonSelector(dimName, tr(e, posConstant), extractionFunction); case NOT_EQUALS: can we extract the `tr(e, posConstant)` call ? // we have guarantees about the format of the output and thus we can apply the // normal selector if (numeric && extractionFunction == null) { + String constantValue = tr(e, posConstant); return new JsonCompositeFilter(JsonFilter.Type.AND, + new JsonBound(dimName, constantValue, true, constantValue, true, + numeric, extractionFunction)); } return new JsonSelector(dimName, tr(e, posConstant), extractionFunction); case NOT_EQUALS:
codereview_java_data_6907
* operations. Violations of this rule will manifest as less than 100% CPU * usage under maximum load (note that this is possible for other reasons too, * for example if the network is the bottleneck or if {@linkplain - * JetProperties#JET_IDLE_COOPERATIVE_MIN_MICROSECONDS parking time} is too high). * The processor must also return as soon as the outbox rejects an item * (that is when the {@link Outbox#offer(Object) offer()} method returns * {@code false}). Why do we link to the minimum parking time here? Is it more relevant than the max parking time? * operations. Violations of this rule will manifest as less than 100% CPU * usage under maximum load (note that this is possible for other reasons too, * for example if the network is the bottleneck or if {@linkplain + * JetProperties#JET_IDLE_COOPERATIVE_MAX_MICROSECONDS parking time} is too high). * The processor must also return as soon as the outbox rejects an item * (that is when the {@link Outbox#offer(Object) offer()} method returns * {@code false}).
codereview_java_data_6928
boolean sawInputEOS = false; boolean sawOutputEOS = false; int noOutputCounter = 0; - final long BAR_FACTOR = (totalDurationUs / (BAR_COUNT * SAMPLES_PER_BAR) + 1); - long barTimer = BAR_FACTOR; while (!sawOutputEOS && noOutputCounter < 50) { noOutputCounter++; Note that `ALL_CAPS` is reserved for class level `final static` values. If this was simply: ``` final long barFactor = totalDurationUs / (BAR_COUNT * SAMPLES_PER_BAR); long barTimer = 0; ``` It would give us this kind of fence post pattern (suppose `BAR_COUNT * SAMPLES_PER_BAR` = 4): ``` |__|__|__|__| ``` With a fifth post right around `totalDurationUs`. What you have is: ``` final long barFactor = totalDurationUs / (BAR_COUNT * SAMPLES_PER_BAR); long barTimer = barFactor; ``` Which puts the forth fence post around `totalDurationUs` but nothing at the start: ``` __|__|__|__| ``` What would be better is to balance out the fence posts like so: ``` final long barFactor = totalDurationUs / (BAR_COUNT * SAMPLES_PER_BAR); long barTimer = barFactor / 2; // (note not >>1 ) ``` ``` _|__|__|__|_ ``` boolean sawInputEOS = false; boolean sawOutputEOS = false; int noOutputCounter = 0; while (!sawOutputEOS && noOutputCounter < 50) { noOutputCounter++;
codereview_java_data_6932
return !oldReference.equals(reference); } - public void updateReference(Reference ref) { - Objects.requireNonNull(ref); - this.reference = ref; - } - public boolean isBranch() { return reference instanceof Branch; } can `this.reference` ever be `null`? return !oldReference.equals(reference); } public boolean isBranch() { return reference instanceof Branch; }
codereview_java_data_6934
return null; } - if (isLocalFile(loadingUrl) || loadingUrl.getHost().contains(bridge.getHost()) || (bridge.getServerUrl() == null && !bridge.getAppAllowNavigationMask().matches(loadingUrl.getHost()))) { Logger.debug("Handling local request: " + request.getUrl().toString()); return handleLocalRequest(request, handler); } else { Would this incorrectly trigger if `loadingUrl.getHost() = "something.app"` and `bridge.getHost() = "app"`? return null; } + if (isLocalFile(loadingUrl) || loadingUrl.getHost().equalsIgnoreCase(bridge.getHost()) || (bridge.getServerUrl() == null && !bridge.getAppAllowNavigationMask().matches(loadingUrl.getHost()))) { Logger.debug("Handling local request: " + request.getUrl().toString()); return handleLocalRequest(request, handler); } else {
codereview_java_data_6935
public void setPosition(int position) { this.position = position; - if(position > 0) { this.item.setPlayed(false); } } Perhaps I'm being daft, is this condition backwards? Why set 'played' to false when position is greater than 0? Should it be setting 'new' to false? public void setPosition(int position) { this.position = position; + if(position > 0 && item.isNew()) { this.item.setPlayed(false); } }
codereview_java_data_6939
+ "The classpath will be searched if this property is not set") private String propsPath; - public String getPropertiesPath() { if (propsPath == null) { URL propLocation = SiteConfiguration.getAccumuloPropsLocation(); propsPath = propLocation.getFile(); could sync this method. + "The classpath will be searched if this property is not set") private String propsPath; + public synchronized String getPropertiesPath() { if (propsPath == null) { URL propLocation = SiteConfiguration.getAccumuloPropsLocation(); propsPath = propLocation.getFile();
codereview_java_data_6943
final String deployId = getAndCheckDeployId(requestId); checkConflict(!(requestManager.markAsBouncing(requestId) == SingularityCreateResult.EXISTED), "%s is already bouncing", requestId); - Optional<Boolean> removeFromLoadBalancer = Optional.absent(); requestManager.createCleanupRequest( new SingularityRequestCleanup(JavaUtils.getUserEmail(user), isIncrementalBounce ? RequestCleanupType.INCREMENTAL_BOUNCE : RequestCleanupType.BOUNCE, - System.currentTimeMillis(), Optional.<Boolean> absent(), removeFromLoadBalancer, requestId, Optional.of(deployId), skipHealthchecks, message, actionId, runBeforeKill)); requestManager.bounce(requestWithState.getRequest(), System.currentTimeMillis(), JavaUtils.getUserEmail(user), message); can probably just put `Optional.absent()` in the args rather than setting it here final String deployId = getAndCheckDeployId(requestId); checkConflict(!(requestManager.markAsBouncing(requestId) == SingularityCreateResult.EXISTED), "%s is already bouncing", requestId); requestManager.createCleanupRequest( new SingularityRequestCleanup(JavaUtils.getUserEmail(user), isIncrementalBounce ? RequestCleanupType.INCREMENTAL_BOUNCE : RequestCleanupType.BOUNCE, + System.currentTimeMillis(), Optional.<Boolean> absent(), Optional.absent(), requestId, Optional.of(deployId), skipHealthchecks, message, actionId, runBeforeKill)); requestManager.bounce(requestWithState.getRequest(), System.currentTimeMillis(), JavaUtils.getUserEmail(user), message);
codereview_java_data_6950
import tech.pegasys.pantheon.ethereum.core.Address; import tech.pegasys.pantheon.ethereum.core.Hash; -import tech.pegasys.pantheon.tests.acceptance.dsl.transaction.PantheonWeb3j; import tech.pegasys.pantheon.tests.acceptance.dsl.transaction.PantheonWeb3j.SignersBlockResponse; import tech.pegasys.pantheon.tests.acceptance.dsl.transaction.Transaction; This is using the clique signers getSignersAtHash import tech.pegasys.pantheon.ethereum.core.Address; import tech.pegasys.pantheon.ethereum.core.Hash; +import tech.pegasys.pantheon.tests.acceptance.dsl.transaction.JsonRequestFactories; import tech.pegasys.pantheon.tests.acceptance.dsl.transaction.PantheonWeb3j.SignersBlockResponse; import tech.pegasys.pantheon.tests.acceptance.dsl.transaction.Transaction;
codereview_java_data_6959
@Value("${" + CREDENTIALS_REFRESH_INTERVAL + "}") Integer credentialsRefreshInterval, @Qualifier(QUALIFIER) BasicCredentials basicCredentials) throws IOException { ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor( - new NamedThreadFactory("zipkin-load-es-credentials-pool")); DynamicCredentialsFileLoader credentialsFileLoader = new DynamicCredentialsFileLoader(basicCredentials, credentialsFile); credentialsFileLoader.updateCredentialsFromProperties(); Minor nit: drop the pool suffix perhaps. @Value("${" + CREDENTIALS_REFRESH_INTERVAL + "}") Integer credentialsRefreshInterval, @Qualifier(QUALIFIER) BasicCredentials basicCredentials) throws IOException { ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor( + new NamedThreadFactory("zipkin-load-es-credentials")); DynamicCredentialsFileLoader credentialsFileLoader = new DynamicCredentialsFileLoader(basicCredentials, credentialsFile); credentialsFileLoader.updateCredentialsFromProperties();
codereview_java_data_6969
/** * @author Jitendra Singh */ public class UsernamePasswordAuthenticationTokenMixinTest extends AbstractMixinTests { We should have test for when `UsernamePasswordAuthenitcationToken.clearCredentials()` has been invoked NOTE: This is applicable to the other `AuthenticationToken` mixins too /** * @author Jitendra Singh + * @since 4.2 */ public class UsernamePasswordAuthenticationTokenMixinTest extends AbstractMixinTests {
codereview_java_data_6976
// TODO: Determine reasonable defaults here public static final int DEFAULT_PIVOT_DISTANCE_FROM_HEAD = 500; public static final float DEFAULT_FULL_VALIDATION_RATE = .1f; - public static final int DEFAULT_FAST_SYNC_MINIMUM_PEERS = 1; private static final Duration DEFAULT_FAST_SYNC_MAXIMUM_PEER_WAIT_TIME = Duration.ofMinutes(5); private static final int DEFAULT_WORLD_STATE_HASH_COUNT_PER_REQUEST = 200; private static final int DEFAULT_WORLD_STATE_REQUEST_PARALLELISM = 10; Is this a dev setting? // TODO: Determine reasonable defaults here public static final int DEFAULT_PIVOT_DISTANCE_FROM_HEAD = 500; public static final float DEFAULT_FULL_VALIDATION_RATE = .1f; + public static final int DEFAULT_FAST_SYNC_MINIMUM_PEERS = 5; private static final Duration DEFAULT_FAST_SYNC_MAXIMUM_PEER_WAIT_TIME = Duration.ofMinutes(5); private static final int DEFAULT_WORLD_STATE_HASH_COUNT_PER_REQUEST = 200; private static final int DEFAULT_WORLD_STATE_REQUEST_PARALLELISM = 10;
codereview_java_data_6978
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; public class DontImportJavaLangRule extends AbstractJavaRule { - private static final String IMPORT_JAVA_LANG = "java.lang."; @Override public Object visit(ASTImportDeclaration node, Object data) { this extra dot at the end is causing a couple tests to fail on Travis import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; public class DontImportJavaLangRule extends AbstractJavaRule { + private static final String IMPORT_JAVA_LANG = "java.lang"; @Override public Object visit(ASTImportDeclaration node, Object data) {
codereview_java_data_6979
@Override protected void init(@Nonnull Context context) { // createFn is allowed to return null, we'll call `destroyFn` even for null `ctx` - ManagedContext managedContext = context.serializationService().getManagedContext(); ctx = (C) managedContext.initialize(createFn.apply(context)); snapshotKey = broadcastKey(context.globalProcessorIndex()); initialized = true; We should get the `MangedContext` from `context.jetInstance().hazelcastInstance()` downcasted to `HazelcastInstanceImpl` @Override protected void init(@Nonnull Context context) { // createFn is allowed to return null, we'll call `destroyFn` even for null `ctx` + ManagedContext managedContext = context.managedContext(); ctx = (C) managedContext.initialize(createFn.apply(context)); snapshotKey = broadcastKey(context.globalProcessorIndex()); initialized = true;
codereview_java_data_6996
public static final String VALID_NAME_REGEX = "^(\\w+\\.)?(\\w+)$"; public static final Long TABLE_MAP_CACHE_EXPIRATION = TimeUnit.SECONDS.toNanos(1L); - private static final AtomicLong tableMapTimestamp = new AtomicLong(System.nanoTime()); private static final SecurityPermission TABLES_PERMISSION = new SecurityPermission("tablesPermission"); private static final AtomicLong cacheResetCount = new AtomicLong(0); private static volatile TableMap tableMapCache; - public static ZooCache getZooCache(Instance instance) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(TABLES_PERMISSION); Could make this package private public static final String VALID_NAME_REGEX = "^(\\w+\\.)?(\\w+)$"; public static final Long TABLE_MAP_CACHE_EXPIRATION = TimeUnit.SECONDS.toNanos(1L); private static final SecurityPermission TABLES_PERMISSION = new SecurityPermission("tablesPermission"); private static final AtomicLong cacheResetCount = new AtomicLong(0); private static volatile TableMap tableMapCache; + private static ZooCache getZooCache(Instance instance) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(TABLES_PERMISSION);
codereview_java_data_7015
} } - private void trimNonResidentQueue() { Entry<V> e; int maxQueue2Size = nonResidentQueueSize * (mapSize - queue2Size); if (maxQueue2Size >= 0) { This method should have default visibility too. } } + void trimNonResidentQueue() { Entry<V> e; int maxQueue2Size = nonResidentQueueSize * (mapSize - queue2Size); if (maxQueue2Size >= 0) {
codereview_java_data_7022
public static class TestPerson implements Serializable { - private String name; - private int age; - private boolean status; public TestPerson() { } Maybe use Jackson jr annotation support to get rid of all those getters & setters? public static class TestPerson implements Serializable { + public String name; + public int age; + public boolean status; public TestPerson() { }
codereview_java_data_7027
return removed; } void initiateChop() { Set<StoredTabletFile> allFiles = tablet.getDatafiles().keySet(); - ChopSelector chopSelector; synchronized (this) { if (fileMgr.getChopStatus() == FileSelectionStatus.NOT_ACTIVE) { Should handle this TODO or create follow on ticket return removed; } + private boolean noneRunning(CompactionKind kind) { + return runningJobs.stream().noneMatch(job -> job.getKind() == kind); + } + void initiateChop() { Set<StoredTabletFile> allFiles = tablet.getDatafiles().keySet(); + FileManager.ChopSelector chopSelector; synchronized (this) { if (fileMgr.getChopStatus() == FileSelectionStatus.NOT_ACTIVE) {
codereview_java_data_7028
import org.apache.accumulo.core.client.admin.DelegationTokenConfig; import org.apache.accumulo.core.client.admin.SecurityOperations; import org.apache.accumulo.core.client.impl.AuthenticationTokenIdentifier; -import org.apache.accumulo.core.client.impl.ConnectionInfoImpl; import org.apache.accumulo.core.client.impl.DelegationTokenImpl; import org.apache.accumulo.core.client.mapreduce.lib.impl.ConfiguratorBase; import org.apache.accumulo.core.client.mapreduce.lib.impl.OutputConfigurator; Using the interface as the type should eliminate the need to depend on the impl as well. import org.apache.accumulo.core.client.admin.DelegationTokenConfig; import org.apache.accumulo.core.client.admin.SecurityOperations; import org.apache.accumulo.core.client.impl.AuthenticationTokenIdentifier; +import org.apache.accumulo.core.client.impl.ConnectionInfoFactory; import org.apache.accumulo.core.client.impl.DelegationTokenImpl; import org.apache.accumulo.core.client.mapreduce.lib.impl.ConfiguratorBase; import org.apache.accumulo.core.client.mapreduce.lib.impl.OutputConfigurator;
codereview_java_data_7047
*/ void destroy(); - /** - * Exit maintenance mode - */ - void exit(); } I thought Maintainable was closable? Appears it isn't, but it probably should be. */ void destroy(); }
codereview_java_data_7050
* @see <a href="https://en.wikipedia.org/wiki/DUAL_table">Wikipedia: DUAL table</a> */ boolean isDualTable(String tableName) { - return ((schemaName == null || equalsToken(schemaName, "SYS")) && equalsToken("F", tableName)) || (database.getMode().sysDummy1 && (schemaName == null || equalsToken(schemaName, "SYSIBM")) && equalsToken("SYSDUMMY1", tableName)); } Why code was broken? * @see <a href="https://en.wikipedia.org/wiki/DUAL_table">Wikipedia: DUAL table</a> */ boolean isDualTable(String tableName) { + return ((schemaName == null || equalsToken(schemaName, "SYS")) && equalsToken("DUAL", tableName)) || (database.getMode().sysDummy1 && (schemaName == null || equalsToken(schemaName, "SYSIBM")) && equalsToken("SYSDUMMY1", tableName)); }
codereview_java_data_7060
* @return true if typed vector */ static boolean isTypedVector(int type) { - return (type >= FBT_VECTOR_INT && type <= FBT_VECTOR_KEY) || type == FBT_VECTOR_BOOL; } /** Shouldn't this still return true for existing data serialized this way? * @return true if typed vector */ static boolean isTypedVector(int type) { + return (type >= FBT_VECTOR_INT && type <= FBT_VECTOR_STRING_DEPRECATED) || type == FBT_VECTOR_BOOL; } /**
codereview_java_data_7061
@JsonProperty private String s3UploaderBucket; - @NotEmpty @JsonProperty private boolean useLocalDownloadService = false; `@NotEmpty` and `@NotNull` are unnecessary for `boolean` -- can't be set to `null` since it's a primitive type @JsonProperty private String s3UploaderBucket; @JsonProperty private boolean useLocalDownloadService = false;
codereview_java_data_7084
import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import java.time.*; import java.time.temporal.ChronoUnit; import java.util.Iterator; import java.util.List; We avoid wildcard imports because it isn't clear where symbols are coming from and there is potential for collision. Could you roll back this change? (As well as the additional newline, we don't use breaks in imports either.) import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.Iterator; import java.util.List;
codereview_java_data_7085
import java.util.Map; import org.flowable.common.engine.impl.interceptor.CommandExecutor; import org.flowable.engine.impl.cmd.CompleteTaskCmd; import org.flowable.engine.impl.cmd.CompleteTaskWithFormCmd; import org.flowable.task.api.TaskCompletionBuilder; -import org.flowable.common.engine.api.variable.VariableCollectionsContainer; -import org.flowable.common.engine.impl.variable.VariableCollectionsContainerImpl; /** Please order the imports in alphabetic order as per project standards; thanks. There are other occurrences also. import java.util.Map; +import org.flowable.common.engine.api.variable.VariableCollectionsContainer; import org.flowable.common.engine.impl.interceptor.CommandExecutor; +import org.flowable.common.engine.impl.variable.VariableCollectionsContainerImpl; import org.flowable.engine.impl.cmd.CompleteTaskCmd; import org.flowable.engine.impl.cmd.CompleteTaskWithFormCmd; import org.flowable.task.api.TaskCompletionBuilder; /**
codereview_java_data_7086
if (cooled instanceof KApply) { KApply kApply = (KApply)cooled; String name = kApply.klabel().name(); - K firstArg = kApply.klist().items().get(0); - if (name.equals("#SemanticCastToK") && firstArg instanceof KApply) { - name = ((KApply)firstArg).klabel().name(); } freezerLabel = getUniqueFreezerLabel(input, name + finalHolePosition[0]); } else { Can we move this declaration inside the name.equals condition? I'm a little worried about the possibility of an IndexOutOfBounds exception. if (cooled instanceof KApply) { KApply kApply = (KApply)cooled; String name = kApply.klabel().name(); + if (name.equals("#SemanticCastToK")) { + K firstArg = kApply.klist().items().get(0); + if (firstArg instanceof KApply) + name = ((KApply)firstArg).klabel().name(); } freezerLabel = getUniqueFreezerLabel(input, name + finalHolePosition[0]); } else {
codereview_java_data_7089
public class GPSExtractor { private String filePath; private double decLatitude, decLongitude; private double currentLatitude, currentLongitude; private Context context; - private static final String TAG = GPSExtractor.class.getName(); public boolean imageCoordsExists; private MyLocationListener myLocationListener; Obviously minor: I recommend grouping your constants at the top of the class. public class GPSExtractor { + private static final String TAG = GPSExtractor.class.getName(); + private String filePath; private double decLatitude, decLongitude; private double currentLatitude, currentLongitude; private Context context; public boolean imageCoordsExists; private MyLocationListener myLocationListener;
codereview_java_data_7096
protected final boolean distinct; /** - * FILTER condition for aggregate/window */ protected Expression filterCondition; H2 supports `FILTER` clause only in aggregate functions (including their window versions, unlike some other databases). H2 does not support it in window functions. SQL Standard also does not have such clause for window functions. protected final boolean distinct; /** + * FILTER condition for aggregate */ protected Expression filterCondition;
codereview_java_data_7105
void queueMutations(final MutationSet mutationsToSend) { if (mutationsToSend == null) return; - binningThreadPool.execute(Trace.wrap(() -> { if (mutationsToSend != null) { try { log.trace("{} - binning {} mutations", Thread.currentThread().getName(), Catching Throwable here seems counterproductive to the goal of this... which I understand is to give control to the calling code that provides the thread pool when an error occurs. We can't do that if we're swallowing the errors instead of letting the user specify their own uncaught exception handler on their thread pool. void queueMutations(final MutationSet mutationsToSend) { if (mutationsToSend == null) return; + binningThreadPool.execute(() -> { if (mutationsToSend != null) { try { log.trace("{} - binning {} mutations", Thread.currentThread().getName(),
codereview_java_data_7107
return mediaDetailPagerFragment; } - // click listener to toggle description private View.OnClickListener toggleDescriptionListener = new View.OnClickListener() { @Override public void onClick(View view) { - View view2 = limitedConnectionDescriptionTv; if (view2.getVisibility() == View.GONE) { view2.setVisibility(View.VISIBLE); } else { Would you mind adding what it means from the UI user's point of view? (tap on the explanation to hide it) Thanks! return mediaDetailPagerFragment; } + // click listener to toggle description that means uses can press the limited connection + // banner and description will hide. Tap again to show description. private View.OnClickListener toggleDescriptionListener = new View.OnClickListener() { @Override public void onClick(View view) { + View view2 = limitedConnectionDescriptionTextView; if (view2.getVisibility() == View.GONE) { view2.setVisibility(View.VISIBLE); } else {
codereview_java_data_7112
} // add the method declaration of the superclass to the candidates, if present - SymbolReference<ResolvedMethodDeclaration> superClassMethodRef = MethodResolutionLogic.solveMethodInFQN - (getSuperclassFQN(), name, argumentsTypes, staticOnly, typeSolver); - if (superClassMethodRef.isSolved()) { - candidates.add(superClassMethodRef.getCorrespondingDeclaration()); } // add the method declaration of the interfaces to the candidates, if present Should we check if the method is null? } // add the method declaration of the superclass to the candidates, if present + String superclassFQN = getSuperclassFQN(); + if (superclassFQN != null) { + SymbolReference<ResolvedMethodDeclaration> superClassMethodRef = MethodResolutionLogic.solveMethodInFQN + (superclassFQN, name, argumentsTypes, staticOnly, typeSolver); + if (superClassMethodRef.isSolved()) { + candidates.add(superClassMethodRef.getCorrespondingDeclaration()); + } } // add the method declaration of the interfaces to the candidates, if present
codereview_java_data_7113
* @return A new {@code Option} instance containing value of type {@code R} * @throws NullPointerException if {@code partialFunction} is null */ - default <R> Option<R> collect(PartialFunction<? super T, ? extends R> partialFunction){ Objects.requireNonNull(partialFunction, "partialFunction is null"); - final Option<T> valueInDomain = filter(partialFunction::isDefinedAt); - return valueInDomain.isEmpty() ? none(): some(partialFunction.apply(valueInDomain.get())); } /** Please `return filter(partialFunction::isDefinedAt).map(partialFunction::apply);`. We try to omit if-branches if possible. * @return A new {@code Option} instance containing value of type {@code R} * @throws NullPointerException if {@code partialFunction} is null */ + default <R> Option<R> collect(PartialFunction<? super T, ? extends R> partialFunction) { Objects.requireNonNull(partialFunction, "partialFunction is null"); + return filter(partialFunction::isDefinedAt).map(partialFunction::apply); } /**
codereview_java_data_7115
*/ public static CharSeq of(char... characters) { Objects.requireNonNull(characters, "characters is null"); - final char[] chrs = new char[characters.length]; - System.arraycopy(characters, 0, chrs, 0, characters.length); - return characters.length == 0 ? empty() : new CharSeq(new String(chrs)); } /** Hi Simone! I would made this check before ``` final char[] chrs = ... ``` to avoid instantiate empty char[] */ public static CharSeq of(char... characters) { Objects.requireNonNull(characters, "characters is null"); + if (characters.length == 0) { + return empty(); + } else { + final char[] chrs = new char[characters.length]; + System.arraycopy(characters, 0, chrs, 0, characters.length); + return new CharSeq(new String(chrs)); + } } /**
codereview_java_data_7123
VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironment(extent.getTableId(), context); - Path newDir = new Path(vm.choose(chooserEnv, - ServerConstants.getBaseUris(context.getConfiguration(), context.getHadoopConf())) + Path.SEPARATOR + ServerConstants.TABLE_DIR + Path.SEPARATOR + dir.getParent().getName() + Path.SEPARATOR + dir.getName()); Could only context be passed here? VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironment(extent.getTableId(), context); + Path newDir = new Path(vm.choose(chooserEnv, ServerConstants.getBaseUris(context)) + Path.SEPARATOR + ServerConstants.TABLE_DIR + Path.SEPARATOR + dir.getParent().getName() + Path.SEPARATOR + dir.getName());