id stringlengths 23 26 | content stringlengths 182 2.49k |
|---|---|
codereview_java_data_8857 | import org.apache.accumulo.core.data.TableId;
import org.apache.accumulo.core.dataImpl.KeyExtent;
import org.apache.accumulo.core.metadata.RootTable;
-import org.apache.accumulo.core.metadata.schema.*;
import org.apache.accumulo.core.metadata.schema.TabletMetadata.ColumnType;
-import org.apache.accumulo.core.metadata.schema.TabletsMetadata.TableOptions;
import org.apache.accumulo.core.util.HostAndPort;
import org.apache.accumulo.server.master.state.TabletLocationState.BadLocationStateException;
import org.apache.accumulo.server.metadata.TabletMutatorBase;
Just a note: our checkstyle rules prevent wildcard imports.
import org.apache.accumulo.core.data.TableId;
import org.apache.accumulo.core.dataImpl.KeyExtent;
import org.apache.accumulo.core.metadata.RootTable;
+import org.apache.accumulo.core.metadata.schema.Ample;
+import org.apache.accumulo.core.metadata.schema.RootTabletMetadata;
+import org.apache.accumulo.core.metadata.schema.TabletMetadata;
import org.apache.accumulo.core.metadata.schema.TabletMetadata.ColumnType;
import org.apache.accumulo.core.util.HostAndPort;
import org.apache.accumulo.server.master.state.TabletLocationState.BadLocationStateException;
import org.apache.accumulo.server.metadata.TabletMutatorBase; |
codereview_java_data_8859 | Type currentType = schema.asStruct();
while (pathIterator.hasNext()) {
- if (currentType == null || !currentType.isStructType()) return false;
String fieldName = pathIterator.next();
currentType = currentType.asStructType().fieldType(fieldName);
}
Style: control flow should always use `{` and `}`.
Type currentType = schema.asStruct();
while (pathIterator.hasNext()) {
+ if (currentType == null || !currentType.isStructType()) {
+ return false;
+ }
String fieldName = pathIterator.next();
currentType = currentType.asStructType().fieldType(fieldName);
} |
codereview_java_data_8863 | String topic = commandLine.getOptionValue("t").trim();
String timeStampStr = commandLine.getOptionValue("s").trim();
//when the param "timestamp" is set to now,it should return the max offset of this queue
- long timestamp = timeStampStr.equals("now") ? -1 : 0;
try {
if (timestamp == 0) {
How to change to -1 is still in line with the semantics of now?
String topic = commandLine.getOptionValue("t").trim();
String timeStampStr = commandLine.getOptionValue("s").trim();
//when the param "timestamp" is set to now,it should return the max offset of this queue
+ long timestamp = timeStampStr.equals("now") ? TIMESTAMP_BY_NOW : 0;
try {
if (timestamp == 0) { |
codereview_java_data_8865 | static final class isBasicAuthRequired implements Condition {
@Override
- public boolean matches(ConditionContext condition, AnnotatedTypeMetadata annotatedTypeMetadata) {
- String userName = condition.getEnvironment().getProperty("zipkin.storage.elasticsearch.basic-auth-user-name");
- String password = condition.getEnvironment().getProperty("zipkin.storage.elasticsearch.basic-auth-password");
return !isEmpty(userName) && !isEmpty(password);
}
}
please simplify to "basic-auth-user-name" to just "username" and same for password (the property name is overly specific as we won't have any other approach)
static final class isBasicAuthRequired implements Condition {
@Override
+ public boolean matches(ConditionContext condition,
+ AnnotatedTypeMetadata annotatedTypeMetadata) {
+ String userName = condition.getEnvironment()
+ .getProperty("zipkin.storage.elasticsearch.basic-auth-user-name");
+ String password = condition.getEnvironment()
+ .getProperty("zipkin.storage.elasticsearch.basic-auth-password");
return !isEmpty(userName) && !isEmpty(password);
}
} |
codereview_java_data_8872 | /**
* Narrows the given {@code CheckedFunction0<? extends R>} to {@code CheckedFunction0<R>}
*
- * @param wideFunction A {@code CheckedFunction0}
* @param <R> return type
- * @return the given {@code wideFunction} instance as narrowed type {@code CheckedFunction0<R>}
*/
@SuppressWarnings("unchecked")
- static <R> CheckedFunction0<R> narrow(CheckedFunction0<? extends R> wideFunction) {
- return (CheckedFunction0<R>) wideFunction;
}
/**
For Functions / CheckedFunctions we use per default `f` as identifier. However, that's merely the only abbreviation. Predicate and Supplier are named _predicate_ and _supplier_. Consumer is often called _action_ throughout the codebase. (Changing `wideFunction` to `f` should be a no-brainer because it is generated code.)
/**
* Narrows the given {@code CheckedFunction0<? extends R>} to {@code CheckedFunction0<R>}
*
+ * @param f A {@code CheckedFunction0}
* @param <R> return type
+ * @return the given {@code f} instance as narrowed type {@code CheckedFunction0<R>}
*/
@SuppressWarnings("unchecked")
+ static <R> CheckedFunction0<R> narrow(CheckedFunction0<? extends R> f) {
+ return (CheckedFunction0<R>) f;
}
/** |
codereview_java_data_8873 | private final Optional<String> schedule;
private final Optional<String> quartzSchedule;
private final Optional<ScheduleType> scheduleType;
- private final Optional<TimeZone> scheduledTimeZone;
private final Optional<Long> killOldNonLongRunningTasksAfterMillis;
private final Optional<Long> scheduledExpectedRuntimeMillis;
i'd keep the naming consistent and go with `scheduleTimeZone`
private final Optional<String> schedule;
private final Optional<String> quartzSchedule;
private final Optional<ScheduleType> scheduleType;
+ private final Optional<TimeZone> scheduleTimeZone;
private final Optional<Long> killOldNonLongRunningTasksAfterMillis;
private final Optional<Long> scheduledExpectedRuntimeMillis; |
codereview_java_data_8885 | private final HazelcastInstance instance;
private final ILogger logger;
- private final IMap<Long, Integer> executionCounts;
private final IMap<Long, JobRecord> jobRecords;
private final IMap<Long, JobExecutionRecord> jobExecutionRecords;
private final IMap<Long, JobResult> jobResults;
This should be configurable using a property.
private final HazelcastInstance instance;
private final ILogger logger;
private final IMap<Long, JobRecord> jobRecords;
private final IMap<Long, JobExecutionRecord> jobExecutionRecords;
private final IMap<Long, JobResult> jobResults; |
codereview_java_data_8902 | this.instanceNumber = instanceNumber;
builder.directory(workDir.toFile());
String workDirPath = workDir.toFile().getAbsolutePath();
- this.stdout =
- Files.createFile(FileSystems.getDefault().getPath(workDirPath, "stdout_" + instanceNumber + ".log")).toFile();
- this.stderr =
- Files.createFile(FileSystems.getDefault().getPath(workDirPath, "stderr_" + instanceNumber + ".log")).toFile();
builder.redirectOutput(this.stdout);
builder.redirectError(this.stderr);
builder.environment().put("INSTANCE_INDEX", Integer.toString(instanceNumber));
~~I the root directory is global for all deployments, then file name needs to include stream name as well~~ Hmm, seems there is one dir per deployment id already, each dir being underneath the global one.
this.instanceNumber = instanceNumber;
builder.directory(workDir.toFile());
String workDirPath = workDir.toFile().getAbsolutePath();
+ this.stdout = Files.createFile(Paths.get(workDirPath, "stdout_" + instanceNumber + ".log")).toFile();
+ this.stderr = Files.createFile(Paths.get(workDirPath, "stderr_" + instanceNumber + ".log")).toFile();
builder.redirectOutput(this.stdout);
builder.redirectError(this.stderr);
builder.environment().put("INSTANCE_INDEX", Integer.toString(instanceNumber)); |
codereview_java_data_8905 | db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_FEED_PLAYBACK_SPEED + " TEXT");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_MEDIA
- + " ADD COLUMN " + PodDBAdapter.KEY_LAST_PLAYBACK_SPEED + " TEXT");
}
}
This feature won't be in 1.7.3, please change to 1.7.4
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_FEED_PLAYBACK_SPEED + " TEXT");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_MEDIA
+ + " ADD COLUMN " + PodDBAdapter.KEY_MEDIA_LAST_PLAYBACK_SPEED + " REAL DEFAULT " + LAST_PLAYBACK_SPEED_UNSET);
}
} |
codereview_java_data_8917 | checkForFailures();
- if (startTime.compareAndSet(0, System.currentTimeMillis())) {
List<GarbageCollectorMXBean> gcmBeans = ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean garbageCollectorMXBean : gcmBeans) {
Now that checkForFailures is not called in a synch block may throw ConcurrentModificationExceptions as its impl iterates over collections that other threads may modify.
checkForFailures();
+ if (startTime == 0) {
+ startTime = System.currentTimeMillis();
List<GarbageCollectorMXBean> gcmBeans = ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean garbageCollectorMXBean : gcmBeans) { |
codereview_java_data_8922 | return readOnlyGroups;
}
- public boolean isBounceAfterScale() {
- return bounceAfterScale.or(Boolean.FALSE).booleanValue();
}
@Override
You need one that is the Json getter that just returns the actual value. If you want to add a helper, you should @JsonIGnore it.
return readOnlyGroups;
}
+ public Optional<Boolean> getBounceAfterScale() {
+ return bounceAfterScale;
}
@Override |
codereview_java_data_8924 | * ANY whenever possible.</p>
*/
public enum NullPolicy {
-
- /** Returns null if and only if all of the arguments are null;
- * If all of the arguments are false return false otherwise true. */
- ALL,
/** Returns null if and only if one of the arguments are null. */
STRICT,
/** Returns null if one of the arguments is null, and possibly other times. */
> If all of the arguments are false return false otherwise true. Do we support this? I think the policy is just for `null` value.
* ANY whenever possible.</p>
*/
public enum NullPolicy {
/** Returns null if and only if one of the arguments are null. */
STRICT,
/** Returns null if one of the arguments is null, and possibly other times. */ |
codereview_java_data_8929 | listUsersResult = getUserpoolLL().listUsers(listUsersRequest);
for (UserType user : listUsersResult.getUsers()) {
if (USERNAME.equals(user.getUsername())
- || "bimin".equals(user.getUsername()) || "roskumr@amazon.com".equals(user.getUsername())) {
// This user is saved to test the identity id permanence
continue;
}
Can we set up a test user rather than using hardcoded individual names?
listUsersResult = getUserpoolLL().listUsers(listUsersRequest);
for (UserType user : listUsersResult.getUsers()) {
if (USERNAME.equals(user.getUsername())
+ || "bimin".equals(user.getUsername()) || "customAuthTestUser".equals(user.getUsername())) {
// This user is saved to test the identity id permanence
continue;
} |
codereview_java_data_8936 | final String children = tree.getChildren()
.map(child -> toString(child, depth + 1))
.join();
- return String.format("%n%s%s%s", indent, value, children);
}
}
}
This has to be a `\n`, not a `%n` to create a new line.
final String children = tree.getChildren()
.map(child -> toString(child, depth + 1))
.join();
+ return String.format("\n%s%s%s", indent, value, children);
}
}
} |
codereview_java_data_8941 | public void toStringTest() {
final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde"));
- assertEquals("abcbcdcde", list.toString());
}
}
This could be instead be "[abc, bcd, cde]" with the changes I suggested
public void toStringTest() {
final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde"));
+ assertEquals("[abc, bcd, cde]", list.toString());
}
} |
codereview_java_data_8943 | cipher = new NullCipher();
} else {
try {
- cipher = Cipher.getInstance(cipherSuite, securityProvider);
} catch (NoSuchAlgorithmException e) {
log.error(String.format("Accumulo configuration file contained a cipher suite \"%s\" that was not recognized by any providers", cipherSuite));
throw new RuntimeException(e);
This will override the system-wide prioritized crypto providers for Java set by the system administrator. This may be okay in some cases, but I don't think this should be the default. I think that we should set the default value to be null, instead of SunJCE, and if it is null, then we call the one-parameter version of this method, which respects the system-wide security settings. The specific provider should only be used if it's not null. Doing it the way I'm suggesting will be much friendlier on system administrators trying to ensure their systems are compliant with their organizational requirements. It also makes more sense if a single crypto doesn't support all of the algorithms the user has specified, because the default behavior is to search the providers set by the system administrator to find one that will work for a given algorithm.
cipher = new NullCipher();
} else {
try {
+ if (securityProvider == null || securityProvider.equals("")) {
+ cipher = Cipher.getInstance(cipherSuite);
+ } else {
+ cipher = Cipher.getInstance(cipherSuite, securityProvider);
+ }
} catch (NoSuchAlgorithmException e) {
log.error(String.format("Accumulo configuration file contained a cipher suite \"%s\" that was not recognized by any providers", cipherSuite));
throw new RuntimeException(e); |
codereview_java_data_8946 | */
void setVariable( String variableName, Object value );
KieRuntime getKieRuntime();
}
\ No newline at end of file
Can you add a `@Deprecated` annotation? What about also add a `getKogitoProcessRuntime()` method? If we can use this method instead of `getKieRuntime` we should be already on the safe side. Wdyt?
*/
void setVariable( String variableName, Object value );
+ @Deprecated
KieRuntime getKieRuntime();
+
+ KogitoProcessRuntime getKogitoProcessRuntime();
}
\ No newline at end of file |
codereview_java_data_8947 | import org.ehcache.clustered.common.messages.EhcacheEntityResponse;
import org.ehcache.clustered.common.messages.EhcacheEntityResponse.Failure;
import org.ehcache.clustered.common.messages.EhcacheEntityResponse.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terracotta.connection.entity.Entity;
I would like to have a bit more error handling here - although it should never happen. But a class cast exception without context seems a bit bland.
import org.ehcache.clustered.common.messages.EhcacheEntityResponse;
import org.ehcache.clustered.common.messages.EhcacheEntityResponse.Failure;
import org.ehcache.clustered.common.messages.EhcacheEntityResponse.Type;
+import org.ehcache.clustered.common.messages.ServerStoreOpMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terracotta.connection.entity.Entity; |
codereview_java_data_8955 | @Nullable public Map<String, String> getContinuation() {
return continuation;
}
-}
\ No newline at end of file
Revert changes to this file.
@Nullable public Map<String, String> getContinuation() {
return continuation;
}
\ No newline at end of file
+} |
codereview_java_data_8957 | import tech.pegasys.pantheon.tests.acceptance.dsl.node.Node;
import java.io.IOException;
-import javax.annotation.concurrent.Immutable;
-@Immutable
public class Blockchain {
public Condition blockNumberMustBeLatest(final Node node) throws IOException {
Might need a better name here as it's a little unclear whether `node` has to be the latest and what latest actual is. `chainHeadMustHaveCaughtUpTo(node)` maybe? Difficult one to name to be honest...
import tech.pegasys.pantheon.tests.acceptance.dsl.node.Node;
import java.io.IOException;
public class Blockchain {
public Condition blockNumberMustBeLatest(final Node node) throws IOException { |
codereview_java_data_8967 | T visit(LogicalTableModify modify) throws E;
- T visit(T other) throws E;
}
Maybe we can add `T visit(RelNode other) throws E; too`
T visit(LogicalTableModify modify) throws E;
+ T visit(RelNode other) throws E;
} |
codereview_java_data_8969 | @RunWith(MockitoJUnitRunner.class)
public class WithMockOidcUserSecurityContextTests {
@Mock
private WithMockOidcUser withUser;
Would you please re-arrange the method names so that they look like `valueWhenUserNameIsNullThenDefaultsUserId`? In new classes, the team has standardized on `methodNameWhenCircumstanceThenResult`.
@RunWith(MockitoJUnitRunner.class)
public class WithMockOidcUserSecurityContextTests {
+ private final static String USER_VALUE = "valueUser";
@Mock
private WithMockOidcUser withUser; |
codereview_java_data_8971 | remover.skipOnCompletion = true;
int playerStatus = PlaybackPreferences.getCurrentPlayerStatus();
if(playerStatus == PlaybackPreferences.PLAYER_STATUS_PLAYING) {
- sendBroadcast(new Intent(
- PlaybackService.ACTION_PAUSE_PLAY_CURRENT_EPISODE)
- .setPackage(getPackageName()));
}
}
remover.executeAsync();
It would make the purpose explicit if the pattern is factored out to a generic helper, e.g., `InAppBroadcastUtil.sendBroadcast(Context, Intent)`
remover.skipOnCompletion = true;
int playerStatus = PlaybackPreferences.getCurrentPlayerStatus();
if(playerStatus == PlaybackPreferences.PLAYER_STATUS_PLAYING) {
+ IntentUtils.sendLocalBroadcast(MainActivity.this, PlaybackService.ACTION_PAUSE_PLAY_CURRENT_EPISODE);
}
}
remover.executeAsync(); |
codereview_java_data_8991 | Expression expressionObject = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getExpressionManager().createExpression(expression);
value = expressionObject.getValue(planItemInstanceEntity);
if (resultVariable != null) {
- if(storeResultVariableAsTransient) {
planItemInstanceEntity.setTransientVariable(resultVariable, value);
} else {
planItemInstanceEntity.setVariable(resultVariable, value);
missing space "if ("
Expression expressionObject = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getExpressionManager().createExpression(expression);
value = expressionObject.getValue(planItemInstanceEntity);
if (resultVariable != null) {
+ if (storeResultVariableAsTransient) {
planItemInstanceEntity.setTransientVariable(resultVariable, value);
} else {
planItemInstanceEntity.setVariable(resultVariable, value); |
codereview_java_data_8992 | ByteString b0, long b1, BinaryOperator<Byte> bitOp) {
final byte[] bytes0 = b0.getBytes();
- final byte[] result = new byte[bytes0.length];
for (int i = 0; i < bytes0.length; i++) {
- result[i] = bitOp.apply((byte) (b1 >> 8 * (bytes0.length - i - 1)), bytes0[i]);
}
- return new ByteString(result);
}
// EXP
Could you please remove `result` allocation and replace it with `bytes0`? An alternative could be to use `b0.byteAt(...)`
ByteString b0, long b1, BinaryOperator<Byte> bitOp) {
final byte[] bytes0 = b0.getBytes();
for (int i = 0; i < bytes0.length; i++) {
+ bytes0[i] = bitOp.apply((byte) (b1 >> 8 * (bytes0.length - i - 1)), bytes0[i]);
}
+ return new ByteString(bytes0);
}
// EXP |
codereview_java_data_8995 | public SimplePropertyDescriptor() {
}
- public SimplePropertyDescriptor(String name, Method readMethod, Method writeMethod, Field field) {
this.name = name;
this.readMethod = readMethod;
this.writeMethod = writeMethod;
- this.field = field;
}
public String getName() {
Since you pass in null as the last parameter a few times (at least in this class), why not create another constructor?
public SimplePropertyDescriptor() {
}
+ public SimplePropertyDescriptor(String name, Method readMethod, Method writeMethod) {
this.name = name;
this.readMethod = readMethod;
this.writeMethod = writeMethod;
}
public String getName() { |
codereview_java_data_8996 | // Use *only* for tracking the user preference change for EventLogging
// Attempting to use anywhere else will cause kitten explosions
public void log(boolean force) {
- SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(application);
- if (!settings.getBoolean(Prefs.TRACKING_ENABLED, true) && !force) {
return; // User has disabled tracking
}
- LogTask logTask = new LogTask(application.getMWApi());
logTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, this);
}
why are we passing the whole instance of commons application? It just needs the app context and mediawikiapi
// Use *only* for tracking the user preference change for EventLogging
// Attempting to use anywhere else will cause kitten explosions
public void log(boolean force) {
+ if (!prefs.getBoolean(Prefs.TRACKING_ENABLED, true) && !force) {
return; // User has disabled tracking
}
+ LogTask logTask = new LogTask(mwApi);
logTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, this);
} |
codereview_java_data_8998 | lastRow = tablet.getExtent().toMetaRow();
if (loc != null) {
- serverCounts.increment(loc.toString(), 1);
}
}
This seems like a regression. In general, unless you're printing something, it's better to use a more specific type than a String type, and a more specific method name than `toString()`, since `toString()` should not be relied upon to not change over time.
lastRow = tablet.getExtent().toMetaRow();
if (loc != null) {
+ serverCounts.increment(loc.getHostPortSession(), 1);
}
} |
codereview_java_data_9034 | implements ServiceCreationConfiguration<ClusteringService>,
CacheManagerConfiguration<PersistentCacheManager> {
- private static final Collection<String> CLUSTER_SCHEMES = new HashSet<String>(Arrays.asList("terracotta", "passthrough"));
private final URI clusterUri;
private final boolean autoCreate;
This is bad, but I find XSD even worse. Can't we handle that elsewhere?
implements ServiceCreationConfiguration<ClusteringService>,
CacheManagerConfiguration<PersistentCacheManager> {
+ private static final String CLUSTER_SCHEME = "terracotta";
private final URI clusterUri;
private final boolean autoCreate; |
codereview_java_data_9037 | SortedPosDeleteWriter<Record> writer = new SortedPosDeleteWriter<>(appenderFactory, fileFactory, format, null, 100);
try (SortedPosDeleteWriter<Record> closeableWriter = writer) {
- for (int index = 0; index < rowSet.size(); index += 2) {
closeableWriter.delete(dataFile.path(), index);
}
}
I think if we delete them in natural order, sorting them or not in delete writer will result in the correct order. Do we want to initialize the index as 4 and decrement the counter to test the sorting logic?
SortedPosDeleteWriter<Record> writer = new SortedPosDeleteWriter<>(appenderFactory, fileFactory, format, null, 100);
try (SortedPosDeleteWriter<Record> closeableWriter = writer) {
+ for (int index = rowSet.size() - 1; index >= 0; index -= 2) {
closeableWriter.delete(dataFile.path(), index);
}
} |
codereview_java_data_9050 | * @throws TableNotFoundException
* if the table does not exist
* @since 1.6.0
- * @deprecated since 2.1.0; use {@link #getConfiguration(String)} (String)} instead.
*/
- @Deprecated(since = "2.1.0")
- Iterable<Entry<String,String>> getProperties(String tableName)
- throws AccumuloException, TableNotFoundException;
/**
* Gets properties of a table. This operation is asynchronous and eventually consistent. It is not
If a default method is used in the interface, most, if not all, of the implementing classes and subclasses can simply remove their implementing method: ```suggestion * @since 1.6.0 */ default Iterable<Entry<String,String>> getProperties(String tableName) throws AccumuloException, TableNotFoundException { return getConfiguration(tableName).entrySet(); } ``` (and the same can be done in NamespaceOperations and its implementing classes and subclasses)
* @throws TableNotFoundException
* if the table does not exist
* @since 1.6.0
*/
+ default Iterable<Entry<String,String>> getProperties(String tableName)
+ throws AccumuloException, TableNotFoundException {
+ return getConfiguration(tableName).entrySet();
+ }
/**
* Gets properties of a table. This operation is asynchronous and eventually consistent. It is not |
codereview_java_data_9062 | private final HashMap<String/* topic */, List<QueueData>> topicQueueTable;
private final HashMap<String/* brokerName */, BrokerData> brokerAddrTable;
private final HashMap<String/* clusterName */, Set<String/* brokerName */>> clusterAddrTable;
- private final Map<String/* brokerAddr */, BrokerLiveInfo> brokerLiveTable;
private final HashMap<String/* brokerAddr */, List<String>/* Filter Server */> filterServerTable;
public RouteInfoManager() {
this.topicQueueTable = new HashMap<String, List<QueueData>>(1024);
this.brokerAddrTable = new HashMap<String, BrokerData>(128);
this.clusterAddrTable = new HashMap<String, Set<String>>(32);
- this.brokerLiveTable = new ConcurrentHashMap<String, BrokerLiveInfo>(256);
this.filterServerTable = new HashMap<String, List<String>>(256);
}
In the most situation, this hashmap was protected by a ReentrantReadWriteLock, so if we changed this map to ConcurrentHashmMap will cause less consistent with other codes, could we also use the lock to ensure thread safety?
private final HashMap<String/* topic */, List<QueueData>> topicQueueTable;
private final HashMap<String/* brokerName */, BrokerData> brokerAddrTable;
private final HashMap<String/* clusterName */, Set<String/* brokerName */>> clusterAddrTable;
+ private final HashMap<String/* brokerAddr */, BrokerLiveInfo> brokerLiveTable;
private final HashMap<String/* brokerAddr */, List<String>/* Filter Server */> filterServerTable;
public RouteInfoManager() {
this.topicQueueTable = new HashMap<String, List<QueueData>>(1024);
this.brokerAddrTable = new HashMap<String, BrokerData>(128);
this.clusterAddrTable = new HashMap<String, Set<String>>(32);
+ this.brokerLiveTable = new HashMap<String, BrokerLiveInfo>(256);
this.filterServerTable = new HashMap<String, List<String>>(256);
} |
codereview_java_data_9064 | */
package org.flowable.engine.impl.bpmn.behavior;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
-import static java.util.stream.Collectors.toList;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
Thanks for the PR. This is a *very* small issue given the work done here but the project standards call for all `static` imports to be first in the file. Obviously this doesn't change the execution of the code but is just the chosen style. Thanks again.
*/
package org.flowable.engine.impl.bpmn.behavior;
+import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils; |
codereview_java_data_9091 | private final ImageView icon;
private final ImageView avatar;
private final CheckBox checkBox;
- private View parent;
ContactFieldViewHolder(View itemView) {
super(itemView);
There's no need to hold an explicit reference to parent, since the super class exposes itemView as a public field.
private final ImageView icon;
private final ImageView avatar;
private final CheckBox checkBox;
ContactFieldViewHolder(View itemView) {
super(itemView); |
codereview_java_data_9095 | Map<String, Object> data = objectMapper.readValue(entry.getData(), new TypeReference<HashMap<String, Object>>() {
});
- assertThat(data.get(Fields.PROCESS_DEFINITION_ID)).isNotNull();
- assertThat(data.get(Fields.PROCESS_INSTANCE_ID)).isNotNull();
- assertThat(data.get(Fields.VALUE_STRING)).isNotNull();
assertThat(data.get(Fields.TENANT_ID)).isEqualTo(testTenant);
}
For maps we can in theory use `assertThat(data).containsOnlyKeys(...)`.
Map<String, Object> data = objectMapper.readValue(entry.getData(), new TypeReference<HashMap<String, Object>>() {
});
+ assertThat(data)
+ .containsKeys(
+ Fields.PROCESS_DEFINITION_ID,
+ Fields.PROCESS_INSTANCE_ID,
+ Fields.VALUE_STRING,
+ Fields.TENANT_ID
+ );
assertThat(data.get(Fields.TENANT_ID)).isEqualTo(testTenant);
} |
codereview_java_data_9099 | public abstract class StateHandler<STATE extends State<STATE, CONTEXT>, CONTEXT> {
/**
- * Holds the main logic of StateMachine State.
*
* @param context the {@link Context}.
* @return the next State
*/
- protected abstract STATE getNextState(CONTEXT context) throws OpenemsNamedException;
/**
* Gets called before the StateMachine changes from another State to this State.
I miss s.th. like handleState(), the implementations are doing it in getNextState(), maybe we can split getNextState into two methods.
public abstract class StateHandler<STATE extends State<STATE, CONTEXT>, CONTEXT> {
/**
+ * Runs the main logic of StateMachine State and returns the next State.
*
* @param context the {@link Context}.
* @return the next State
*/
+ protected abstract STATE runAndGetNextState(CONTEXT context) throws OpenemsNamedException;
/**
* Gets called before the StateMachine changes from another State to this State. |
codereview_java_data_9111 | String tenant,
@RequestParam(value = "tag", required = false) String tag)
throws IOException, ServletException, NacosException {
- if (NAMESPACE_PUBLIC_KEY.equalsIgnoreCase(tenant)) {
- tenant = "";
- }
// check params
ParamUtils.checkParam(dataId, group, "datumId", "content");
ParamUtils.checkParam(tag);
Plz try not to have duplicate code, it will be difficult to maintain
String tenant,
@RequestParam(value = "tag", required = false) String tag)
throws IOException, ServletException, NacosException {
+ tenant = processTenant(tenant);
// check params
ParamUtils.checkParam(dataId, group, "datumId", "content");
ParamUtils.checkParam(tag); |
codereview_java_data_9116 | /**
* Remove the given map.
*
- * @param <K> the key type
- * @param <V> the value type
* @param map the map
*/
- <K, V> void removeMap(TransactionMap<K, V> map) {
store.removeMap(map.map);
}
The type arguments can be removed. ```Java void removeMap(TransactionMap<?, ?> map) ```
/**
* Remove the given map.
*
* @param map the map
*/
+ void removeMap(TransactionMap map) {
store.removeMap(map.map);
} |
codereview_java_data_9121 | final SignedData<RoundChangePayload> msg) {
if (!isMessageValid(msg)) {
- LOG.error("RoundChange message was invalid.");
return Optional.empty();
}
probably not an error ... just can't use the message (typically pantheon treats malformed packets as bad, but not terrible, as there are so many actors out there ... its kinda normal)
final SignedData<RoundChangePayload> msg) {
if (!isMessageValid(msg)) {
+ LOG.info("RoundChange message was invalid.");
return Optional.empty();
} |
codereview_java_data_9127 | PartitionField existingField = nameToField.get(newName);
if (existingField != null && isVoidTransform(existingField)) {
// rename the old deleted field that is being replaced by the new field
- renameField(existingField.name(), existingField.name() + "_" + UUID.randomUUID());
}
PartitionField added = nameToAddedField.get(name);
Why use `UUID.randomUUID()` instead of the partition field ID? I think it makes more sense to use `existingField.fieldId()`.
PartitionField existingField = nameToField.get(newName);
if (existingField != null && isVoidTransform(existingField)) {
// rename the old deleted field that is being replaced by the new field
+ renameField(existingField.name(), existingField.name() + "_" + existingField.fieldId());
}
PartitionField added = nameToAddedField.get(name); |
codereview_java_data_9133 | public static Monster getRootAsMonster(ByteBuffer _bb) { return getRootAsMonster(_bb, new Monster()); }
public static Monster getRootAsMonster(ByteBuffer _bb, Monster obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public static Monster getSizePrefixedRootAsMonster(ByteBuffer _psbb) { return getSizePrefixedRootAsMonster(_psbb, new Monster()); }
- public static Monster getSizePrefixedRootAsMonster(ByteBuffer _psbb, Monster obj) { ByteBuffer _bb = _psbb.slice(); _bb.position(4); return getRootAsMonster(_bb, obj); }
public static int getSizePrefix(ByteBuffer _bb) { _bb.order(ByteOrder.LITTLE_ENDIAN); return _bb.getInt(_bb.position()); }
public static boolean MonsterBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "MONS"); }
public void __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; }
Not sure why we're creating a new `ByteBuffer` here, ideally this refers to the existing one?
public static Monster getRootAsMonster(ByteBuffer _bb) { return getRootAsMonster(_bb, new Monster()); }
public static Monster getRootAsMonster(ByteBuffer _bb, Monster obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public static Monster getSizePrefixedRootAsMonster(ByteBuffer _psbb) { return getSizePrefixedRootAsMonster(_psbb, new Monster()); }
+ public static Monster getSizePrefixedRootAsMonster(ByteBuffer _psbb, Monster obj) { ByteBuffer _bb = _psbb.slice(); _bb.position(Constants.SIZE_PREFIX_LENGTH); return getRootAsMonster(_bb, obj); }
public static int getSizePrefix(ByteBuffer _bb) { _bb.order(ByteOrder.LITTLE_ENDIAN); return _bb.getInt(_bb.position()); }
public static boolean MonsterBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "MONS"); }
public void __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; } |
codereview_java_data_9144 | platform = (Platform) getNativePlatform.invoke(null);
} catch (Throwable t) {
platform = null;
- if (LOG.isDebugEnabled())
- LOG.debug("Could not load jnr.ffi.Platform class, this class will not be available.", t);
- else
- LOG.info(
- "Could not load jnr.ffi.Platform class, this class will not be available "
- + "(set this logger level to DEBUG to see the full stack trace).");
}
PLATFORM = platform;
}
I see that contrary to 3.x, in 4.x we only log at DEBUG level, again I think we should harmonize the code.
platform = (Platform) getNativePlatform.invoke(null);
} catch (Throwable t) {
platform = null;
+ LOG.debug("Error loading jnr.ffi.Platform class, this class will not be available.", t);
}
PLATFORM = platform;
} |
codereview_java_data_9154 | try {
startFuture.get(60, TimeUnit.SECONDS);
} catch (final InterruptedException e) {
- LOG.debug("Interrupted while waiting for service to start", e);
Thread.currentThread().interrupt();
- return;
} catch (final ExecutionException e) {
LOG.error("Service " + serviceName + " failed to start", e);
throw new IllegalStateException(e);
Why return and not continue (retry)? That would imply if the thread gets interrupted we don't care if it succeeds or fails to start up
try {
startFuture.get(60, TimeUnit.SECONDS);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
+ throw new IllegalStateException("Interrupted while waiting for service to start", e);
} catch (final ExecutionException e) {
LOG.error("Service " + serviceName + " failed to start", e);
throw new IllegalStateException(e); |
codereview_java_data_9157 | try {
logger.info(message.getContent().toString());
} catch (IOException ex) {
- logger.error("Error occured while sending email: " + ex);
}
}
I guess `logger.error("Error occurred while sending email", ex);` would be even better. What do you think?
try {
logger.info(message.getContent().toString());
} catch (IOException ex) {
+ logger.error("Error occured while sending email", ex);
}
} |
codereview_java_data_9166 | return Iterables.getOnlyElement(tablets);
}
}
-
- public TableOptions readTablets() {
- TableOptions builder = TabletsMetadata.builder();
- return builder;
- }
}
The main difference with moving this Ampl is that the client can be supplied to the builder implementation at the beginning and the final method in the builder can go from `build(client)` to `build()` with no arguments. I would try experimenting with making the following change and removing the client parameter from the build method. ```suggestion TableOptions builder = TabletsMetadata.builder(client); ```
return Iterables.getOnlyElement(tablets);
}
}
} |
codereview_java_data_9167 | LayoutInflater inflater = LayoutInflater.from(container.getContext());
ViewGroup layout = (ViewGroup) inflater.inflate(PAGE_LAYOUTS[position], container, false);
if( BuildConfig.FLAVOR == "beta"){
ViewHolder holder = new ViewHolder(layout);
layout.setTag(holder);
} else {
I dont think it should be part of `else`. Please leave the original `if` check intact.
LayoutInflater inflater = LayoutInflater.from(container.getContext());
ViewGroup layout = (ViewGroup) inflater.inflate(PAGE_LAYOUTS[position], container, false);
if( BuildConfig.FLAVOR == "beta"){
+ TextView textView = (TextView) layout.findViewById(R.id.welcomeYesButton);
+ if( textView.getVisibility() != View.VISIBLE){
+ textView.setVisibility(View.VISIBLE);
+ }
ViewHolder holder = new ViewHolder(layout);
layout.setTag(holder);
} else { |
codereview_java_data_9180 | import tech.pegasys.pantheon.tests.acceptance.dsl.AcceptanceTestBase;
import tech.pegasys.pantheon.tests.acceptance.dsl.account.Account;
-import tech.pegasys.pantheon.tests.acceptance.dsl.condition.Condition;
import tech.pegasys.pantheon.tests.acceptance.dsl.node.PantheonNode;
import java.io.IOException;
Is a hard coded sleep really the best way to achieve this testing? ...typically sleeps are best avoided in tests, in preference for state condition checks with timeouts (and what's the `15_000` magic number mean?)
import tech.pegasys.pantheon.tests.acceptance.dsl.AcceptanceTestBase;
import tech.pegasys.pantheon.tests.acceptance.dsl.account.Account;
import tech.pegasys.pantheon.tests.acceptance.dsl.node.PantheonNode;
import java.io.IOException; |
codereview_java_data_9181 | try {
TopicRouteData topicRouteData = this.mQClientAPIImpl.getTopicRouteInfoFromNameServer(topic, 1000 * 3);
Map<String, BrokerData> brokerDataMap = new HashMap<>();
- for (BrokerData brokerData : topicRouteData.getBrokerDatas()) {
- brokerDataMap.put(brokerData.getBrokerName(), brokerData);
- }
if (topicRouteData != null) {
Set<MessageQueue> newSubscribeInfo = MQClientInstance.topicRouteData2TopicSubscribeInfo(topic, topicRouteData);
Set<AddressableMessageQueue> newAddressableMessageQueueSet = new HashSet<>();
for (MessageQueue mq : newSubscribeInfo) {
should move it into topicRouteData != null condition branch ?
try {
TopicRouteData topicRouteData = this.mQClientAPIImpl.getTopicRouteInfoFromNameServer(topic, 1000 * 3);
Map<String, BrokerData> brokerDataMap = new HashMap<>();
if (topicRouteData != null) {
+ for (BrokerData brokerData : topicRouteData.getBrokerDatas()) {
+ brokerDataMap.put(brokerData.getBrokerName(), brokerData);
+ }
Set<MessageQueue> newSubscribeInfo = MQClientInstance.topicRouteData2TopicSubscribeInfo(topic, topicRouteData);
Set<AddressableMessageQueue> newAddressableMessageQueueSet = new HashSet<>();
for (MessageQueue mq : newSubscribeInfo) { |
codereview_java_data_9182 | }
@Override
- public List<Expression.OpType> getSupportedExpressionTypes() {
LOG.info("[{}]: getSupportedExpressionTypes()", signature);
- return Arrays.asList(OpType.OP_AND, OpType.OP_OR, OpType.OP_EQ, OpType.OP_NE, OpType.OP_NOT, OpType.OP_GE,
OpType.OP_GT, OpType.OP_LE, OpType.OP_LT, OpType.OP_BETWEEN, OpType.OP_IN, OpType.OP_NULL);
}
Should this be a static `ImmutableList`?
}
@Override
+ public ImmutableList<OpType> getSupportedExpressionTypes() {
LOG.info("[{}]: getSupportedExpressionTypes()", signature);
+ return ImmutableList.of(OpType.OP_AND, OpType.OP_OR, OpType.OP_EQ, OpType.OP_NE, OpType.OP_NOT, OpType.OP_GE,
OpType.OP_GT, OpType.OP_LE, OpType.OP_LT, OpType.OP_BETWEEN, OpType.OP_IN, OpType.OP_NULL);
} |
codereview_java_data_9183 | Dataset<Row> validFileDF = validDataFileDF.union(validMetadataFileDF);
Dataset<Row> actualFileDF = buildActualFileDF();
- Column joinCond = actualFileDF.col("file_path").contains(validFileDF.col("file_path"));
List<String> orphanFiles = actualFileDF.join(validFileDF, joinCond, "leftanti")
.as(Encoders.STRING())
.collectAsList();
Isn't this going to cause Spark to use a nested loop join (full join) because there is no way to partition the data for this expression? To fix it, what about using just the file name as well? File names should be unique because we embed the write UUID, partition, and task ID. And if we add both checks, filename could be used to distribute the data without many collisions and contains could be used for final correctness. ```java Column nameEqual = filename(actualFileDF.col("file_path")).equals(filename(validFileDF.col("file_path"))); Column actualContains = actualFileDF.col("file_path").contains(validFileDF.col("file_path")); Column joinCond = nameEqual.and(actualContains); ``` FYI @aokolnychyi.
Dataset<Row> validFileDF = validDataFileDF.union(validMetadataFileDF);
Dataset<Row> actualFileDF = buildActualFileDF();
+ Column nameEqual = filename.apply(actualFileDF.col("file_path"))
+ .equalTo(filename.apply(validFileDF.col("file_path")));
+ Column actualContains = actualFileDF.col("file_path").contains(validFileDF.col("file_path"));
+ Column joinCond = nameEqual.and(actualContains);
List<String> orphanFiles = actualFileDF.join(validFileDF, joinCond, "leftanti")
.as(Encoders.STRING())
.collectAsList(); |
codereview_java_data_9193 | setHint(ellipsizeToWidth(hint));
}
}
- setLayoutParams(getLayoutParams());
}
private CharSequence ellipsizeToWidth(CharSequence text) {
I haven't run this, but I feel like this will just constantly invalidate the layout, given that `setLayoutParams()` calls `requestLayout()` internally.
setHint(ellipsizeToWidth(hint));
}
}
+ if (refreshLayout) {
+
+ refreshLayout = false;
+ }
}
private CharSequence ellipsizeToWidth(CharSequence text) { |
codereview_java_data_9198 | * {@link NullPointerException}s for reasons that still require further investigation, but are assumed to be due to a
* bug in the JDK. Propagating such NPEs is confusing for users and are not subject to being retried on by the default
* retry policy configuration, so instead we bias towards propagating these as {@link IOException}s.
*/
private static int getResponseCodeSafely(HttpURLConnection connection) throws IOException {
Validate.paramNotNull(connection, "connection");
Agree we should revisit this in the future. Can you add a `TODO` here?
* {@link NullPointerException}s for reasons that still require further investigation, but are assumed to be due to a
* bug in the JDK. Propagating such NPEs is confusing for users and are not subject to being retried on by the default
* retry policy configuration, so instead we bias towards propagating these as {@link IOException}s.
+ * <p>
+ * TODO: Determine precise root cause of intermittent NPEs, submit JDK bug report if applicable, and consider applying
+ * this behavior only on unpatched JVM runtime versions.
*/
private static int getResponseCodeSafely(HttpURLConnection connection) throws IOException {
Validate.paramNotNull(connection, "connection"); |
codereview_java_data_9205 | }
private ChainDownloader downloader() {
- final SynchronizerConfiguration syncConfig = SynchronizerConfiguration.builder().build();
return downloader(syncConfig);
}
@Test
public void syncsToBetterChain_multipleSegments() {
otherBlockchainSetup.importFirstBlocks(15);
Should you set up these tests to run on both versions of the downloader?
}
private ChainDownloader downloader() {
+ final SynchronizerConfiguration syncConfig = syncConfigBuilder().build();
return downloader(syncConfig);
}
+ private Builder syncConfigBuilder() {
+ return SynchronizerConfiguration.builder()
+ .piplineDownloaderForFullSyncEnabled(usePipelineDownloader);
+ }
+
@Test
public void syncsToBetterChain_multipleSegments() {
otherBlockchainSetup.importFirstBlocks(15); |
codereview_java_data_9226 | }
scanner.setRange(rangeSplit.getRange());
-
- // do this last after setting all scanner options
- scannerIterator = scanner.iterator();
scannerBase = scanner;
} else if (split instanceof BatchInputSplit) {
Duplicated call to `scanner.iterator()`. Looks like you do it down below too?
}
scanner.setRange(rangeSplit.getRange());
scannerBase = scanner;
} else if (split instanceof BatchInputSplit) { |
codereview_java_data_9231 | private static final int STANDARD_DELAY_FINISH = 1000;
public static final int BUSY_SIGNAL_DELAY_FINISH = 5500;
- public static final String ANSWER_ACTION = RedPhone.class.getName() + ".ANSWER_ACTION";
- public static final String DENY_ACTION = RedPhone.class.getName() + ".DENY_ACTION";
- public static final String END_CALL_ACTION = RedPhone.class.getName() + ".END_CALL_ACTION";
private CallScreen callScreen;
private BroadcastReceiver bluetoothStateReceiver;
small nitpick: getCanonicalName() is more consistent with how other action strings are constructed in other parts of the app (even though getName() would return the same string in this case)
private static final int STANDARD_DELAY_FINISH = 1000;
public static final int BUSY_SIGNAL_DELAY_FINISH = 5500;
+ public static final String ANSWER_ACTION = RedPhone.class.getCanonicalName() + ".ANSWER_ACTION";
+ public static final String DENY_ACTION = RedPhone.class.getCanonicalName() + ".DENY_ACTION";
+ public static final String END_CALL_ACTION = RedPhone.class.getCanonicalName() + ".END_CALL_ACTION";
private CallScreen callScreen;
private BroadcastReceiver bluetoothStateReceiver; |
codereview_java_data_9243 | .with(requiresSecret),
get("/se/grid/newsessionqueuer/queue/size")
.to(() -> new GetNewSessionQueueSize(tracer, this)),
- get("/se/grid/newsessionqueue")
.to(() -> new GetSessionQueue(tracer, this)),
delete("/se/grid/newsessionqueuer/queue")
.to(() -> new ClearSessionQueue(tracer, this))
should it be `newsessionqueue` or `newsessionqueuer`? In case we'd like to be consistent
.with(requiresSecret),
get("/se/grid/newsessionqueuer/queue/size")
.to(() -> new GetNewSessionQueueSize(tracer, this)),
+ get("/se/grid/newsessionqueuer/queue")
.to(() -> new GetSessionQueue(tracer, this)),
delete("/se/grid/newsessionqueuer/queue")
.to(() -> new ClearSessionQueue(tracer, this)) |
codereview_java_data_9248 | }
/**
- * To get the data for Iceberg {@link Record}s we have to use the Hive ObjectInspectors (sourceInspector) to get
- * the Hive primitive types and the Iceberg ObjectInspectors (writerInspector) also if conversion is needed for
* generating the correct type for Iceberg Records. See: {@link WriteObjectInspector} interface on the provided
* writerInspector.
*/
nit: Could you please reformulate this doc? Just split up the long sentence into two parts :)
}
/**
+ * To get the data for Iceberg {@link Record}s we have to use both ObjectInspectors.
+ * <p>
+ * We use the Hive ObjectInspectors (sourceInspector) to get the Hive primitive types.
+ * <p>
+ * We use the Iceberg ObjectInspectors (writerInspector) only if conversion is needed for
* generating the correct type for Iceberg Records. See: {@link WriteObjectInspector} interface on the provided
* writerInspector.
*/ |
codereview_java_data_9255 | initGenerateXPathFromStackTrace();
EventStreams.valuesOf(xpathResultListView.getSelectionModel().selectedItemProperty())
.filter(Objects::nonNull)
.subscribe(parent::onNodeItemSelected);
There's a bug that shows up when selecting an XPath result, then trying to select any other node in the AST treeview. The XPath result will be reselected immediately afterwards, making the whole thing unusable. Fixing that bug requires you to add a `.conditionOn(xpathResultListView.focusedProperty())` call in that pipeline, before the subscribe call.
initGenerateXPathFromStackTrace();
EventStreams.valuesOf(xpathResultListView.getSelectionModel().selectedItemProperty())
+ .conditionOn(xpathResultListView.focusedProperty())
.filter(Objects::nonNull)
.subscribe(parent::onNodeItemSelected); |
codereview_java_data_9259 | private static final String PREFIX = "cv:";
private static final String IGNORE_KEY = "ignored";
- // map for computing summary incrementally stores information in efficient form
private Map<ByteSequence,MutableLong> summary = new HashMap<>();
private long ignored = 0;
Could use LongAddr on jdk8
private static final String PREFIX = "cv:";
private static final String IGNORE_KEY = "ignored";
+ // Map used for computing summary incrementally uses ByteSequence for key which is more efficient than converting colvis to String for each Key. The
+ // conversion to String is deferred until the summary is requested. This shows how the interface enables users to write efficient summarizers.
private Map<ByteSequence,MutableLong> summary = new HashMap<>();
private long ignored = 0; |
codereview_java_data_9272 | Constants.VERSION_MINOR < 4);
/**
- * System property {@code h2.oldResultSetGetObject}, {@code false} by default.
* Return {@code Byte} and {@code Short} instead of {@code Integer} from
* {@code ResultSet#getObject(...)} for {@code TINYINT} and {@code SMALLINT}
* values.
*/
public static final boolean OLD_RESULT_SET_GET_OBJECT =
- Utils.getProperty("h2.oldResultSetGetObject", false);
/**
* System property <code>h2.pgClientEncoding</code> (default: UTF-8).<br />
hmmm, we don't normally change API in a minor point release, so this needs to default to true for now. At some point, we need to bump the version and then set all of these compat flag things to the newer stuff.
Constants.VERSION_MINOR < 4);
/**
+ * System property {@code h2.oldResultSetGetObject}, {@code true} by default.
* Return {@code Byte} and {@code Short} instead of {@code Integer} from
* {@code ResultSet#getObject(...)} for {@code TINYINT} and {@code SMALLINT}
* values.
*/
public static final boolean OLD_RESULT_SET_GET_OBJECT =
+ Utils.getProperty("h2.oldResultSetGetObject", true);
/**
* System property <code>h2.pgClientEncoding</code> (default: UTF-8).<br /> |
codereview_java_data_9278 | return CsvResolver.resolveFields(entry.keySet());
}
- @Override
- protected SupplierEx<QueryTarget> queryTargetSupplier(List<MappingField> resolvedFields) {
- List<String> fieldMap = createFieldList(resolvedFields);
- return () -> new CsvQueryTarget(fieldMap);
- }
-
@Nonnull
private static List<String> createFieldList(List<MappingField> resolvedFields) {
return resolvedFields.stream()
Why `distinct` is needed here? Maybe it should be part of validation?
return CsvResolver.resolveFields(entry.keySet());
}
@Nonnull
private static List<String> createFieldList(List<MappingField> resolvedFields) {
return resolvedFields.stream() |
codereview_java_data_9280 | tablet.computeNumEntries();
- tablet.resetLastLocation();
tablet.setLastCompactionID(compactionId);
t2 = System.currentTimeMillis();
This seems likely where the actual lastLocation information is lost.
tablet.computeNumEntries();
+ lastLocation = tablet.resetLastLocation();
tablet.setLastCompactionID(compactionId);
t2 = System.currentTimeMillis(); |
codereview_java_data_9282 | @Override
public GenericToken getNext() {
- // not required
- return null;
}
@Override
Please either implement this or throw `NotImplementedException` (from lang3) or `UnsupportedOperationException`
@Override
public GenericToken getNext() {
+ throw new UnsupportedOperationException();
}
@Override |
codereview_java_data_9284 | public class Main {
- public static final long startTime = System.currentTimeMillis();
-
/**
* @param args
* - the running arguments for the K3 tool. First argument must be one of the following: kompile|kast|krun.
this is not going to play nice with the k server. Can you please put this in a request-scoped value that is requested by the Main class that is instantiated (see the constructor on line 90) and then inject it into the Profiler2?
public class Main {
/**
* @param args
* - the running arguments for the K3 tool. First argument must be one of the following: kompile|kast|krun. |
codereview_java_data_9286 | import java.util.concurrent.TimeUnit;
import static com.amazonaws.mobile.auth.core.internal.util.ThreadUtils.runOnUiThread;
-import static com.amazonaws.mobile.client.AWSMobileClientPersistenceTest.PASSWORD;
import static com.amazonaws.mobile.client.AWSMobileClientTest.USERNAME;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
For future cleanup, can we put the user & password credentials in the same file?
import java.util.concurrent.TimeUnit;
import static com.amazonaws.mobile.auth.core.internal.util.ThreadUtils.runOnUiThread;
+import static com.amazonaws.mobile.client.AWSMobileClientTest.PASSWORD;
import static com.amazonaws.mobile.client.AWSMobileClientTest.USERNAME;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; |
codereview_java_data_9292 | @JsonProperty("oldestDeployStep") long oldestDeployStep,
@JsonProperty("activeDeploys") List<SingularityDeployMarker> activeDeploys,
@JsonProperty("lateTasks") int lateTasks,
- @JsonProperty("listLateTasks") List<SingularityPendingTask> listLateTasks,
@JsonProperty("futureTasks") int futureTasks,
@JsonProperty("maxTaskLag") long maxTaskLag,
@JsonProperty("generatedAt") long generatedAt,
we probably just want to use the SingularityPendingTaskId here. That will give us the basic information about the request/deploy it belongs to. The SingularityPendingTask can be a very large amount of data (includes lists of artifacts, environment variables, etc, etc), which we wouldn't want to be sending on every call for the state
@JsonProperty("oldestDeployStep") long oldestDeployStep,
@JsonProperty("activeDeploys") List<SingularityDeployMarker> activeDeploys,
@JsonProperty("lateTasks") int lateTasks,
+ @JsonProperty("listLateTasks") List<SingularityPendingTaskId> listLateTasks,
@JsonProperty("futureTasks") int futureTasks,
@JsonProperty("maxTaskLag") long maxTaskLag,
@JsonProperty("generatedAt") long generatedAt, |
codereview_java_data_9295 | prep.setObject(2, "D", Types.VARCHAR);
prep.executeUpdate();
prep.setInt(1, 5);
- prep.setObject(2, 4, Types.INTEGER);
prep.executeUpdate();
ResultSet rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");
if setObject(foo, enum or geometry, Types.OTHER) no longer works, that is an API change, and will quite likely break some client code
prep.setObject(2, "D", Types.VARCHAR);
prep.executeUpdate();
prep.setInt(1, 5);
+ prep.setObject(2, "E", Types.OTHER);
+ prep.executeUpdate();
+ prep.setInt(1, 6);
+ prep.setObject(2, 5, Types.OTHER);
+ prep.executeUpdate();
+ prep.setInt(1, 7);
+ prep.setObject(2, 6, Types.INTEGER);
prep.executeUpdate();
ResultSet rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID"); |
codereview_java_data_9296 | import software.amazon.awssdk.extensions.dynamodb.mappingclient.model.BatchWriteResult;
import software.amazon.awssdk.extensions.dynamodb.mappingclient.model.TransactGetItemsEnhancedRequest;
import software.amazon.awssdk.extensions.dynamodb.mappingclient.model.TransactWriteItemsEnhancedRequest;
-import software.amazon.awssdk.extensions.dynamodb.mappingclient.model.UnmappedItem;
import software.amazon.awssdk.extensions.dynamodb.mappingclient.operations.BatchGetItemOperation;
import software.amazon.awssdk.extensions.dynamodb.mappingclient.operations.BatchWriteItemOperation;
import software.amazon.awssdk.extensions.dynamodb.mappingclient.operations.TransactGetItemsOperation;
We should drop this annotation.
import software.amazon.awssdk.extensions.dynamodb.mappingclient.model.BatchWriteResult;
import software.amazon.awssdk.extensions.dynamodb.mappingclient.model.TransactGetItemsEnhancedRequest;
import software.amazon.awssdk.extensions.dynamodb.mappingclient.model.TransactWriteItemsEnhancedRequest;
+import software.amazon.awssdk.extensions.dynamodb.mappingclient.model.TransactGetResultPage;
import software.amazon.awssdk.extensions.dynamodb.mappingclient.operations.BatchGetItemOperation;
import software.amazon.awssdk.extensions.dynamodb.mappingclient.operations.BatchWriteItemOperation;
import software.amazon.awssdk.extensions.dynamodb.mappingclient.operations.TransactGetItemsOperation; |
codereview_java_data_9300 | */
package org.kie.kogito.monitoring.prometheus.common.rest;
public interface MetricsResource {
}
Is this marker interface necessary?
*/
package org.kie.kogito.monitoring.prometheus.common.rest;
+/**
+ * This class must always have exact FQCN as <code>org.kie.kogito.monitoring.prometheus.common.rest. MetricsResource </code>
+ */
public interface MetricsResource {
} |
codereview_java_data_9313 | @Override
public String[] preferredLocations() {
- if (!enableLocality) {
return new String[0];
}
Any chance `getFileBlockLocations ` returns `null` so we'd end up with a NPE for `b.getHosts()`?
@Override
public String[] preferredLocations() {
+ if (!localityPreferred) {
return new String[0];
} |
codereview_java_data_9319 | return devMode;
}
- public boolean isDiscovery() {
- return discovery;
}
PermissioningConfiguration getPermissioningConfiguration() {
isDiscovery() or discoveryEnabled() ?
return devMode;
}
+ public boolean isDiscoveryEnabled() {
+ return discoveryEnabled;
}
PermissioningConfiguration getPermissioningConfiguration() { |
codereview_java_data_9344 | private boolean isFullInstantiation() {
return !isDocker;
}
-
- private MetricsSystem supplyMetricSystem() {
- if (rpcApis.contains(RpcApis.METRICS)) {
- return PrometheusMetricsSystem.init();
- } else {
- return new NoOpMetricsSystem();
- }
- }
}
Instead of overloading the rpc apis config to enable metrics, I'd just add a new `--metrics` flag or something. The rpc api's currently represent namespaces, and this new `METRICS` option breaks that convention.
private boolean isFullInstantiation() {
return !isDocker;
}
} |
codereview_java_data_9355 | private static final String TAG_NOTIFICATION_WORKER_FRAGMENT = "NotificationWorkerFragment";
private NotificationWorkerFragment mNotificationWorkerFragment;
- private boolean mIsRestoredToTop;
@Override
protected void onCreate(Bundle savedInstanceState) {
I think this one escaped
private static final String TAG_NOTIFICATION_WORKER_FRAGMENT = "NotificationWorkerFragment";
private NotificationWorkerFragment mNotificationWorkerFragment;
@Override
protected void onCreate(Bundle savedInstanceState) { |
codereview_java_data_9359 | AppAdapter.get().getPassword(), "");
}
- //Get CSRFToken response off the main thread.
- Response<MwQueryResponse> response = Executors.newSingleThreadExecutor().submit(new getCSRFTokenResponse(service)).get();
if (response.body() == null || response.body().query() == null
|| TextUtils.isEmpty(response.body().query().csrfToken())) {
Minor: One space after `//`
AppAdapter.get().getPassword(), "");
}
+ // Get CSRFToken response off the main thread.
+ Response<MwQueryResponse> response = Executors.newSingleThreadExecutor().submit(new CsrfTokenCallExecutor(service)).get();
if (response.body() == null || response.body().query() == null
|| TextUtils.isEmpty(response.body().query().csrfToken())) { |
codereview_java_data_9361 | private final static String DEPLOYER_PREFIX = "deployer.";
private final static String COMMAND_ARGUMENT_PREFIX = "cmdarg.";
private final static String DATA_FLOW_URI_KEY = "spring.cloud.dataflow.client.serverUri";
- private final static String KUBERNETES = "kubernetes";
private final static int MAX_SCHEDULE_NAME_LEN = 52;
private CommonApplicationProperties commonApplicationProperties;
We could perhaps move the PLATFORM_TYPE constant values (kubernetes, cloudfoundry and local) from TaskPlatformFactory classes into some common or core module and that way we can re-use them in other places.
private final static String DEPLOYER_PREFIX = "deployer.";
private final static String COMMAND_ARGUMENT_PREFIX = "cmdarg.";
private final static String DATA_FLOW_URI_KEY = "spring.cloud.dataflow.client.serverUri";
private final static int MAX_SCHEDULE_NAME_LEN = 52;
private CommonApplicationProperties commonApplicationProperties; |
codereview_java_data_9365 | if (!StringUtils.hasText(ldif)) {
throw new IllegalArgumentException("Unable to load LDIF " + ldif);
}
- if (!ldif.endsWith(".ldif")) {
- throw new IllegalArgumentException("Unable to load LDIF " + ldif);
- }
}
public int getPort() {
Please remove this check. We do not require the file to have a ".ldif" extension to be processed.
if (!StringUtils.hasText(ldif)) {
throw new IllegalArgumentException("Unable to load LDIF " + ldif);
}
}
public int getPort() { |
codereview_java_data_9366 | package com.palantir.baseline.errorprone;
-import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.jupiter.api.parallel.Execution;
one more nit: mind using our `RefactoringValidator` instead of `BugCheckerRefactoringTestHelper`? Ours validates that the refactored result also passes validation
package com.palantir.baseline.errorprone;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.jupiter.api.parallel.Execution; |
codereview_java_data_9368 | }
URL resource = this.getClass().getResource(fileName);
if (resource != null) {
- return Files.size(Paths.get(this.getClass().getResource(fileName).toURI()));
} else {
return 0;
}
why not just `return Files.size(Paths.get(resource.toURI()));` ?
}
URL resource = this.getClass().getResource(fileName);
if (resource != null) {
+ return Files.size(Paths.get(resource.toURI()));
} else {
return 0;
} |
codereview_java_data_9369 | public class GenesisConfigOptions {
private static final String IBFT_CONFIG_KEY = "ibft";
private static final String CLIQUE_CONFIG_KEY = "clique";
private final JsonObject configRoot;
is there a reason this doesn't do the same as IBFT/clique with regard a class constant?
public class GenesisConfigOptions {
+ private static final String ETHASH_CONFIG_KEY = "ethash";
private static final String IBFT_CONFIG_KEY = "ibft";
private static final String CLIQUE_CONFIG_KEY = "clique";
private final JsonObject configRoot; |
codereview_java_data_9380 | resilienceStrategy.possiblyInconsistent(key, e, e1);
}
}
- return inCache == value ? null : inCache;
}
@Override
I think this is dodgy. At least for the case when the value of `inCache` is loaded from SOR (and possibly for stores that use serialization/copying for values, regardless of the presence of a loader), this reference equality check will surely return false no matter what. In fact, the only time the reference comparison is guaranteed to be meaningful is when your function falls all the way down to `return value`. So you want to have instead: ``` value.equals(inCache) ? null : inCache; ```
resilienceStrategy.possiblyInconsistent(key, e, e1);
}
}
+ return installed.get() ? null : inCache;
}
@Override |
codereview_java_data_9381 | });
/**
- * Constructore that attaches gossip logic to a set of peers
*
* @param peers The always up to date set of connected peers that understand IBFT
*/
nit: typo for constructor
});
/**
+ * Constructor that attaches gossip logic to a set of peers
*
* @param peers The always up to date set of connected peers that understand IBFT
*/ |
codereview_java_data_9387 | if (this.recipients != null) {
recipientsPanel.addRecipients(this.recipients);
} else {
- InputMethodManager input = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
- input.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
Two space indents please. Shouldn't this be showSoftInput, and with a flag of SHOW_IMPLICIT?
if (this.recipients != null) {
recipientsPanel.addRecipients(this.recipients);
} else {
+ InputMethodManager input = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
+ input.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
} |
codereview_java_data_9391 | @BeforeClass
public static void startMetastore() throws Exception {
HiveMetastoreTest.metastore = new TestHiveMetastore();
- metastore.start(new HiveConf(HiveMetastoreTest.class));
HiveMetastoreTest.hiveConf = metastore.hiveConf();
HiveMetastoreTest.metastoreClient = new HiveMetaStoreClient(hiveConf);
String dbPath = metastore.getDatabasePath(DB_NAME);
Is this change needed? `start()` is still defined and uses `HiveMetastoreTest.class`. The only difference is that this doesn't pass a `Configuration` and the parameterless `start` passes `new Configuration()`.
@BeforeClass
public static void startMetastore() throws Exception {
HiveMetastoreTest.metastore = new TestHiveMetastore();
+ metastore.start();
HiveMetastoreTest.hiveConf = metastore.hiveConf();
HiveMetastoreTest.metastoreClient = new HiveMetaStoreClient(hiveConf);
String dbPath = metastore.getDatabasePath(DB_NAME); |
codereview_java_data_9392 | * false} otherwise
*/
public boolean contentEquals(CharSequence cs) {
- return toString().contentEquals(cs);
}
/**
Could be ``` Java delegate.map(Character::toLowerCase).equals(that.delegate.map(Character::toLowerCase)) ``` also, but this should be a lot more optimal (it can short circuit in case of non-equality, and only converts to lowercase if not equal)
* false} otherwise
*/
public boolean contentEquals(CharSequence cs) {
+ return back.contentEquals(cs);
}
/** |
codereview_java_data_9406 | }
}
if (node instanceof MethodCallExpr) {
- Optional<ResolvedMethodDeclaration> result = JavaParserFacade.get(typeSolver)
.solve((MethodCallExpr) node)
.getCorrespondingDeclaration();
- if (result.isPresent()) {
- return resultClass.cast(result.get());
} else {
throw new UnsolvedSymbolException("We are unable to find the method declaration corresponding to " + node);
}
given we're touching these lines already, please rename `result` (here and below) to `declaration` (or `correspondingDeclaration` or `decl` or similar)
}
}
if (node instanceof MethodCallExpr) {
+ Optional<ResolvedMethodDeclaration> methodDeclaration = JavaParserFacade.get(typeSolver)
.solve((MethodCallExpr) node)
.getCorrespondingDeclaration();
+ if (methodDeclaration.isPresent()) {
+ return resultClass.cast(methodDeclaration.get());
} else {
throw new UnsolvedSymbolException("We are unable to find the method declaration corresponding to " + node);
} |
codereview_java_data_9412 | () -> {
try {
return createRemotes();
- } catch (URISyntaxException | SSLException | CertificateException e) {
throw new RuntimeException(e);
}
},
Nit please alphabetise.
() -> {
try {
return createRemotes();
+ } catch (CertificateException | SSLException | URISyntaxException e) {
throw new RuntimeException(e);
}
}, |
codereview_java_data_9418 | private void getTagline() {
OpenFoodAPIService openFoodAPIService = new OpenFoodAPIClient(getActivity(), "https://ssl-api.openfoodfacts.org").getAPIService();
- Call<ArrayList<TaglineLanguageModel>> call = openFoodAPIService.getTagline(getString(R.string.app_name) + " " + Utils.getUserAgent("OTHERS"));
call.enqueue(new Callback<ArrayList<TaglineLanguageModel>>() {
@Override
public void onResponse(Call<ArrayList<TaglineLanguageModel>> call, Response<ArrayList<TaglineLanguageModel>> response) {
samething here. The prefix should be added by `Utils.getUserAgent` In method `Utils.getUserAgent`, we could use `BuildConfig.APPLICATION_ID` as prefix and not `Official Android App `
private void getTagline() {
OpenFoodAPIService openFoodAPIService = new OpenFoodAPIClient(getActivity(), "https://ssl-api.openfoodfacts.org").getAPIService();
+ Call<ArrayList<TaglineLanguageModel>> call = openFoodAPIService.getTagline(Utils.getUserAgent());
call.enqueue(new Callback<ArrayList<TaglineLanguageModel>>() {
@Override
public void onResponse(Call<ArrayList<TaglineLanguageModel>> call, Response<ArrayList<TaglineLanguageModel>> response) { |
codereview_java_data_9425 | package org.openqa.selenium;
/**
- * Created by James Reed on 11/04/2016.
* Thrown to indicate that a click was attempted on an element but was intercepted by another
* element on top of it
*/
We keep who wrote the code anonymous.
package org.openqa.selenium;
/**
* Thrown to indicate that a click was attempted on an element but was intercepted by another
* element on top of it
*/ |
codereview_java_data_9428 | if (StringUtils.isBlank(userName)) {
return;
}
- wikidataEditsText.setText(String.valueOf(0));
compositeDisposable.add(okHttpJsonApiClient
.getWikidataEdits(userName)
.subscribeOn(Schedulers.io())
Is there a reason why you use `String.valueOf(0)` instead of `"0"`?
if (StringUtils.isBlank(userName)) {
return;
}
+ wikidataEditsText.setText("0");
compositeDisposable.add(okHttpJsonApiClient
.getWikidataEdits(userName)
.subscribeOn(Schedulers.io()) |
codereview_java_data_9438 | return getProject()
.provider(() ->
getProject().getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().stream()
- .filter(ss -> !ss.getName().equals(IGNORE_MAIN_CONFIGURATION))
.map(SourceSet::getRuntimeClasspathConfigurationName)
.map(getProject().getConfigurations()::getByName)
.collect(toList()));
Can we extract this snippet up to `getSourceSets().stream().filter(...)` out to a method and reuse it in `validateDependencies` too?
return getProject()
.provider(() ->
getProject().getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().stream()
+ .filter(ss -> !ss.getName().equals(SourceSet.MAIN_SOURCE_SET_NAME))
.map(SourceSet::getRuntimeClasspathConfigurationName)
.map(getProject().getConfigurations()::getByName)
.collect(toList())); |
codereview_java_data_9439 | }
/** SQL {@code string compare string} operator. */
- public static Integer strcmp(String s0, String s1) {
return s0.compareTo(s1);
}
I thin It is better to return `int` instead of `Integer`.
}
/** SQL {@code string compare string} operator. */
+ public static int strcmp(String s0, String s1) {
return s0.compareTo(s1);
} |
codereview_java_data_9445 | @NonNull Uri uri,
@NonNull String defaultMime,
long size,
boolean hasThumbnail,
@Nullable String fileName,
boolean voiceNote)
To revisit this agian, I still kind of want this to be passed in rather than having the model do all this i/o. Off the top of my head, these URI constructions should either be coming from the media store, in which case perhaps we can query the content provider for that info like we do size, or some other source, in which case we can do the long thing of looking at the data itself?
@NonNull Uri uri,
@NonNull String defaultMime,
long size,
+ int width,
+ int height,
boolean hasThumbnail,
@Nullable String fileName,
boolean voiceNote) |
codereview_java_data_9446 | public static void main(String... a) throws Exception {
TestBase test = TestBase.createCaller().init();
// test.config.traceTest = true;
- FilePathEncrypt.register();
- for (int i = 0; i < 100; i++) {
- ((TestFileSystem)test).testConcurrent("encrypt:0007:" + test.getBaseDir() + "/fs");
- test.println("Done pass #" + i);
- }
}
@Override
This temporary change shouldn't be here.
public static void main(String... a) throws Exception {
TestBase test = TestBase.createCaller().init();
// test.config.traceTest = true;
+ test.testFromMain();
}
@Override |
codereview_java_data_9448 | if (trieNode.isReferencedByHash()) {
// If child nodes are reference by hash, we need to download them
final Hash hash = Hash.wrap(trieNode.getHash());
- if (hash.equals(MerklePatriciaTrie.EMPTY_TRIE_NODE_HASH) || hash.equals(BytesValue.EMPTY)) {
return Stream.empty();
}
final NodeDataRequest req = createChildNodeDataRequest(hash);
consider inverting the ".equals(...) statements so that you never have to worry about the hash being null.
if (trieNode.isReferencedByHash()) {
// If child nodes are reference by hash, we need to download them
final Hash hash = Hash.wrap(trieNode.getHash());
+ if (MerklePatriciaTrie.EMPTY_TRIE_NODE_HASH.equals(hash) || BytesValue.EMPTY.equals(hash)) {
return Stream.empty();
}
final NodeDataRequest req = createChildNodeDataRequest(hash); |
codereview_java_data_9468 | @Parameter(names="--md-selector", description="Preprocessor: for .md files, select only the md code blocks that match the selector expression. Ex:'k&(!a|b)'.")
public String mdSelector = "k";
-
- @Parameter(names="--profile-rule-parsing", description="Generate time in seconds to parse each rule in the semantics. Found in -kompiled directory under timing.log.")
- public String profileRules;
}
This is not an appropriate place for this flag because it does not relate to outer parsing.
@Parameter(names="--md-selector", description="Preprocessor: for .md files, select only the md code blocks that match the selector expression. Ex:'k&(!a|b)'.")
public String mdSelector = "k";
} |
codereview_java_data_9471 | */
updater.updateState(download.id, TransferState.WAITING_FOR_NETWORK);
LOGGER.debug("Network Connection Interrupted: " + "Moving the TransferState to WAITING_FOR_NETWORK");
progressListener.progressChanged(new ProgressEvent(0));
return false;
}
Shouldn't we be resetting the progress upon loss of network and then pass `reserEvent` to the `progressListener`?
*/
updater.updateState(download.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_9481 | */
package org.apache.calcite.rel.rel2sql;
-import org.apache.calcite.linq4j.Ord;
import org.apache.calcite.linq4j.tree.Expressions;
import org.apache.calcite.rel.RelFieldCollation;
import org.apache.calcite.rel.RelNode;
what's the difference just use A.class ?
*/
package org.apache.calcite.rel.rel2sql;
import org.apache.calcite.linq4j.tree.Expressions;
import org.apache.calcite.rel.RelFieldCollation;
import org.apache.calcite.rel.RelNode; |
codereview_java_data_9488 | } else {
// The current user has no credentials, let it fail naturally at the RPC layer (no ticket)
// We know this won't work, but we can't do anything else
- log.warn("The current user is a proxy user but there is no underlying real user (RPCs will fail): {}", currentUser);
userForRpc = currentUser;
}
} else {
Why not throw an exception here?
} else {
// The current user has no credentials, let it fail naturally at the RPC layer (no ticket)
// We know this won't work, but we can't do anything else
+ log.warn("The current user is a proxy user but there is no underlying real user (likely that RPCs will fail): {}", currentUser);
userForRpc = currentUser;
}
} else { |
codereview_java_data_9523 | * Call with the user's response to the sign-in challenge.
*
* @param signInChallengeResponse obtained from user
* @return the result containing next steps or done.
* @throws Exception
*/
This would be a breaking change in terms of compilation for a publicly available API. Would prefer to overload this method to accept clientMetadata. ```java confirmSignIn(signInChallengeResponse); confirmSignIn(signInChallengeResponse, clientMetadata); ```
* Call with the user's response to the sign-in challenge.
*
* @param signInChallengeResponse obtained from user
+ * @param clientMetaData Meta data for lambda triggers
* @return the result containing next steps or done.
* @throws Exception
*/ |
codereview_java_data_9541 | try {
String commaSeparatedUids = ImapUtility.join(",", uidWindow);
String command = String.format("UID FETCH %s (%s)", commaSeparatedUids, spaceSeparatedFetchFields);
- Timber.d("Sending command "+command);
connection.sendCommand(command, false);
ImapResponse response;
I assume this is left over from debugging. Please remove.
try {
String commaSeparatedUids = ImapUtility.join(",", uidWindow);
String command = String.format("UID FETCH %s (%s)", commaSeparatedUids, spaceSeparatedFetchFields);
connection.sendCommand(command, false);
ImapResponse response; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.