id stringlengths 23 26 | content stringlengths 182 2.49k |
|---|---|
codereview_java_data_11726 | Seq(NonTerminal(ul.childSort), Terminal(""), NonTerminal(Sort(ul.sort.name() + "#Terminator", ul.sort.params()))),
newAtts.add(Constants.ORIGINAL_PRD, Production.class, ul.pList));
// Es ::= Ne#Es
- prod4 = Production(Seq(), ul.sort, Seq(NonTerminal(Sort("Ne#" + ul.sort.name(), ul.sort.params()))), Att().add("notInjection"));
// Es ::= Es#Terminator // if the list is *
- prod5 = Production(Seq(), ul.sort, Seq(NonTerminal(Sort(ul.sort.name() + "#Terminator", ul.sort.params()))), Att().add("notInjection"));
res.add(prod1);
res.add(prod2);
Maybe make `notInjection` a static String.
Seq(NonTerminal(ul.childSort), Terminal(""), NonTerminal(Sort(ul.sort.name() + "#Terminator", ul.sort.params()))),
newAtts.add(Constants.ORIGINAL_PRD, Production.class, ul.pList));
// Es ::= Ne#Es
+ prod4 = Production(Seq(), ul.sort, Seq(NonTerminal(Sort("Ne#" + ul.sort.name(), ul.sort.params()))), Att().add(NOT_INJECTION));
// Es ::= Es#Terminator // if the list is *
+ prod5 = Production(Seq(), ul.sort, Seq(NonTerminal(Sort(ul.sort.name() + "#Terminator", ul.sort.params()))), Att().add(NOT_INJECTION));
res.add(prod1);
res.add(prod2); |
codereview_java_data_11727 | }
@Override
- public ASTTypeExpression getRhs() {
return (ASTTypeExpression) jjtGetChild(1);
}
/** Gets the wrapped type node. */
public ASTType getTypeNode() {
- return getRhs().getTypeNode();
}
@Override
I'm not sure, if we should do that... We definitely don't need to do it for compatibility reasons, since InfixExpression is new with PMD 7. But representing the node "InstanceOfExpression" in XPath as "InfixExpression" might be surprising, if one looks at the Java AST...
}
@Override
+ public ASTTypeExpression getRightOperand() {
return (ASTTypeExpression) jjtGetChild(1);
}
/** Gets the wrapped type node. */
public ASTType getTypeNode() {
+ return getRightOperand().getTypeNode();
}
@Override |
codereview_java_data_11730 | return s;
}
char[] res = new char[length];
- for (int i = 0; i < s.length(); i++) {
- res[i] = s.charAt(i);
- }
Arrays.fill(res, s.length(), length, ' ');
return new String(res);
}
String#getChars probably faster than this loop
return s;
}
char[] res = new char[length];
+ s.getChars(0, s.length(), res, 0);
Arrays.fill(res, s.length(), length, ' ');
return new String(res);
} |
codereview_java_data_11733 | // @formatter:off
/**
- * Returns the type of this node. The type of a declarator ID is
* <ul>
* <li>1. not necessarily the same as the type written out at the
* start of the declaration, e.g. {@code int a[];}
on this case however, the doc is actually useful as the relation between code / type may be non-obvious on these valid, yet corner cases. Kudos on the detail
// @formatter:off
/**
+ * Returns the type of the declared variable. The type of a declarator ID is
* <ul>
* <li>1. not necessarily the same as the type written out at the
* start of the declaration, e.g. {@code int a[];} |
codereview_java_data_11739 | log.trace("asyncReload called for key: {}", propCacheId);
metrics.incrRefresh();
- return CompletableFuture.supplyAsync(() -> loadIfDifferentVersion(propCacheId, oldValue));
}
@Override
`supplyAsync` may use a jvm wide shared executor service. Seems like this can cause unrelated code in the JVM to interfere with each other, but I am not sure about this.
log.trace("asyncReload called for key: {}", propCacheId);
metrics.incrRefresh();
+ return CompletableFuture.supplyAsync(() -> loadIfDifferentVersion(propCacheId, oldValue),
+ executor);
}
@Override |
codereview_java_data_11740 | }
public CompletableFuture<SyncTarget> findSyncTarget() {
- if (syncState.syncTarget().isPresent() && !syncState.isInSync()) {
- return CompletableFuture.completedFuture(syncState.syncTarget().get());
- }
- return selectNewSyncTarget();
}
private CompletableFuture<SyncTarget> selectNewSyncTarget() {
Overall this looks like the right direction. The `isInSync` check has a small tolerance to avoid rapidly toggling between inSync/outOfSync when a new block is first published but we don't want that behaviour here. It's common to want different tolerances in different situations so we probably should introduce a `isInSync(long tolerance)` variant and use `isInSync(0)` here. We could also remove the `syncState.syncTarget().isPresent()` condition because `isInSync` will always be true if there is no sync target.
}
public CompletableFuture<SyncTarget> findSyncTarget() {
+ return syncState
+ .syncTarget()
+ .map(CompletableFuture::completedFuture) // Return an existing sync target if present
+ .orElseGet(this::selectNewSyncTarget);
}
private CompletableFuture<SyncTarget> selectNewSyncTarget() { |
codereview_java_data_11742 | }
node.getPermissioningConfiguration()
- .map(PermissioningConfiguration::getLocalConfig)
- .map(Optional::get)
.ifPresent(
permissioningConfiguration -> {
if (permissioningConfiguration.isNodeWhitelistEnabled()) {
replace with `.flatMap(PermissioningConfiguration::getLocalConfig)`
}
node.getPermissioningConfiguration()
+ .flatMap(PermissioningConfiguration::getLocalConfig)
.ifPresent(
permissioningConfiguration -> {
if (permissioningConfiguration.isNodeWhitelistEnabled()) { |
codereview_java_data_11761 | extends MergingSnapshotProducer<ReplacePartitions> implements ReplacePartitions {
BaseReplacePartitions(String tableName, TableOperations ops) {
super(tableName, ops);
- set("replace-partitions", "true");
}
@Override
can we make `replace-partitions` property a static variable in `SnaphotSummary.java`?
extends MergingSnapshotProducer<ReplacePartitions> implements ReplacePartitions {
BaseReplacePartitions(String tableName, TableOperations ops) {
super(tableName, ops);
+ set(SnapshotSummary.REPLACE_PARTITIONS_PROP, "true");
}
@Override |
codereview_java_data_11773 | public class ItunesTopListLoader {
private final Context context;
- String LOG = "ITunesTopListLoader";
public ItunesTopListLoader(Context context) {
this.context = context;
In other classes, we call this field TAG (and it's private static final)
public class ItunesTopListLoader {
private final Context context;
+ String TAG = "ITunesTopListLoader";
public ItunesTopListLoader(Context context) {
this.context = context; |
codereview_java_data_11782 | if (suffix.isArguments() && prefix.getNumChildren() == 1 && prefix.getChild(0) instanceof ASTName) {
ASTName name = (ASTName) prefix.getChild(0);
return name.getImage().startsWith("StructuredArguments.")
- || StringUtil.isAnyOf(name.getImage(), STRUCTURED_ARGUMENTS_METHODS);
}
}
}
This could be replaced by a Set.contains call if `STRUCTURED_ARGUMENTS_METHODS` was a Set
if (suffix.isArguments() && prefix.getNumChildren() == 1 && prefix.getChild(0) instanceof ASTName) {
ASTName name = (ASTName) prefix.getChild(0);
return name.getImage().startsWith("StructuredArguments.")
+ || STRUCTURED_ARGUMENTS_METHODS.contains(name.getImage());
}
}
} |
codereview_java_data_11783 | return failOnArtifactWithNoMatchingSignature;
}
- public void seFailOnArtifactWithNoMatchingSignature(
boolean failOnArtifactWithNoMatchingSignature
) {
this.failOnArtifactWithNoMatchingSignature = failOnArtifactWithNoMatchingSignature;
I think you meant `setFailOnArtifactWithNoMatchingSignature`
return failOnArtifactWithNoMatchingSignature;
}
+ public void setFailOnArtifactWithNoMatchingSignature(
boolean failOnArtifactWithNoMatchingSignature
) {
this.failOnArtifactWithNoMatchingSignature = failOnArtifactWithNoMatchingSignature; |
codereview_java_data_11806 | return fileStore != null && fileStore.isReadOnly();
}
- public synchronized double getUpdateFailureRatio() {
long updateCounter = this.updateCounter;
long updateAttemptCounter = this.updateAttemptCounter;
MVMap.RootReference rootReference = meta.getRoot();
why does this need to be synchronized?
return fileStore != null && fileStore.isReadOnly();
}
+ public double getUpdateFailureRatio() {
long updateCounter = this.updateCounter;
long updateAttemptCounter = this.updateAttemptCounter;
MVMap.RootReference rootReference = meta.getRoot(); |
codereview_java_data_11813 | Tasks.range(readTasks.length)
.stopOnFailure()
- .executeWith(readTasksInitExecutorService)
- .run(index -> {
- readTasks[index] = new ReadTask<>(
- scanTasks.get(index), tableBroadcast, expectedSchemaString, caseSensitive,
- localityPreferred, new BatchReaderFactory(batchSize));
- });
LOG.info("Batching input partitions with {} tasks.", readTasks.length);
return Arrays.asList(readTasks);
The block is unnecessary because there is only one expression, can you remove it?
Tasks.range(readTasks.length)
.stopOnFailure()
+ .executeWith(localityPreferred ? ThreadPools.getWorkerPool() : null)
+ .run(index -> readTasks[index] = new ReadTask<>(
+ scanTasks.get(index), tableBroadcast, expectedSchemaString, caseSensitive,
+ localityPreferred, new BatchReaderFactory(batchSize)));
LOG.info("Batching input partitions with {} tasks.", readTasks.length);
return Arrays.asList(readTasks); |
codereview_java_data_11821 | 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()));
I think gradle will get angry at you for using Provider<List<>> instead of ListProperty. If you want to have dynamic set of inputs you have to do it via `getInputs()` similarly to how you handle outputs
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_11827 | List<ExternalCompactionId> statusesToDelete = new ArrayList<>();
- Map<KeyExtent,TabletMetadata> tabletsMetadata = new HashMap<>();
-
- List<KeyExtent> extents =
- batch.stream().map(ecfs -> ecfs.getExtent()).collect(Collectors.toList());
-
try (TabletsMetadata tablets = context.getAmple().readTablets().forTablets(extents)
.fetch(ColumnType.LOCATION, ColumnType.PREV_ROW, ColumnType.ECOMP).build()) {
- tablets.forEach(tm -> tabletsMetadata.put(tm.getExtent(), tm));
}
for (ExternalCompactionFinalState ecfs : batch) {
Can stream directly to a map using a collector (I did a static import of `Function.identity()` and `Collectors.toMap()` to shorten the line for readability): ```suggestion Map<KeyExtent,TabletMetadata> tabletsMetadata; var extents = batch.stream().map(ExternalCompactionFinalState::getExtent).collect(toList()); try (TabletsMetadata tablets = context.getAmple().readTablets().forTablets(extents) .fetch(ColumnType.LOCATION, ColumnType.PREV_ROW, ColumnType.ECOMP).build()) { tabletsMetadata = tablets.stream().collect(toMap(TabletMetadata::getExtent, identity())); } ```
List<ExternalCompactionId> statusesToDelete = new ArrayList<>();
+ Map<KeyExtent,TabletMetadata> tabletsMetadata;
+ var extents = batch.stream().map(ExternalCompactionFinalState::getExtent).collect(toList());
try (TabletsMetadata tablets = context.getAmple().readTablets().forTablets(extents)
.fetch(ColumnType.LOCATION, ColumnType.PREV_ROW, ColumnType.ECOMP).build()) {
+ tabletsMetadata = tablets.stream().collect(toMap(TabletMetadata::getExtent, identity()));
}
for (ExternalCompactionFinalState ecfs : batch) { |
codereview_java_data_11838 | return mProperties.getLong(name);
}
- public long getLong(String name, long defaultValue) {
- return mProperties.getLong(name, defaultValue);
- }
-
public String[] getStringArray(String name) {
return mProperties.getStringArray(name);
}
I think you can remove this method now.
return mProperties.getLong(name);
}
public String[] getStringArray(String name) {
return mProperties.getStringArray(name);
} |
codereview_java_data_11850 | pstmt = con.prepareStatement(INSERT_MESSAGE);
ArchivedMessage message;
int count = 0;
while ((message = messageQueue.poll()) != null) {
- pstmt.setInt(1, getArchivedMessageCount());
pstmt.setLong(2, message.getConversationID());
pstmt.setString(3, message.getFromJID().toBareJID());
pstmt.setString(4, message.getFromJID().getResource());
Wouldn't this need to be done in the same transaction?
pstmt = con.prepareStatement(INSERT_MESSAGE);
ArchivedMessage message;
+
+ int msgCount = getArchivedMessageCount();
+
int count = 0;
while ((message = messageQueue.poll()) != null) {
+ pstmt.setInt(1, ++msgCount);
pstmt.setLong(2, message.getConversationID());
pstmt.setString(3, message.getFromJID().toBareJID());
pstmt.setString(4, message.getFromJID().getResource()); |
codereview_java_data_11854 | return this.constructDsl(streamDefinition.getDslText(), StreamDefinitionServiceUtils.sanitizeStreamAppDefinitions(this.getAppDefinitions(streamDefinition)));
}
- public static String unescape(String text) {
return StringEscapeUtils.unescapeHtml(text);
}
public static method is probably not a good idea.
return this.constructDsl(streamDefinition.getDslText(), StreamDefinitionServiceUtils.sanitizeStreamAppDefinitions(this.getAppDefinitions(streamDefinition)));
}
+ private String unescape(String text) {
return StringEscapeUtils.unescapeHtml(text);
} |
codereview_java_data_11868 | package org.openqa.selenium.devtools.network.types;
/**
* Cookie object
*/
Consider extending Selenium's existing `Cookie` class.
package org.openqa.selenium.devtools.network.types;
+import java.util.Date;
+
/**
* Cookie object
*/ |
codereview_java_data_11872 | "The time to wait for a tablet server to process a bulk import request."),
TSERV_MINTHREADS("tserver.server.threads.minimum", "20", PropertyType.COUNT,
"The minimum number of threads to use to handle incoming requests."),
- TSERV_MINTHREADS_ALLOW_TIMEOUT("tserver.server.thread.timeout.allowed", "true",
PropertyType.BOOLEAN,
"True if the incoming request threads are allowed to timeout with no work available."),
TSERV_THREADCHECK("tserver.server.threadcheck.time", "1s", PropertyType.TIMEDURATION,
The default of true maintains the current behavior, however that behavior seemed problematic in the issue you opened. Makes me wonder if the default should be false.
"The time to wait for a tablet server to process a bulk import request."),
TSERV_MINTHREADS("tserver.server.threads.minimum", "20", PropertyType.COUNT,
"The minimum number of threads to use to handle incoming requests."),
+ TSERV_MINTHREADS_ALLOW_TIMEOUT("tserver.server.thread.timeout.allowed", "false",
PropertyType.BOOLEAN,
"True if the incoming request threads are allowed to timeout with no work available."),
TSERV_THREADCHECK("tserver.server.threadcheck.time", "1s", PropertyType.TIMEDURATION, |
codereview_java_data_11886 | // This plugin interferes with gradles native annotation processor path configuration so need to configure
- // it as well.
project.getPluginManager().withPlugin("org.inferred.processors", processorsplugin ->
project.getConfigurations()
.named(ErrorProneJavacPluginPlugin.CONFIGURATION_NAME)
any chance you could just fix the processors plugin?
// This plugin interferes with gradles native annotation processor path configuration so need to configure
+ // it as well to avoid surprises.
project.getPluginManager().withPlugin("org.inferred.processors", processorsplugin ->
project.getConfigurations()
.named(ErrorProneJavacPluginPlugin.CONFIGURATION_NAME) |
codereview_java_data_11889 | SpringDmnEngineConfigurator dmnConfigurator = context.getBean(SpringDmnEngineConfigurator.class);
SpringFormEngineConfigurator formConfigurator = context.getBean(SpringFormEngineConfigurator.class);
SpringIdmEngineConfigurator idmConfigurator = context.getBean(SpringIdmEngineConfigurator.class);
SpringProcessEngineConfigurator processConfigurator = context.getBean(SpringProcessEngineConfigurator.class);
assertThat(appEngineConfiguration.getConfigurators())
.as("AppEngineConfiguration configurators")
Nice spot about this. However, let's not remove it and instead add ``` assertThat(cmmnEngineConfiguration.isDisableEventRegistry()).isTrue(); assertThat(cmmnEngineConfiguration.getEventRegistryConfigurator()).isNull(); assertThat(processEngineConfiguration.isDisableEventRegistry()).isTrue(); assertThat(processEngineConfiguration.getEventRegistryConfigurator()).isNull(); assertThat(appEngineConfiguration.getEventRegistryConfigurator()) .as("AppEngineConfiguration idmEngineConfigurator") .isSameAs(idmConfigurator); ``` in the appropriate places below. Similar to how it is done for the IDM
SpringDmnEngineConfigurator dmnConfigurator = context.getBean(SpringDmnEngineConfigurator.class);
SpringFormEngineConfigurator formConfigurator = context.getBean(SpringFormEngineConfigurator.class);
SpringIdmEngineConfigurator idmConfigurator = context.getBean(SpringIdmEngineConfigurator.class);
+ SpringEventRegistryConfigurator eventConfigurator = context.getBean(SpringEventRegistryConfigurator.class);
SpringProcessEngineConfigurator processConfigurator = context.getBean(SpringProcessEngineConfigurator.class);
assertThat(appEngineConfiguration.getConfigurators())
.as("AppEngineConfiguration configurators") |
codereview_java_data_11890 | return reflectiveSource(handler, handler.getDef().methods, handlerClass);
}
private static RelMetadataProvider reflectiveSource(
final MetadataHandler target, final ImmutableList<Method> methods,
final Class<? extends MetadataHandler<?>> handlerClass) {
Why do we still need to rely on `handler.getDef().methods`?
return reflectiveSource(handler, handler.getDef().methods, handlerClass);
}
+ @Deprecated // to be removed before 2.0
private static RelMetadataProvider reflectiveSource(
final MetadataHandler target, final ImmutableList<Method> methods,
final Class<? extends MetadataHandler<?>> handlerClass) { |
codereview_java_data_11891 | List<String> lines = IOUtils.readLines(new StringReader(result.content));
List<String> ips = new ArrayList<String>(lines.size());
for (String serverAddr : lines) {
- if (null == serverAddr || serverAddr.trim().isEmpty()) {
- } else {
ips.add(getFormatServerAddr(serverAddr));
}
}
There is no statement in IF block, this is weird. Maybe you can change it into: ``` if (StringUtils.isNotBlank(serverAddr)) { ips.add(getFormatServerAddr(serverAddr)); } ```
List<String> lines = IOUtils.readLines(new StringReader(result.content));
List<String> ips = new ArrayList<String>(lines.size());
for (String serverAddr : lines) {
+ if (StringUtils.isNotBlank(serverAddr)) {
ips.add(getFormatServerAddr(serverAddr));
}
} |
codereview_java_data_11893 | final long now = System.currentTimeMillis();
- if (maybeOldRequestWithState.isPresent() && maybeOldRequestWithState.get().getRequest().isLongRunning()) {
- requestManager.update(newRequest, maybeOldRequestWithState.get().getState(), maybeOldRequest.isPresent() ? RequestHistoryType.UPDATED : RequestHistoryType.CREATED, now, JavaUtils.getUserEmail(user));
} else {
- requestManager.activate(newRequest, maybeOldRequest.isPresent() ? RequestHistoryType.UPDATED : RequestHistoryType.CREATED, now, JavaUtils.getUserEmail(user));
}
checkReschedule(newRequest, maybeOldRequest, now);
if i'm reading this right, paused cron jobs will still get un-paused. i'd welcome @wsorenson's 2 cents on this, but i think we should only call `activate()` if the request didn't previously exist
final long now = System.currentTimeMillis();
+ if (maybeOldRequestWithState.isPresent() && maybeOldRequestWithState.get().getState() != RequestState.FINISHED) {
+ requestManager.update(newRequest, maybeOldRequestWithState.get().getState(), RequestHistoryType.UPDATED, now, JavaUtils.getUserEmail(user));
} else {
+ requestManager.activate(newRequest, maybeOldRequestWithState.isPresent() ? RequestHistoryType.UPDATED : RequestHistoryType.CREATED, now, JavaUtils.getUserEmail(user));
}
checkReschedule(newRequest, maybeOldRequest, now); |
codereview_java_data_11898 | break;
}
}
- } catch (IOException ioe) {
- /**
- * Let the user continue composing their message even if we have a problem processing
- * the source message. Log it as an error, though.
- */
- Log.e(K9.LOG_TAG, "Error while processing source message: ", ioe);
} catch (MessagingException me) {
/**
* Let the user continue composing their message even if we have a problem processing
This is too broad. It should wrap only the individual calls that we reasonable expect to throw it (I think that's just Forward and Report ?). That way if the underlying API for the other methods is changed the developer has to think how to handle an IOE.
break;
}
}
} catch (MessagingException me) {
/**
* Let the user continue composing their message even if we have a problem processing |
codereview_java_data_11922 | @Test
public void leftHandAssignmentCanBeInBraces() {
ParseResult<Expression> result = new JavaParser().parse(EXPRESSION, provider("(i) += (i) += 1"));
- assertProblems(result);
}
}
maybe "assertNoProblems" would be more intuitive in this case?
@Test
public void leftHandAssignmentCanBeInBraces() {
ParseResult<Expression> result = new JavaParser().parse(EXPRESSION, provider("(i) += (i) += 1"));
+ assertNoProblems(result);
}
} |
codereview_java_data_11929 | public String format() {
return CsvFileFormat.FORMAT_CSV;
}
-
- private static int[] createSimpleFieldMap(List<String> fieldList, String[] actualHeader) {
- int[] res = new int[fieldList.size()];
- Arrays.fill(res, -1);
- for (int i = 0; i < actualHeader.length; i++) {
- int index = fieldList.indexOf(actualHeader[i]);
- // if the header is present in the file and we didn't encounter it yet, store its index
- if (index >= 0 && res[index] == -1) {
- res[index] = i;
- }
- }
- return res;
- }
}
Is `res[index] == -1` condition needed?
public String format() {
return CsvFileFormat.FORMAT_CSV;
}
} |
codereview_java_data_11975 | String containerName = String.format("%s%s", configuration.getDockerPrefix(), taskProcess.getTask().getTaskId());
int possiblePid = dockerClient.inspectContainer(containerName).state().pid();
if (possiblePid == 0) {
- LOG.warn(String.format("Container %s has pid 0. Running: (%s). Will not try to get threads", containerName, dockerClient.inspectContainer(containerName).state().running()));
return 0;
} else {
dockerPid = Optional.of(possiblePid);
i'd suggest `"Container %s has pid %s (running: %s). Defaulting to 0 threads running."`
String containerName = String.format("%s%s", configuration.getDockerPrefix(), taskProcess.getTask().getTaskId());
int possiblePid = dockerClient.inspectContainer(containerName).state().pid();
if (possiblePid == 0) {
+ LOG.warn(String.format("Container %s has pid %s (running: %s). Defaulting to 0 threads running.", containerName, possiblePid, dockerClient.inspectContainer(containerName).state().running()));
return 0;
} else {
dockerPid = Optional.of(possiblePid); |
codereview_java_data_11978 | }
case UPPER_BOUND:
case UPPER_WILDCARD:
- case LOWER_WILDCARD:
return new JavaTypeDefinitionSpecial(type, intersectionTypes);
default:
throw new IllegalStateException("Unknow type");
}
who is using this new factory method?
}
case UPPER_BOUND:
case UPPER_WILDCARD:
return new JavaTypeDefinitionSpecial(type, intersectionTypes);
+ case LOWER_WILDCARD:
+ return new JavaTypeDefinitionLower(intersectionTypes);
default:
throw new IllegalStateException("Unknow type");
} |
codereview_java_data_11984 | @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- user = SAVED_USER;
-
}
@Override
How does this help?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override |
codereview_java_data_11985 | import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
public class MyLoginModule implements LoginModule{
String password;
Probably a type cast should be used here instead. If password can have different type also some more complicated code is required, because char arrays are not concatenated properly.
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
+/**
+ * Dummy login module used for test cases
+ */
public class MyLoginModule implements LoginModule{
String password; |
codereview_java_data_11987 | * <pre>{@code
* Pipeline pipeline = Pipeline.create();
* pipeline.<String>readFrom(Sources.list(LIST_NAME))
- * .mapUsingService(JetSpringServiceFactories.beanServiceFactory("userDao", UserDao.class),
* (userDao, item) -> userDao.findByName(item.toLowerCase()))
* .writeTo(Sinks.logger());
* }</pre>
these still refer to old name
* <pre>{@code
* Pipeline pipeline = Pipeline.create();
* pipeline.<String>readFrom(Sources.list(LIST_NAME))
+ * .mapUsingService(JetSpringServiceFactories.bean("userDao", UserDao.class),
* (userDao, item) -> userDao.findByName(item.toLowerCase()))
* .writeTo(Sinks.logger());
* }</pre> |
codereview_java_data_11997 | @Override
public List<ASTAnyTypeBodyDeclaration> getDeclarations() {
- return findChildrenOfType(ASTAnnotationTypeBody.class)
- .get(0).findChildrenOfType(ASTAnyTypeBodyDeclaration.class);
}
}
We could use `getFirstChildOfType` here. I think, we don't need to check for null, since even an empty AnnotationTypeDeclaration has always a AnnotationBody.
@Override
public List<ASTAnyTypeBodyDeclaration> getDeclarations() {
+ return getFirstChildOfType(ASTAnnotationTypeBody.class)
+ .findChildrenOfType(ASTAnyTypeBodyDeclaration.class);
}
} |
codereview_java_data_12011 | public void multipartSigned__shouldCallOpenPgpApiAsync() throws Exception {
BodyPart signedBodyPart;
Message message = messageFromBody(
- multipart("signed", "application/pgp-signature",
signedBodyPart = spy(bodypart("text/plain", "content")),
bodypart("application/pgp-signature", "content")
)
I'm not a fan of inline assignments. Especially since that's the syntax for named arguments in Kotlin.
public void multipartSigned__shouldCallOpenPgpApiAsync() throws Exception {
BodyPart signedBodyPart;
Message message = messageFromBody(
+ multipart("signed", "protocol=\"application/pgp-signature\"",
signedBodyPart = spy(bodypart("text/plain", "content")),
bodypart("application/pgp-signature", "content")
) |
codereview_java_data_12012 | );
} finally {
if (persisterSuccess.get()) {
LOG.info(
- "Request Persister: successful move to history ({} so far)",
- lastPersisterSuccess.incrementAndGet()
);
}
Probably most helpful to set this to something like System.currentTimeMillis() that way we know the last timestamp it ran and can generate an effective 'lag' type of metric off of that. incrementAndGet will just add 1 to the existing value. Logging message would change then too, something like 'finished run on persister at {}' or similar
);
} finally {
if (persisterSuccess.get()) {
+ lastPersisterSuccess.set(System.currentTimeMillis());
LOG.info(
+ "Finished run on request history persist at {}",
+ lastPersisterSuccess.get()
);
} |
codereview_java_data_12031 | SingularityDeployResult deployResult =
getDeployResult(request, cancelRequest, pendingDeploy, updatePendingDeployRequest, deployKey, deploy, deployMatchingTasks, allOtherMatchingTasks, inactiveDeployMatchingTasks);
- LOG.info("Deploy {} had result {} after {}", pendingDeployMarker, deployResult, JavaUtils.durationFromMillis(Math.max(System.currentTimeMillis() - pendingDeployMarker.getTimestamp(), 0)));
if (deployResult.getDeployState() == DeployState.SUCCEEDED) {
if (saveNewDeployState(pendingDeployMarker, Optional.of(pendingDeployMarker))) {
thoughts on moving `Math.max()` into `durationFromMillis()`?
SingularityDeployResult deployResult =
getDeployResult(request, cancelRequest, pendingDeploy, updatePendingDeployRequest, deployKey, deploy, deployMatchingTasks, allOtherMatchingTasks, inactiveDeployMatchingTasks);
+ LOG.info("Deploy {} had result {} after {}", pendingDeployMarker, deployResult, JavaUtils.durationFromMillis(System.currentTimeMillis() - pendingDeployMarker.getTimestamp()));
if (deployResult.getDeployState() == DeployState.SUCCEEDED) {
if (saveNewDeployState(pendingDeployMarker, Optional.of(pendingDeployMarker))) { |
codereview_java_data_12032 | import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static com.hazelcast.jet.Traversers.traverseIterable;
-import static com.hazelcast.jet.hadoop.HdfsSources.REUSE_OBJECT;
import static com.hazelcast.jet.impl.util.ExceptionUtil.sneakyThrow;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
why not just create the instance ourselves, rather than creating and then deleting from cache? It doesn't seem to do any magic.
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static com.hazelcast.jet.Traversers.traverseIterable;
+import static com.hazelcast.jet.hadoop.HdfsSources.COPY_ON_READ;
import static com.hazelcast.jet.impl.util.ExceptionUtil.sneakyThrow;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList; |
codereview_java_data_12039 | }
@GET
- @Path("/singularity-limits-format")
@Operation(summary = "Retrieve configuration data for Singularity")
public SingularityLimits getSingularityLimits() {
return new SingularityLimits(config.getMaxDecommissioningAgents());
Nitpick - can we change this to just `/singularity-limits`?
}
@GET
+ @Path("/singularity-limits")
@Operation(summary = "Retrieve configuration data for Singularity")
public SingularityLimits getSingularityLimits() {
return new SingularityLimits(config.getMaxDecommissioningAgents()); |
codereview_java_data_12042 | <h1>Error 503 Backend is unhealthy</h1>
<p>Backend is unhealthy</p>
<h3>Guru Mediation:</h3>
- <p>Details: cache-sea4444-SEA 1645538750 1560503721</p>
<hr>
<p>Varnish cache server</p>
</body>
This line is part of every test. Might as well extract it to a `setUp()` method.
<h1>Error 503 Backend is unhealthy</h1>
<p>Backend is unhealthy</p>
<h3>Guru Mediation:</h3>
+ <p>Details: cache-sea4473-SEA 1645538750 2103418130</p>
<hr>
<p>Varnish cache server</p>
</body> |
codereview_java_data_12051 | public class ASTAnnotationTypeDeclaration extends AbstractJavaAccessTypeNode implements ASTAnyTypeDeclaration {
- QualifiedName qualifiedName;
public ASTAnnotationTypeDeclaration(int id) {
super(id);
I'd declare this field `qualifiedName` private to hide it. Unless it really needs to be modified from somewhere else... (e.g. unit tests..), but then, we should find a solution, where this field can stay private.
public class ASTAnnotationTypeDeclaration extends AbstractJavaAccessTypeNode implements ASTAnyTypeDeclaration {
+ private QualifiedName qualifiedName;
public ASTAnnotationTypeDeclaration(int id) {
super(id); |
codereview_java_data_12061 | // These Text functions are safe, either because of what they accept or what they return.
"begins", "br", "casesafeid", "contains", "find", "getsessionid", "ispickval", "len",
// These Advanced functions are safe because of what they accept or what they return.
- "currencyrate", "getrecordids", "ischanged", "junctionidlist", "regex", "urlfor"
));
private static final Set<String> FUNCTIONS_WITH_XSSABLE_ARG0 = new HashSet<>(Arrays.asList(
// For these methods, the first argument is a string that must be escaped.
There are now two functions/properties missing: `linkto` and `nullvalue`. Is this correct, that they now create a violation if used without escaping? Previously we ignored these....
// These Text functions are safe, either because of what they accept or what they return.
"begins", "br", "casesafeid", "contains", "find", "getsessionid", "ispickval", "len",
// These Advanced functions are safe because of what they accept or what they return.
+ "currencyrate", "getrecordids", "ischanged", "junctionidlist", "linkto", "regex", "urlfor"
));
private static final Set<String> FUNCTIONS_WITH_XSSABLE_ARG0 = new HashSet<>(Arrays.asList(
// For these methods, the first argument is a string that must be escaped. |
codereview_java_data_12075 | enum State {
ACTIVE(0x00),
AUTHORITY_FILTER_DISABLED(0x01),
- AUTHORITY_SYSTEM_DISABLED(0x02);
private final int principalState;
State(int state) {
somewhat confusing to call this bit as system disabled since the full attribute with combined bits is also called system disabled. So maybe we should call this bit suspended since that's what we're implementing.
enum State {
ACTIVE(0x00),
AUTHORITY_FILTER_DISABLED(0x01),
+ AUTHORITY_SYSTEM_SUSPENDED(0x02);
private final int principalState;
State(int state) { |
codereview_java_data_12082 | @Test
public void shouldReturnModifiedValuesMap() {
- assertThat(HashMap.of(1, "1").put(2, "2").mapValues(Integer::parseInt)).isEqualTo(HashMap.of(1, 1).put(2, 2));
}
// -- merge
We can't use the concrete `HashMap.of` here because it is an abstract Map test, the base for _all_ Map implementations. Please use the methods `empty`, `of` and `ofAll` which are implemented by all AbstractMapTest implementations.
@Test
public void shouldReturnModifiedValuesMap() {
+ assertThat(emptyIntString().put(1, "1").put(2, "2").mapValues(Integer::parseInt)).isEqualTo(emptyMap().put(1, 1).put(2, 2));
}
// -- merge |
codereview_java_data_12099 | PagedResources<MetricResource> list(/* TODO */);
/**
- * Delete the counter with given name
*/
void delete(String name);
}
"...with _the_ given name." <- ends with period for consistency
PagedResources<MetricResource> list(/* TODO */);
/**
+ * Delete the counter with given name.
*/
void delete(String name);
} |
codereview_java_data_12113 | reconnectOften = !config.memory && config.big;
testScript("testScript.sql");
testScript("derived-column-names.sql");
testScript("dual.sql");
testScript("indexes.sql");
I pushed a change that allows to set different expectations in different modes and fixed `joins.sql` with that functionality. So this test should not be disabled, it completes normally now in both MVStore and PageStore modes.
reconnectOften = !config.memory && config.big;
testScript("testScript.sql");
+ testScript("comments.sql");
testScript("derived-column-names.sql");
testScript("dual.sql");
testScript("indexes.sql"); |
codereview_java_data_12125 | }
final LazyKafkaWorkers kafkaWorkers;
- private final Properties properties;
- private AdminClient adminClient;
KafkaCollector(Builder builder) {
kafkaWorkers = new LazyKafkaWorkers(builder);
I would change this to package specific access to reduce the size of the bytecode.
}
final LazyKafkaWorkers kafkaWorkers;
+ final Properties properties;
+ AdminClient adminClient;
KafkaCollector(Builder builder) {
kafkaWorkers = new LazyKafkaWorkers(builder); |
codereview_java_data_12130 | private final ObjectMapper objectMapper;
private final AsyncSemaphore<Response> webhookSemaphore;
- private final ExecutorService webhookExecutorService;
@Inject
public SingularityWebhookSender(SingularityConfiguration configuration, AsyncHttpClient http, ObjectMapper objectMapper, TaskHistoryHelper taskHistoryHelper, WebhookManager webhookManager) {
Doesn't look like this guy is used anywhere after being created.
private final ObjectMapper objectMapper;
private final AsyncSemaphore<Response> webhookSemaphore;
@Inject
public SingularityWebhookSender(SingularityConfiguration configuration, AsyncHttpClient http, ObjectMapper objectMapper, TaskHistoryHelper taskHistoryHelper, WebhookManager webhookManager) { |
codereview_java_data_12133 | private void showFragment(Fragment fragment, String tag, Fragment otherFragment) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (fragment.isAdded() && otherFragment != null) {
- removeFragment(otherFragment);
transaction.hide(otherFragment);
transaction.show(fragment);
transaction.addToBackStack(CONTRIBUTION_LIST_FRAGMENT_TAG);
Hey @Pratham2305 , thanks a lot for the PR. It works as intended. Code looks nice in general. However, I couldn't understand why this line was needed to achieve this task. Can you please explain?
private void showFragment(Fragment fragment, String tag, Fragment otherFragment) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (fragment.isAdded() && otherFragment != null) {
transaction.hide(otherFragment);
transaction.show(fragment);
transaction.addToBackStack(CONTRIBUTION_LIST_FRAGMENT_TAG); |
codereview_java_data_12136 | * Displays a progress indicator.
*/
private void setLoadingLayout() {
- binding.progressBar.setVisibility(View.VISIBLE);
- binding.feedDisplay.setVisibility(View.GONE);
}
@Override
`feedDisplay` is a strange name. I had to look at the xml file to find out what it actually is. How do you feel about `feedDisplayContainer`? I know it was like that before and the guidelines we have come up with say that it is not necessary. How do you feel about this? Should we update the guidelines?
* Displays a progress indicator.
*/
private void setLoadingLayout() {
+ viewBinding.progressBar.setVisibility(View.VISIBLE);
+ viewBinding.feedDisplay.setVisibility(View.GONE);
}
@Override |
codereview_java_data_12149 | protected File generatedResources;
@Parameter(property = "kogito.codegen.persistence", defaultValue = "true")
- protected String persistence;
@Parameter(property = "kogito.codegen.rules", defaultValue = "true")
protected String generateRules;
```suggestion protected String generatePersistence; ``` To keep cohesion between these properties?
protected File generatedResources;
@Parameter(property = "kogito.codegen.persistence", defaultValue = "true")
+ protected String generatePersistence;
@Parameter(property = "kogito.codegen.rules", defaultValue = "true")
protected String generateRules; |
codereview_java_data_12150 | @Before
public void init() throws Exception {
- Field field = MQClientInstance.class.getDeclaredField("brokerAddrTable");
- field.setAccessible(true);
- field.set(mqClientInstance, brokerAddrTable);
}
@Test
mockito and jmockit has native support for the reflection
@Before
public void init() throws Exception {
+ FieldSetter.setField(mqClientInstance, MQClientInstance.class.getDeclaredField("brokerAddrTable"), brokerAddrTable);
}
@Test |
codereview_java_data_12159 | try {
result = httpAgent.httpGet(path, headers, paramValues, encoding, readTimeoutMs);
} catch (IOException e) {
timer.observeDuration();
timer.close();
- throw e;
}
- timer.observeDuration();
- timer.close();
-
return result;
}
Lines 50-51 and 55-56 can be placed on the "finally block", similar below.
try {
result = httpAgent.httpGet(path, headers, paramValues, encoding, readTimeoutMs);
} catch (IOException e) {
+ throw e;
+ } finally {
timer.observeDuration();
timer.close();
}
return result;
} |
codereview_java_data_12160 | @Override
public String toString() {
- return "ParameterizedMetricKey{key=" + key.name() + ", version=" + options + '}';
}
adjust also the string: version= -> options=
@Override
public String toString() {
+ return "ParameterizedMetricKey{key=" + key.name() + ", options=" + options + '}';
} |
codereview_java_data_12169 | .miningParameters(node.getMiningParameters())
.privacyParameters(node.getPrivacyParameters())
.nodePrivateKeyFile(KeyPairUtil.getDefaultKeyFile(node.homeDirectory()))
- .metricsSystem(noOpMetricsSystem)
.transactionPoolConfiguration(TransactionPoolConfiguration.builder().build())
- .rocksDbConfiguration(RocksDbConfiguration.builder().databaseDir(tempDir).build())
.ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.clock(Clock.systemUTC())
.isRevertReasonEnabled(node.isRevertReasonEnabled())
.gasLimitCalculator((gasLimit) -> gasLimit)
.build();
} catch (final IOException e) {
This should be `Function.identity()` (from java.util.function package), here and about 13 other places.
.miningParameters(node.getMiningParameters())
.privacyParameters(node.getPrivacyParameters())
.nodePrivateKeyFile(KeyPairUtil.getDefaultKeyFile(node.homeDirectory()))
+ .metricsSystem(metricsSystem)
.transactionPoolConfiguration(TransactionPoolConfiguration.builder().build())
.ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.clock(Clock.systemUTC())
.isRevertReasonEnabled(node.isRevertReasonEnabled())
+ .storageProvider(storageProvider)
.gasLimitCalculator((gasLimit) -> gasLimit)
.build();
} catch (final IOException e) { |
codereview_java_data_12187 | */
public class LinearViewAnimator extends ViewAnimator {
- Animation mUpInAnimation;
- Animation mUpOutAnimation;
- Animation mDownInAnimation;
- Animation mDownOutAnimation;
public LinearViewAnimator(Context context) {
super(context);
We don't prefix field names with "m" anymore. Also, minimize visibility.
*/
public class LinearViewAnimator extends ViewAnimator {
+ private Animation upInAnimation;
+ private Animation upOutAnimation;
+ private Animation downInAnimation;
+ private Animation downOutAnimation;
public LinearViewAnimator(Context context) {
super(context); |
codereview_java_data_12188 | return Uri.parse(BASE_URI.toString() + "/" + id);
}
- @Inject
- Lazy<DBOpenHelper> dbOpenHelper;
@Override
public boolean onCreate() {
Inconsistent line wrapping compared with other places where annotations are on the same line.
return Uri.parse(BASE_URI.toString() + "/" + id);
}
+ @Inject DBOpenHelper dbOpenHelper;
@Override
public boolean onCreate() { |
codereview_java_data_12189 | -//snippet-sourcedescription:[ListPipelineExecutions.java demonstrates how to all executions for a specific pipeline.]
//snippet-keyword:[SDK for Java 2.0]
//snippet-keyword:[Code Sample]
//snippet-service:[AWS CodePipeline]
"...demonstrates how to _blank_ all executions..."
+//snippet-sourcedescription:[ListPipelineExecutions.java demonstrates how to get all executions for a specific pipeline.]
//snippet-keyword:[SDK for Java 2.0]
//snippet-keyword:[Code Sample]
//snippet-service:[AWS CodePipeline] |
codereview_java_data_12207 | }
private int countEntries(Iterable<Entry<Key,Value>> scanner) {
-
- int count = 0;
-
- for (Entry<Key,Value> keyValueEntry : scanner) {
- count++;
- }
-
- return count;
}
private void setRange(Range range, List<? extends ScannerBase> scanners) {
I think this whole method could be replaced with Guava Iterables.size()
}
private int countEntries(Iterable<Entry<Key,Value>> scanner) {
+ return Iterables.size(scanner);
}
private void setRange(Range range, List<? extends ScannerBase> scanners) { |
codereview_java_data_12216 | this(null, modifiers, new NodeList<>(), new NodeList<>(), type, new SimpleName(name), parameters, new NodeList<>(), new BlockStmt(), null);
}
@AllFieldsConstructor
public MethodDeclaration(final EnumSet<Modifier> modifiers, final NodeList<AnnotationExpr> annotations, final NodeList<TypeParameter> typeParameters, final Type type, final SimpleName name, final NodeList<Parameter> parameters, final NodeList<ReferenceType> thrownExceptions, final BlockStmt body, ReceiverParameter receiverParameter) {
this(null, modifiers, annotations, typeParameters, type, name, parameters, thrownExceptions, body, receiverParameter);
I wonder if it would make sense to exclude receiverParameter from the all fields constructor because it is so rarely used
this(null, modifiers, new NodeList<>(), new NodeList<>(), type, new SimpleName(name), parameters, new NodeList<>(), new BlockStmt(), null);
}
+ public MethodDeclaration(final EnumSet<Modifier> modifiers, final NodeList<AnnotationExpr> annotations, final NodeList<TypeParameter> typeParameters, final Type type, final SimpleName name, final NodeList<Parameter> parameters, final NodeList<ReferenceType> thrownExceptions, final BlockStmt body) {
+ this(null, modifiers, annotations, typeParameters, type, name, parameters, thrownExceptions, body, null);
+ }
+
@AllFieldsConstructor
public MethodDeclaration(final EnumSet<Modifier> modifiers, final NodeList<AnnotationExpr> annotations, final NodeList<TypeParameter> typeParameters, final Type type, final SimpleName name, final NodeList<Parameter> parameters, final NodeList<ReferenceType> thrownExceptions, final BlockStmt body, ReceiverParameter receiverParameter) {
this(null, modifiers, annotations, typeParameters, type, name, parameters, thrownExceptions, body, receiverParameter); |
codereview_java_data_12221 | * Example:
* <pre>
* <code>
- * List.unfold(10, x -> x == 0
* ? Option.none()
- * : Option.of(new Tuple2<>(x, x-1)));
* // List(10, 9, 8, 7, 6, 5, 4, 3, 2, 1))
* </code>
* </pre>
This seems to be the same as e.g. ``` java List.ofAll(Iterator.iterate(10, x -> x - 1).takeWhile(x -> x > 0)); ``` Which seems cleaner to me than the above example :/ (i.e. better separation of concerns)
* Example:
* <pre>
* <code>
+ * List.unfoldRight(10, x -> x == 0
* ? Option.none()
+ * : Option.of(new Tuple2<>(x, x-1)));
* // List(10, 9, 8, 7, 6, 5, 4, 3, 2, 1))
* </code>
* </pre> |
codereview_java_data_12222 | import android.webkit.URLUtil;
import org.apache.commons.io.FileUtils;
-import org.shredzone.flattr4j.model.User;
import org.xml.sax.SAXException;
import java.io.File;
This change (import org.shredzone.flatter4j.model.User;) does not seem relevant to this fix / commit.
import android.webkit.URLUtil;
import org.apache.commons.io.FileUtils;
import org.xml.sax.SAXException;
import java.io.File; |
codereview_java_data_12240 | /** Local index value for when the class is not local. */
static final int NOTLOCAL_PLACEHOLDER = -1;
- // Should we share that with ClassTypeResolver?
- private static final PMDASMClassLoader CLASS_LOADER = PMDASMClassLoader.getInstance(JavaTypeQualifiedName.class.getClassLoader());
// since we prepend each time, these lists are in the reversed order (innermost elem first).
// we use ImmutableList.reverse() to get them in their usual, user-friendly order
Hm.... I think, we need to make sure, to use the auxclasspath here, if we use JavaTypeQualifiedName later for typeresolution... In that case it can't be static final... we need to delegate it somehow from the QualifiedNameVisitor, similar how we do it for the type resolution phase (initializeWith...)
/** Local index value for when the class is not local. */
static final int NOTLOCAL_PLACEHOLDER = -1;
+ private static ClassLoader classLoader = PMDASMClassLoader.getInstance(JavaTypeQualifiedName.class.getClassLoader());
// since we prepend each time, these lists are in the reversed order (innermost elem first).
// we use ImmutableList.reverse() to get them in their usual, user-friendly order |
codereview_java_data_12243 | /**
* Indicator that map is locked for update.
*/
- public final boolean semaphore;
/**
* Reference to the previous root in the chain.
*/
rather call this lockedForUpdate then, semaphore is a bit general (like calling a field "lock") :-)
/**
* Indicator that map is locked for update.
*/
+ public final boolean lockedForUpdate;
/**
* Reference to the previous root in the chain.
*/ |
codereview_java_data_12246 | return LOCALHOST;
}
- private NodeRequests jsonRequestFactories() {
Optional<WebSocketService> websocketService = Optional.empty();
if (nodeRequests == null) {
final Web3jService web3jService;
perhaps rename method as well, nodeRequestFactories?
return LOCALHOST;
}
+ private NodeRequests nodeRequests() {
Optional<WebSocketService> websocketService = Optional.empty();
if (nodeRequests == null) {
final Web3jService web3jService; |
codereview_java_data_12249 | }
MessageAndMetadata<byte[], byte[]> kafkaMessage = mIterator.next();
- Long timestamp = null;
- if (mConfig.useKafkaTimestamp()) {
- timestamp = mKafkaMessageTimestampFactory.create(mKafkaMessageTimestampClassName).getTimestamp(kafkaMessage);
- }
Message message = new Message(kafkaMessage.topic(), kafkaMessage.partition(),
kafkaMessage.offset(), kafkaMessage.key(),
kafkaMessage.message(), timestamp);
Avoid calling reflection class creation each time.
}
MessageAndMetadata<byte[], byte[]> kafkaMessage = mIterator.next();
+ Long timestamp = mKafkaMessageTimestampFactory.getKafkaMessageTimestamp().getTimestamp(kafkaMessage);
Message message = new Message(kafkaMessage.topic(), kafkaMessage.partition(),
kafkaMessage.offset(), kafkaMessage.key(),
kafkaMessage.message(), timestamp); |
codereview_java_data_12259 | protected View inflate(LayoutInflater layoutInflater, ViewGroup viewGroup) {
View inflatedView = layoutInflater.inflate(R.layout.item_notification, viewGroup, false);
ButterKnife.bind(this, inflatedView);
- if (NotificationActivity.isarchivedvisible) {
swipeLayout.setSwipeEnabled(false);
}else {
swipeLayout.setSwipeEnabled(true);
Pass `isSwipeEnabled` in the constructor. Do not use `NotificationActivity.isarchivedvisible`
protected View inflate(LayoutInflater layoutInflater, ViewGroup viewGroup) {
View inflatedView = layoutInflater.inflate(R.layout.item_notification, viewGroup, false);
ButterKnife.bind(this, inflatedView);
+ if (isarchivedvisible) {
swipeLayout.setSwipeEnabled(false);
}else {
swipeLayout.setSwipeEnabled(true); |
codereview_java_data_12260 | throw new UnsupportedOperationException("Identity transform is not supported");
}
- default T bucket(int fieldId, String sourceName, int sourceId, int width) {
- return bucket(sourceName, sourceId, width);
}
- default T bucket(String sourceName, int sourceId, int width) {
throw new UnsupportedOperationException("Bucket transform is not supported");
}
`width` -> `numBuckets`? Same as in `SortOrderVisitor`L34
throw new UnsupportedOperationException("Identity transform is not supported");
}
+ default T bucket(int fieldId, String sourceName, int sourceId, int numBuckets) {
+ return bucket(sourceName, sourceId, numBuckets);
}
+ default T bucket(String sourceName, int sourceId, int numBuckets) {
throw new UnsupportedOperationException("Bucket transform is not supported");
} |
codereview_java_data_12263 | @SuppressLint("CheckResult")
public void removeNotification(Notification notification) {
- if(isRead) {
return;
}
Disposable disposable = Observable.defer((Callable<ObservableSource<Boolean>>)
Style: One space after `if` like in the similar lines you added as part of this commit.
@SuppressLint("CheckResult")
public void removeNotification(Notification notification) {
+ if (isRead) {
return;
}
Disposable disposable = Observable.defer((Callable<ObservableSource<Boolean>>) |
codereview_java_data_12270 | CryptoEnvironment env = new CryptoEnvironment(Scope.RFILE,
conf.getAllPropertiesWithPrefix(Property.TABLE_PREFIX));
FileEncrypter encrypter = cryptoService.getFileEncrypter(env);
- String params = encrypter.getParameters();
ByteArrayOutputStream out = new ByteArrayOutputStream();
- OutputStream encrypted = encrypter.encryptStream(out);
// System.out.println("after enc out Bytes written " + out.size());
assertNotNull(encrypted);
Should remove these or convert to `log.trace` or `log.debug`
CryptoEnvironment env = new CryptoEnvironment(Scope.RFILE,
conf.getAllPropertiesWithPrefix(Property.TABLE_PREFIX));
FileEncrypter encrypter = cryptoService.getFileEncrypter(env);
+ byte[] params = encrypter.getParameters();
+ env.setParameters(params);
ByteArrayOutputStream out = new ByteArrayOutputStream();
+ DataOutputStream dataOut = new DataOutputStream(out);
+ env.writeParams(dataOut);
+ OutputStream encrypted = encrypter.encryptStream(dataOut);
// System.out.println("after enc out Bytes written " + out.size());
assertNotNull(encrypted); |
codereview_java_data_12272 | /*
- * Copyright 2019 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
FYI - copyright dates are usually left as the earliest date i.e. prior art
/*
+ * Copyright 2018 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at |
codereview_java_data_12275 | public void ethPeerIsMissingResultInNoUpdate() {
when(ethPeers.peer(any())).thenReturn(null);
- final SynchronizerUpdater updater = new SynchronizerUpdater(ethPeers);
updater.updatePeerChainState(1, createAnonymousPeerConnection());
Should the `anyLong()` be `knownChainHeight`? ...unless any value is really acceptable?
public void ethPeerIsMissingResultInNoUpdate() {
when(ethPeers.peer(any())).thenReturn(null);
+ final EthSynchronizerUpdater updater = new EthSynchronizerUpdater(ethPeers);
updater.updatePeerChainState(1, createAnonymousPeerConnection()); |
codereview_java_data_12278 | @Override
public synchronized final long position() throws IOException {
- return 0;
}
@Override
Why that read() has to be under lock? We only need to protect usage of the "position" field (or even make it atomic instead) and let actual read() / write() concurrency to be taken care of by underlying FileChannel.
@Override
public synchronized final long position() throws IOException {
+ return position;
}
@Override |
codereview_java_data_12283 | import android.text.util.Rfc822Tokenizer;
public class Address implements Serializable {
- private static final Pattern ATOM = Pattern.compile(
- "^(?:[a-zA-Z0-9!#$%&'*+\\-/=?^_`{|}~]|\\s)+$");
/**
* Immutable empty {@link Address} array
Why the line break?
import android.text.util.Rfc822Tokenizer;
public class Address implements Serializable {
+ private static final Pattern ATOM = Pattern.compile("^(?:[a-zA-Z0-9!#$%&'*+\\-/=?^_`{|}~]|\\s)+$");
/**
* Immutable empty {@link Address} array |
codereview_java_data_12299 | import java.util.Arrays;
-import static org.junit.Assert.assertTrue;
/**
* Unit test that verify the implementation of {@link ConnectionType}
Could you change this into `assertEquals(expected, result)` ?
import java.util.Arrays;
+import static org.junit.Assert.assertEquals;
/**
* Unit test that verify the implementation of {@link ConnectionType} |
codereview_java_data_12300 | required(102, "partition", partitionType),
required(103, "record_count", LongType.get()),
required(104, "file_size_in_bytes", LongType.get()),
optional(105, "block_size_in_bytes", LongType.get()),
optional(106, "file_ordinal", IntegerType.get()),
optional(107, "sort_columns", ListType.ofRequired(112, IntegerType.get())),
Could you add a note that although it is optional, we need to always write it for older readers?
required(102, "partition", partitionType),
required(103, "record_count", LongType.get()),
required(104, "file_size_in_bytes", LongType.get()),
+ // Note that although this field is optional, we need to always write it for older readers
optional(105, "block_size_in_bytes", LongType.get()),
optional(106, "file_ordinal", IntegerType.get()),
optional(107, "sort_columns", ListType.ofRequired(112, IntegerType.get())), |
codereview_java_data_12307 | pathParameters(
parameterWithName("my-task").description("The name of an existing task definition (required)")),
requestParameters(
- parameterWithName("cleanup").description("The flag to indicate if the associated task executions needed to be cleanedup")
)
));
}
cleanedup is 2 words. Can clean up on merge.
pathParameters(
parameterWithName("my-task").description("The name of an existing task definition (required)")),
requestParameters(
+ parameterWithName("cleanup").description("The flag to indicate if the associated task executions needed to be cleaned up")
)
));
} |
codereview_java_data_12310 | StringUtils.getParsedStringFromHtml(metadata.artist().value())
);
- media.setDescriptions(Collections.singletonMap("default", metadata.imageDescription().value()));
media.setCategories(MediaDataExtractorUtil.extractCategoriesFromList(metadata.categories().value()));
String latitude = metadata.gpsLatitude().value();
String longitude = metadata.gpsLongitude().value();
@maskaravivek can you explain why this lines were unnecessary?
StringUtils.getParsedStringFromHtml(metadata.artist().value())
);
+ String language = Locale.getDefault().getLanguage();
+ if (StringUtils.isNullOrWhiteSpace(language)) {
+ language = "default";
+ }
+
+ media.setDescriptions(Collections.singletonMap(language, metadata.imageDescription().value()));
media.setCategories(MediaDataExtractorUtil.extractCategoriesFromList(metadata.categories().value()));
String latitude = metadata.gpsLatitude().value();
String longitude = metadata.gpsLongitude().value(); |
codereview_java_data_12313 | private void scheduleNextPull(PullResult pullResult) {
pullRequest.setNextOffset(pullResult.getNextBeginOffset());
correctTagsOffset(pullRequest);
- if (defaultMQPushConsumer.getPullInterval() > 0) {
- executePullRequestLater(pullRequest, defaultMQPushConsumer.getPullInterval());
} else {
DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest);
}
what about renaming the method to `correctTagsOffsetAndSchedulePull` since this method is called by the result which needs to correct tags offset before schedule.
private void scheduleNextPull(PullResult pullResult) {
pullRequest.setNextOffset(pullResult.getNextBeginOffset());
correctTagsOffset(pullRequest);
+ if (defaultMQPushConsumer.getPullIntervalPolicy().getPullInterval() > 0) {
+ executePullRequestLater(pullRequest, defaultMQPushConsumer.getPullIntervalPolicy().getPullInterval());
} else {
DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest);
} |
codereview_java_data_12314 | * constructor invocation}.
*/
@Nullable
- public ASTExpression getLhsExpression() {
- Node node = getFirstChild();
- return node instanceof ASTExpression ? (ASTExpression) node : null;
}
}
In other nodes, we just called this `getLhs` (without "Expression" suffix).
* constructor invocation}.
*/
@Nullable
+ @Override
+ public ASTExpression getQualifier() {
+ return QualifierOwner.super.getQualifier();
}
} |
codereview_java_data_12316 | }
HashSet<String> filteredGroups = new HashSet<String>();
- for (String group : groups) {
- if (this.brokerController.getSubscriptionGroupManager().getSubscriptionGroupTable().containsKey(group)) {
- filteredGroups.add(group);
}
}
GroupList groupList = new GroupList();
It would be better to make an optional configuration here, because some users also want to show the consumption progress of topics that they have subscribed to, and it seems that users in the community are already used to this usage, so forward compatibility is necessary
}
HashSet<String> filteredGroups = new HashSet<String>();
+ if (requestHeader.isIgnoreDeteled()) {
+ for (String group : groups) {
+ if (this.brokerController.getSubscriptionGroupManager().getSubscriptionGroupTable().containsKey(group)) {
+ filteredGroups.add(group);
+ }
}
+ } else {
+ filteredGroups = groups;
}
GroupList groupList = new GroupList(); |
codereview_java_data_12325 | runtimeEnvironment.setAppDeployer(deployerInfo);
} catch (UnsupportedOperationException uoe) {
- logger.debug("expected in skipper mode due to #392");
}
}
This message can be generic as there could be other modes in the future. Maybe we don't need to specify Skipper's 392 here.
runtimeEnvironment.setAppDeployer(deployerInfo);
} catch (UnsupportedOperationException uoe) {
+ logger.debug("RuntimeEnvironmentInfo is not supported!");
}
} |
codereview_java_data_12327 | = new SimpleHeaderMarshaller<>(JsonProtocolMarshaller.INSTANT_VALUE_TO_STRING);
public static final JsonMarshaller<List<?>> LIST = (list, context, paramName, sdkField) -> {
- if (list.isEmpty()) {
return;
}
SdkField memberFieldInfo = sdkField.getRequiredTrait(ListTrait.class).memberFieldInfo();
Do we need to check null here?
= new SimpleHeaderMarshaller<>(JsonProtocolMarshaller.INSTANT_VALUE_TO_STRING);
public static final JsonMarshaller<List<?>> LIST = (list, context, paramName, sdkField) -> {
+ if (isNullOrEmpty(list)) {
return;
}
SdkField memberFieldInfo = sdkField.getRequiredTrait(ListTrait.class).memberFieldInfo(); |
codereview_java_data_12330 | }
// no arg constructor should do minimal work since its used in Main ServiceLoader
- public Shell() throws IOException {}
public Shell(ConsoleReader reader) {
super();
Can remove the `throws IOException` as it won't affect callers at all. They were already expecting the IOException -- if we don't throw that anymore, that's fine.
}
// no arg constructor should do minimal work since its used in Main ServiceLoader
+ public Shell() {}
public Shell(ConsoleReader reader) {
super(); |
codereview_java_data_12332 | public static class GroupCommitRequest {
private final long nextOffset;
- private final CountDownLatch countDownLatch = new CountDownLatch(1);
- private CompletableFuture<Boolean> flushOk = new CompletableFuture<>();
private final long startTimestamp = System.currentTimeMillis();
private long timeoutMillis = Long.MAX_VALUE;
When we use CompletableFuture, countDownLatch and waitForFlush seem redundant.
public static class GroupCommitRequest {
private final long nextOffset;
+ private CompletableFuture<PutMessageStatus> flushOKFuture = new CompletableFuture<>();
private final long startTimestamp = System.currentTimeMillis();
private long timeoutMillis = Long.MAX_VALUE; |
codereview_java_data_12367 | * criteria as {@link #valueMatchesType}. */
public static boolean validConstant(Object o, Litmus litmus) {
if (o == null
|| o instanceof Boolean
|| o instanceof BigDecimal
|| o instanceof NlsString
It seems that this method is only used in tests ?
* criteria as {@link #valueMatchesType}. */
public static boolean validConstant(Object o, Litmus litmus) {
if (o == null
+ || o instanceof Integer
+ || o instanceof Long
+ || o instanceof Float
+ || o instanceof Double
|| o instanceof Boolean
|| o instanceof BigDecimal
|| o instanceof NlsString |
codereview_java_data_12376 | */
private String getTemplatizedCreatedDate() {
if (dateCreated != null) {
if (UploadableFile.DateTimeWithSource.EXIF_SOURCE.equals(dateCreatedSource)) {
- java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
return String.format(Locale.ENGLISH, TEMPLATE_DATE_ACC_TO_EXIF, dateFormat.format(dateCreated)) + "\n";
} else {
- java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
return String.format(Locale.ENGLISH, TEMPLATE_DATA_OTHER_SOURCE, dateFormat.format(dateCreated)) + "\n";
}
}
dateFormat could be placed out of if-else, the same thing is used in both if and else
*/
private String getTemplatizedCreatedDate() {
if (dateCreated != null) {
+ java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
if (UploadableFile.DateTimeWithSource.EXIF_SOURCE.equals(dateCreatedSource)) {
return String.format(Locale.ENGLISH, TEMPLATE_DATE_ACC_TO_EXIF, dateFormat.format(dateCreated)) + "\n";
} else {
return String.format(Locale.ENGLISH, TEMPLATE_DATA_OTHER_SOURCE, dateFormat.format(dateCreated)) + "\n";
}
} |
codereview_java_data_12380 | return;
}
String notificationTag = localUri.toString();
- File file1 =new File(localUri.getPath());
Timber.d("Before execution!");
curNotification.setContentTitle(getString(R.string.upload_progress_notification_title_start, contribution.getDisplayTitle()))
.setContentText(getResources().getQuantityString(R.plurals.uploads_pending_notification_indicator, toUpload, toUpload))
.setTicker(getString(R.string.upload_progress_notification_title_in_progress, contribution.getDisplayTitle()));
- notificationManager.notify(notificationTag, NOTIFICATION_UPLOAD_IN_PROGRESS, curNotification.build());
String filename = contribution.getFilename();
- formatting. - use a more meaningful variable name.
return;
}
String notificationTag = localUri.toString();
+ File localFile = new File(localUri.getPath());
Timber.d("Before execution!");
curNotification.setContentTitle(getString(R.string.upload_progress_notification_title_start, contribution.getDisplayTitle()))
.setContentText(getResources().getQuantityString(R.plurals.uploads_pending_notification_indicator, toUpload, toUpload))
.setTicker(getString(R.string.upload_progress_notification_title_in_progress, contribution.getDisplayTitle()));
+ notificationManager
+ .notify(notificationTag, NOTIFICATION_UPLOAD_IN_PROGRESS, curNotification.build());
String filename = contribution.getFilename(); |
codereview_java_data_12384 | network.disconnect(this, Optional.ofNullable(reason));
}
@Override
public SocketAddress getLocalAddress() {
throw new UnsupportedOperationException();
Should we push Optional<DisconnectReason> into PeerConnection? An alternative would be to make a no-args disconnect() and make disconnect(@NotNull final DisconnectReason reason) and handle the optional stuff in the impls.
network.disconnect(this, Optional.ofNullable(reason));
}
+ @Override
+ public void disconnect() {
+ network.disconnect(this, Optional.empty());
+ }
+
@Override
public SocketAddress getLocalAddress() {
throw new UnsupportedOperationException(); |
codereview_java_data_12389 | TableConfiguration tableConf = this.master.getContext().getTableConfiguration(tableId);
MergeStats mergeStats = mergeStatsCache.computeIfAbsent(tableId,
- k -> currentMerges.getOrDefault(k, new MergeStats(new MergeInfo())));
TabletGoalState goal = this.master.getGoalState(tls, mergeStats.getMergeInfo());
TServerInstance server = tls.getServer();
TabletState state = tls.getState(currentTServers.keySet());
This always constructs the the 'default' `new MergeStats(new MergeInfo()))`, even if already exists in `currentMerges`. To avoid that, you could use the following instead of `getOrDefault`: ```suggestion k -> { var mergeStats = currentMerges.get(k); return mergeStats != null ? mergeStats : new MergeStats(new MergeInfo()); }); ```
TableConfiguration tableConf = this.master.getContext().getTableConfiguration(tableId);
MergeStats mergeStats = mergeStatsCache.computeIfAbsent(tableId,
+ k -> {
+ var mergeStats = currentMerges.get(k);
+ return mergeStats != null ? mergeStats : new MergeStats(new MergeInfo());
+ });
TabletGoalState goal = this.master.getGoalState(tls, mergeStats.getMergeInfo());
TServerInstance server = tls.getServer();
TabletState state = tls.getState(currentTServers.keySet()); |
codereview_java_data_12400 | */
public abstract class FeedPreferenceSkipDialog extends AlertDialog.Builder {
- public FeedPreferenceSkipDialog(Context context, int titleRes, int skipIntroInitialValue,
int skipEndInitialValue) {
super(context);
- setTitle(titleRes);
View rootView = View.inflate(context, R.layout.feed_pref_skip_dialog, null);
setView(rootView);
Is there a case where the title might be different from `R.string.pref_feed_skip`? I do not think this needs to be a parameter.
*/
public abstract class FeedPreferenceSkipDialog extends AlertDialog.Builder {
+ public FeedPreferenceSkipDialog(Context context, int skipIntroInitialValue,
int skipEndInitialValue) {
super(context);
+ setTitle(R.string.pref_feed_skip);
View rootView = View.inflate(context, R.layout.feed_pref_skip_dialog, null);
setView(rootView); |
codereview_java_data_12404 | }
@Ignore
@Test
public void testSavingsAccount_DormancyTracking() throws InterruptedException {
this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec);
remove this from this PR, and rebase from master, you'll get it from #761 ...
}
@Ignore
@Test
+ @Ignore // TODO FINERACT-852
public void testSavingsAccount_DormancyTracking() throws InterruptedException {
this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec); |
codereview_java_data_12408 | combiners = new ColumnSet(Lists.newArrayList(Splitter.on(",").split(encodedColumns)));
isPartialCompaction = ((env.getIteratorScope() == IteratorScope.majc) && !env.isFullMajorCompaction());
- if (options.containsKey(DELETE_HANDLING_ACTION_OPTION)) {
- deleteHandlingAction = DeleteHandlingAction.valueOf(options.get(DELETE_HANDLING_ACTION_OPTION));
} else {
deleteHandlingAction = DeleteHandlingAction.LOG_ERROR;
}
A warning message with the actual property being checked (DELETE_HANDLING_ACTION_OPTION) and the value that we have no enum-value for would be useful.
combiners = new ColumnSet(Lists.newArrayList(Splitter.on(",").split(encodedColumns)));
isPartialCompaction = ((env.getIteratorScope() == IteratorScope.majc) && !env.isFullMajorCompaction());
+
+ String dhaOpt = options.get(DELETE_HANDLING_ACTION_OPTION);
+ if (dhaOpt != null) {
+ try{
+ deleteHandlingAction = DeleteHandlingAction.valueOf(dhaOpt);
+ } catch(IllegalArgumentException iae) {
+ throw new IllegalAccessError(dhaOpt+" is not a legal option for "+DELETE_HANDLING_ACTION_OPTION);
+ }
} else {
deleteHandlingAction = DeleteHandlingAction.LOG_ERROR;
} |
codereview_java_data_12414 | @Override
public boolean saveToSnapshot() {
if (inComplete) {
return complete();
}
if (snapshotTraverser == null) {
this needs more explanation, like in SessionWindowP. Do we perhaps need better support for this in ProcessorTasklet?
@Override
public boolean saveToSnapshot() {
if (inComplete) {
+ // If we are in completing phase, we can have a half-emitted item. Instead of finishing it and
+ // writing a snapshot, we finish the final items and save no state.
return complete();
}
if (snapshotTraverser == null) { |
codereview_java_data_12424 | public static final String PUBLISHED_WAP_ID_PROP = "published-wap-id";
public static final String SOURCE_SNAPSHOT_ID_PROP = "source-snapshot-id";
public static final String REPLACE_PARTITIONS_PROP = "replace-partitions";
- public static final String EXTRA_METADATA_PREFIX = "extra-metadata.";
private SnapshotSummary() {
}
happy to change if a different prefix string would be more suitable
public static final String PUBLISHED_WAP_ID_PROP = "published-wap-id";
public static final String SOURCE_SNAPSHOT_ID_PROP = "source-snapshot-id";
public static final String REPLACE_PARTITIONS_PROP = "replace-partitions";
+ public static final String EXTRA_METADATA_PREFIX = "snapshot.property.";
private SnapshotSummary() {
} |
codereview_java_data_12428 | import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class CsvFileFormatTest extends BaseFileFormatTest {
We could use a test, proving that _projection_ works.
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.util.Lists.newArrayList;
public class CsvFileFormatTest extends BaseFileFormatTest { |
codereview_java_data_12429 | import com.hazelcast.jet.core.ProcessorSupplier;
import com.hazelcast.jet.core.processor.Processors;
import org.elasticsearch.client.RestClient;
-import org.elasticsearch.client.RestHighLevelClient;
import javax.annotation.Nonnull;
-import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
I see that we have this obtaining RestClient via reflection at processor too. Maybe we can have it as a static utility method, in ElasticCatClient for example.
import com.hazelcast.jet.core.ProcessorSupplier;
import com.hazelcast.jet.core.processor.Processors;
import org.elasticsearch.client.RestClient;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap; |
codereview_java_data_12435 | SendMessageContext sendMessageContext,
ChannelHandlerContext ctx,
int queueIdInt) {
- return putMessageResult.thenApplyAsync((r) ->
- handlePutMessageResult(r, response, request, msgInner, responseHeader, sendMessageContext, ctx, queueIdInt),
- this.brokerController.getSendMessageExecutor());
}
private boolean handleRetryAndDLQ(SendMessageRequestHeader requestHeader, RemotingCommand response,
how about change to: putMessageResult.thenAcceptAsync(result -> { RemotingCommand remotingCommand = handlePutMessageResult(result, response, request, msgInner, responseHeader, sendMessageContext, ctx, queueIdInt); if (remotingCommand != null) { doResponse(ctx, request, remotingCommand); } }, this.brokerController.getSendMessageExecutor()); return null;
SendMessageContext sendMessageContext,
ChannelHandlerContext ctx,
int queueIdInt) {
+ putMessageResult.thenAcceptAsync(result -> {
+ RemotingCommand remotingCommand =
+ handlePutMessageResult(result, response, request, msgInner, responseHeader, sendMessageContext, ctx, queueIdInt);
+ if (remotingCommand != null) {
+ doResponse(ctx, request, remotingCommand);
+ }
+ }, this.brokerController.getSendMessageExecutor());
+ return null;
}
private boolean handleRetryAndDLQ(SendMessageRequestHeader requestHeader, RemotingCommand response, |
codereview_java_data_12440 | */
package org.kie.kogito.tracing.event.message.models;
import org.kie.kogito.tracing.event.message.Message;
import org.kie.kogito.tracing.event.message.MessageCategory;
import org.kie.kogito.tracing.event.message.MessageExceptionField;
Shouldn't `type` be hard-coded as a literal as it's used to determine the sub-class when deserialising? For example `decision`?
*/
package org.kie.kogito.tracing.event.message.models;
+import org.kie.kogito.ModelDomain;
import org.kie.kogito.tracing.event.message.Message;
import org.kie.kogito.tracing.event.message.MessageCategory;
import org.kie.kogito.tracing.event.message.MessageExceptionField; |
codereview_java_data_12443 | }
byte[] bytes = createGIFFromImages(bitmaps);
File file = new File(Environment.getExternalStorageDirectory() + "/" + "Phimpme_gifs");
- DateFormat dateFormat = new SimpleDateFormat("dMMyy_HHmm");
String date = dateFormat.format(Calendar.getInstance().getTime());
if(file.exists() && file.isDirectory()){
FileOutputStream outStream = null;
It should be `dd` not `d`
}
byte[] bytes = createGIFFromImages(bitmaps);
File file = new File(Environment.getExternalStorageDirectory() + "/" + "Phimpme_gifs");
+ DateFormat dateFormat = new SimpleDateFormat("ddMMyy_HHmm");
String date = dateFormat.format(Calendar.getInstance().getTime());
if(file.exists() && file.isDirectory()){
FileOutputStream outStream = null; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.