id stringlengths 23 26 | content stringlengths 182 2.49k |
|---|---|
codereview_java_data_2985 | + "SELECT " + KEY_USERNAME + "," + KEY_PASSWORD + " FROM " + TABLE_NAME_FEED_ITEMS
+ " INNER JOIN " + TABLE_NAME_FEEDS
+ " ON " + TABLE_NAME_FEED_ITEMS + "." + KEY_FEED + " = " + TABLE_NAME_FEEDS + "." + KEY_ID
- + " WHERE " + TABLE_NAME_FEED_ITEMS + "." + KEY_IMAGE_URL + "=" + downloadUrl;
return db.rawQuery(query, null);
}
Regression Image authentication: the logic here supports images of `FeedItem`, but not the images of `Feed`.
+ "SELECT " + KEY_USERNAME + "," + KEY_PASSWORD + " FROM " + TABLE_NAME_FEED_ITEMS
+ " INNER JOIN " + TABLE_NAME_FEEDS
+ " ON " + TABLE_NAME_FEED_ITEMS + "." + KEY_FEED + " = " + TABLE_NAME_FEEDS + "." + KEY_ID
+ + " WHERE " + TABLE_NAME_FEED_ITEMS + "." + KEY_IMAGE_URL + "=" + downloadUrl
+ + " UNION SELECT " + KEY_USERNAME + "," + KEY_PASSWORD + " FROM " + TABLE_NAME_FEEDS
+ + " WHERE " + TABLE_NAME_FEEDS + "." + KEY_IMAGE_URL + "=" + downloadUrl;
return db.rawQuery(query, null);
} |
codereview_java_data_2988 | }
@SuppressWarnings("deprecation")
@Test
public void testAnnotations() {
assertTrue(Property.TABLE_VOLUME_CHOOSER.isExperimental());
Rather than suppress warnings across the entire method, it's better to only suppress the one case in the method that is deprecated. This avoids masking future un-triaged warnings. Here, the `Property.INSTANCE_DFS_URI` can be assigned to a variable of type Property just before its corresponding `assertTrue` line, and the assignment can be suppressed.
}
@SuppressWarnings("deprecation")
+ private Property getDeprecatedProperty() {
+ return Property.INSTANCE_DFS_DIR;
+ }
+
@Test
public void testAnnotations() {
assertTrue(Property.TABLE_VOLUME_CHOOSER.isExperimental()); |
codereview_java_data_2990 | .inc();
} else {
outboundMessagesCounter
- .labels("null", Integer.toString(message.getCode()), Integer.toString(message.getCode()))
.inc();
}
Messages with no capability would be one of the ones from `WireMessageCodes` so maybe could add a message name function there and provide the proper name rather than just the message code.
.inc();
} else {
outboundMessagesCounter
+ .labels(
+ "Wire",
+ WireMessageCodes.messageName(message.getCode()),
+ Integer.toString(message.getCode()))
.inc();
} |
codereview_java_data_2995 | import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.RemoteKeySourceException;
-import com.nimbusds.jose.jwk.*;
import com.nimbusds.jose.jwk.source.JWKSetCache;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
Please don't use `*` imports.
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.RemoteKeySourceException;
+import com.nimbusds.jose.jwk.JWK;
+import com.nimbusds.jose.jwk.JWKSet;
+import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.source.JWKSetCache;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.jwk.source.RemoteJWKSet; |
codereview_java_data_3001 | this.getRemoteRepositories()));
}
properties.put(MAVEN_PREFIX + "offline", String.valueOf(this.isOffline()));
- if (this.getConnectTimeout() > 0) {
properties.put(MAVEN_PREFIX + "connectTimeout", String.valueOf(this.getConnectTimeout()));
}
- if (this.getRequestTimeout() > 0) {
properties.put(MAVEN_PREFIX + "requestTimeout", String.valueOf(this.getRequestTimeout()));
}
Proxy proxy = getProxy();
this means we would not pass thru a value of 0, which is valid... but maybe that's ok since that means NO timeout (although a user could pass any negative value to accomplish the same).... another option is to use `Integer` instead of `int` and check for `null` as the indicator to rely on the system's own default
this.getRemoteRepositories()));
}
properties.put(MAVEN_PREFIX + "offline", String.valueOf(this.isOffline()));
+ if (this.getConnectTimeout() != null) {
properties.put(MAVEN_PREFIX + "connectTimeout", String.valueOf(this.getConnectTimeout()));
}
+ if (this.getRequestTimeout() != null) {
properties.put(MAVEN_PREFIX + "requestTimeout", String.valueOf(this.getRequestTimeout()));
}
Proxy proxy = getProxy(); |
codereview_java_data_3005 | return CheckResult.OK;
}
- public String name() {
- String name = this.getClass().getSimpleName();
- return name.replace("AutoValue_", "");
- }
-
/**
* Closes any network resources created implicitly by the component.
*
please revert this method as it is adding a public method to a base type that existed for a long time, for a single call site. We take public methods on base types more seriously here vs other projects.
return CheckResult.OK;
}
/**
* Closes any network resources created implicitly by the component.
* |
codereview_java_data_3012 | return put(entry._1, entry._2);
}
- @Override
- public LinkedHashMap<K, V> put(java.util.Map<? extends K, ? extends V> map) {
- Objects.requireNonNull(map, "map is null");
- LinkedHashMap<K, V> result = LinkedHashMap.empty();
- for (java.util.Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
- result = result.put(entry.getKey(), entry.getValue());
- }
- return result;
- }
-
@Override
public LinkedHashMap<K, V> remove(K key) {
if (containsKey(key)) {
also move to `ofAll` and use `merge` instead like described above
return put(entry._1, entry._2);
}
@Override
public LinkedHashMap<K, V> remove(K key) {
if (containsKey(key)) { |
codereview_java_data_3016 | public abstract class MemberChangeListener extends Subscriber<MembersChangeEvent> {
@Override
- public Class<? extends Event> subscribeType() {
return MembersChangeEvent.class;
}
Under the final modification
public abstract class MemberChangeListener extends Subscriber<MembersChangeEvent> {
@Override
+ public final Class<? extends Event> subscribeType() {
return MembersChangeEvent.class;
} |
codereview_java_data_3038 | /**
* Database setting <code>IGNORE_CATALOGS</code>
* (default: false).<br />
- * ignore Catalog-Prefix at object-Names.
*/
public final boolean ignoreCatalogs = get("IGNORE_CATALOGS", false);
Please, use normal spelling and punctuation here. Also the description should be more correct, now it looks like the catalogs aren't accepted by default, but actually they are always accepted. This setting only allows usage of any names.
/**
* Database setting <code>IGNORE_CATALOGS</code>
* (default: false).<br />
+ * Generally accept the all catalog prefixes at objectnames even if they are not equal to the current databasename.
*/
public final boolean ignoreCatalogs = get("IGNORE_CATALOGS", false); |
codereview_java_data_3039 | * @param file The file to upload.
* @param metadata The S3 metadata to associate with this object
* @param cannedAcl The canned ACL to associate with this object
- * @param connectionCheckType Type of connection check. Default is {@link NetworkInfoReceiver.Type#WIFI_ONLY}
* @return A TransferObserver used to track upload progress and state
*/
public TransferObserver upload(String bucket, String key, File file, ObjectMetadata metadata,
- CannedAccessControlList cannedAcl, NetworkInfoReceiver.Type connectionCheckType) {
if (file == null || file.isDirectory()) {
throw new IllegalArgumentException("Invalid file: " + file);
}
can we instead move the WAN configuration into some sort of a TransferConfiguration class? that way API doesnt have to change much between feature changes.
* @param file The file to upload.
* @param metadata The S3 metadata to associate with this object
* @param cannedAcl The canned ACL to associate with this object
* @return A TransferObserver used to track upload progress and state
*/
public TransferObserver upload(String bucket, String key, File file, ObjectMetadata metadata,
+ CannedAccessControlList cannedAcl) {
if (file == null || file.isDirectory()) {
throw new IllegalArgumentException("Invalid file: " + file);
} |
codereview_java_data_3047 | return this;
}
- public ConfigBuilder select(String[] columns) {
- conf.setStrings(COLUMN_PROJECTIONS, columns);
return this;
}
Could we use a `List` instead of an array of strings here? It's usually easier if Iceberg converts to an array instead of expecting the caller to.
return this;
}
+ public ConfigBuilder select(List<String> columns) {
+ conf.setStrings(SELECTED_COLUMNS, columns.toArray(new String[0]));
+ return this;
+ }
+
+ public ConfigBuilder select(String... columns) {
+ conf.setStrings(SELECTED_COLUMNS, columns);
return this;
} |
codereview_java_data_3054 | .map(tasklet -> taskletInitExecutor.submit(() ->
Util.doWithClassLoader(jobClassLoader, tasklet::init)))
.collect(toList());
- for (Future<?> future : futures) {
- try {
- future.get();
- } catch (InterruptedException | ExecutionException e) {
- throw new JetException("Tasklet initialization failed", e);
- }
- }
// We synchronize so that no two jobs submit their tasklets in
// parallel. If two jobs submit in parallel, the tasklets of one of
We can't just throw at the first failure. We have to wait before all `init()` calls return. Otherwise we might call `close()` concurrently to `init()` for non-failed futures.
.map(tasklet -> taskletInitExecutor.submit(() ->
Util.doWithClassLoader(jobClassLoader, tasklet::init)))
.collect(toList());
+ awaitAll(futures);
// We synchronize so that no two jobs submit their tasklets in
// parallel. If two jobs submit in parallel, the tasklets of one of |
codereview_java_data_3058 | wl2.setUpdateTime(Timestamp.fromMillis(123456789123L));
wl2.setHostname("random");
wl2.setHostname("testhost-1");
assertEquals(wl1, wl2);
we seem to be missing test cases here. After you set random, you need to verify that assertNotEquals(wl1, wl2); then you set the value to null, and then verify again that it's assertNotEquals(wl1, wl2); then you store value back to its original value and verify they're equal. as in lines 87-88. This sequence verifies all the lines have code coverage. Whenever making changes, always run clover in the mode where the changes were mode: mvn -P coverage clean org.openclover:clover-maven-plugin:instrument org.openclover:clover-maven-plugin:clover and verify in the clover output that all your new lines have full code coverage.
wl2.setUpdateTime(Timestamp.fromMillis(123456789123L));
wl2.setHostname("random");
+ assertNotEquals(wl1, wl2);
+ wl2.setHostname(null);
+ assertNotEquals(wl1, wl2);
wl2.setHostname("testhost-1");
assertEquals(wl1, wl2); |
codereview_java_data_3062 | private final TaskSanitizer taskSanitizer = new TaskSanitizer();
- private static final List<String> allowedSorts = Arrays.asList("TASK_EXECUTION_ID", "TASK_NAME", "START_TIME",
- "END_TIME", "EXIT_CODE");
/**
* Creates a {@code TaskExecutionController} that retrieves Task Execution information
In SCT, I validated the ability to sort by any field in the table...Are these the only fields we ever allow the user to sort by in the UI?
private final TaskSanitizer taskSanitizer = new TaskSanitizer();
+ private static final List<String> allowedSorts = Arrays.asList("task_execution_id", "task_name", "start_time",
+ "end_time", "exit_code");
/**
* Creates a {@code TaskExecutionController} that retrieves Task Execution information |
codereview_java_data_3063 | }
private String createComposedTaskDefinition(String graph) {
- String composedTaskDefinition = StringUtils.hasText(this.dataFlowUri) ? "%s --graph=\"%s\" --dataFlowUri=%s" : "%s --graph=\"%s\"";
- return String.format(composedTaskDefinition,
- taskConfigurationProperties.getComposedTaskRunnerName(), graph, this.dataFlowUri);
}
@Override
I don't think we should set this here. It would be better to check the appDeploymentProperties and commandLineArgs for this key and if not specified add it as a command line arg
}
private String createComposedTaskDefinition(String graph) {
+ return String.format(String.format("%s --graph=\"%s\""),
+ taskConfigurationProperties.getComposedTaskRunnerName(), graph);
}
@Override |
codereview_java_data_3071 | final JsonObject respBody = new JsonObject(body);
final String token = respBody.getString("token");
assertThat(token).isNotNull();
- System.out.println("token " + token);
websocketService
.authenticationService
Should probably delete this line.
final JsonObject respBody = new JsonObject(body);
final String token = respBody.getString("token");
assertThat(token).isNotNull();
websocketService
.authenticationService |
codereview_java_data_3075 | if (currRange != null || lmi.hasNext()) {
// merge happened after the mapping was generated and before the table lock was acquired
throw new AcceptableThriftTableOperationException(tableId, null, TableOperation.BULK_IMPORT,
- TableOperationExceptionType.OTHER, Constants.BULK_CONCURRENT_MERGE_MSG);
}
}
Rather than rely on "OTHER" with a specific message, we should add a new enum type to `TableOperationExceptionType` to use for this case.
if (currRange != null || lmi.hasNext()) {
// merge happened after the mapping was generated and before the table lock was acquired
throw new AcceptableThriftTableOperationException(tableId, null, TableOperation.BULK_IMPORT,
+ TableOperationExceptionType.BULK_CONCURRENT_MERGE, "Concurrent merge happened");
}
} |
codereview_java_data_3079 | this.applyS3StorageClassAfterBytes = applyS3StorageClassAfterBytes;
this.checkSubdirectories = checkSubdirectories.orElse(false);
this.compressBeforeUpload = compressBeforeUpload.orElse(false);
- this.checkIfOpen = checkIfOpen.orElse(false);
}
@Schema(description = "The name of the file")
should this be `true` if the default is true?
this.applyS3StorageClassAfterBytes = applyS3StorageClassAfterBytes;
this.checkSubdirectories = checkSubdirectories.orElse(false);
this.compressBeforeUpload = compressBeforeUpload.orElse(false);
+ this.checkIfOpen = checkIfOpen.orElse(true);
}
@Schema(description = "The name of the file") |
codereview_java_data_3081 | * @since 2.0.0
*/
public interface IteratorConfiguration {
- public String getIteratorClass();
- public String getName();
- public int getPriority();
Map<String,String> getOptions();
}
`public` is redundant in all methods of this interface
* @since 2.0.0
*/
public interface IteratorConfiguration {
+ String getIteratorClass();
+ String getName();
+ int getPriority();
Map<String,String> getOptions();
} |
codereview_java_data_3096 | import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
-import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.method.MethodMatchers;
-import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import java.util.Collections;
Nit: this is the only message most people see, I'd exclude overriding the more verbose message from the class definition since that explains the intent.
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
+import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import java.util.Collections; |
codereview_java_data_3099 | private long getNumInstancesWithAttribute(List<SingularityTaskId> taskIds, String attrKey, String attrValue) {
return taskIds.stream()
- .map(id -> slaveManager.getSlave(taskManager.getTask(id).get().getMesosTask().getSlaveId().getValue()).get().getAttributes().get(attrKey))
.filter(Objects::nonNull)
.filter(x -> x.equals(attrValue))
.count();
I think we already fetch a full list of slaves somewhere before this. Each of these would be a zk call currently. So, we should either: - Add slaveManager stuff to leader cache so this is all in memory or - Pass through a list of slave data we have already read from zk for use here
private long getNumInstancesWithAttribute(List<SingularityTaskId> taskIds, String attrKey, String attrValue) {
return taskIds.stream()
+ .map(id -> leaderCache.getSlave(taskManager.getTask(id).get().getMesosTask().getSlaveId().getValue()).get().getAttributes().get(attrKey))
.filter(Objects::nonNull)
.filter(x -> x.equals(attrValue))
.count(); |
codereview_java_data_3104 | Integer.toString(mvStore.getFillRate()));
add(rows, "info.CHUNKS_FILL_RATE",
Integer.toString(mvStore.getChunksFillRate()));
- long size;
try {
- size = fs.getFile().size();
- } catch (IOException e) {
- throw DbException.convertIOException(e, "Can not get size");
- }
- add(rows, "info.FILE_SIZE",
- Long.toString(size));
add(rows, "info.CHUNK_COUNT",
Long.toString(mvStore.getChunkCount()));
add(rows, "info.PAGE_COUNT",
I think the exception should be ignored for safety. Not really significant, but this code looks suspicious and raises attention.
Integer.toString(mvStore.getFillRate()));
add(rows, "info.CHUNKS_FILL_RATE",
Integer.toString(mvStore.getChunksFillRate()));
try {
+ add(rows, "info.FILE_SIZE",
+ Long.toString(fs.getFile().size()));
+ } catch (IOException ignore) {/**/}
add(rows, "info.CHUNK_COUNT",
Long.toString(mvStore.getChunkCount()));
add(rows, "info.PAGE_COUNT", |
codereview_java_data_3107 | eq(
new EthereumWireProtocolConfiguration(
13,
- EthereumWireProtocolConfiguration.DEFAULT_MAX_GET_BLOCK_BODIES.getValue(),
- EthereumWireProtocolConfiguration.DEFAULT_MAX_GET_RECEIPTS.getValue(),
- EthereumWireProtocolConfiguration.DEFAULT_MAX_GET_NODE_DATA.getValue())));
assertThat(commandOutput.toString()).isEmpty();
assertThat(commandErrorOutput.toString()).isEmpty();
}
We don't have a testing pattern yet for validating these unstable/hidden options, so this is an opportunity to feel it out. It doesn't feel like they should be in PantheonCommandTest but each mixin class should have its own. Where that class lives is I'm not sure about. We could do it in the module the builder live in, or we could do it in this module.
eq(
new EthereumWireProtocolConfiguration(
13,
+ EthereumWireProtocolConfiguration.DEFAULT_MAX_GET_BLOCK_BODIES,
+ EthereumWireProtocolConfiguration.DEFAULT_MAX_GET_RECEIPTS,
+ EthereumWireProtocolConfiguration.DEFAULT_MAX_GET_NODE_DATA)));
assertThat(commandOutput.toString()).isEmpty();
assertThat(commandErrorOutput.toString()).isEmpty();
} |
codereview_java_data_3111 | assertThat(dataObj.getName()).isEqualTo("LongTest");
assertThat(dataObj.getItemSubjectRef().getStructureRef()).isEqualTo("xsd:long");
assertThat(dataObj.getValue()).isInstanceOf(Long.class);
- assertThat(dataObj.getValue()).isEqualTo((long) -123456);
assertThat(dataObj.getExtensionElements()).hasSize(1);
List<ExtensionElement> testValues = dataObj.getExtensionElements().get("testvalue");
assertThat(testValues).isNotNull();
No need for cast you can write it like `-123456L` instead
assertThat(dataObj.getName()).isEqualTo("LongTest");
assertThat(dataObj.getItemSubjectRef().getStructureRef()).isEqualTo("xsd:long");
assertThat(dataObj.getValue()).isInstanceOf(Long.class);
+ assertThat(dataObj.getValue()).isEqualTo(-123456L);
assertThat(dataObj.getExtensionElements()).hasSize(1);
List<ExtensionElement> testValues = dataObj.getExtensionElements().get("testvalue");
assertThat(testValues).isNotNull(); |
codereview_java_data_3113 | * @since 1.7.0
* @see #setBatchScan(Job, boolean)
*/
- protected static boolean isBatchScan(JobContext context) {
- return InputConfigurator.isIsolated(CLASS, context.getConfiguration());
}
/**
Why JobContext here? And why not public?
* @since 1.7.0
* @see #setBatchScan(Job, boolean)
*/
+ public static boolean isBatchScan(JobContext context) {
+ return InputConfigurator.isBatchScan(CLASS, context.getConfiguration());
}
/** |
codereview_java_data_3130 | @Test
public void shouldAppendElementToNil() {
- final Seq<Integer> actual = this.<Integer>empty().append(1);
final Seq<Integer> expected = of(1);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldAppendNullElementToNil() {
- final Seq<Integer> actual = this.<Integer>empty().append(null);
final Seq<Integer> expected = this.of((Integer) null);
assertThat(actual).isEqualTo(expected);
}
Was it necessary to change the formatting of the code? Formatting changes a hide the real changes and not necessary as I think.
@Test
public void shouldAppendElementToNil() {
+ final Seq<Integer> actual = this.<Integer> empty().append(1);
final Seq<Integer> expected = of(1);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldAppendNullElementToNil() {
+ final Seq<Integer> actual = this.<Integer> empty().append(null);
final Seq<Integer> expected = this.of((Integer) null);
assertThat(actual).isEqualTo(expected);
} |
codereview_java_data_3135 | int selected = UserPreferences.getFeedFilter();
String[] entryValues = context.getResources().getStringArray(R.array.nav_drawer_feed_filter_values);
for (int i = 0; i < entryValues.length; i++) {
- if (Integer.parseInt(entryValues[i]) == selected)
selectedIndexTemp = i;
}
final int selectedIndex = selectedIndexTemp;
- dialog.setSingleChoiceItems(context.getResources().getStringArray(R.array.nav_drawer_feed_filter_options), selectedIndex, (d, which) -> {
if (selectedIndex != which) {
UserPreferences.setFeedFilter(entryValues[which]);
//Update subscriptions
There are a few checkstyle errors left: ``` [ERROR] /home/circleci/AntennaPod/./app/src/main/java/de/danoeh/antennapod/dialog/FeedFilterDialog.java:24: 'if' construct must use '{}'s. [NeedBraces] [ERROR] /home/circleci/AntennaPod/./app/src/main/java/de/danoeh/antennapod/dialog/FeedFilterDialog.java:29: Line is longer than 120 characters (found 145). [LineLength] [ERROR] /home/circleci/AntennaPod/./core/src/main/java/de/danoeh/antennapod/core/preferences/UserPreferences.java:1064:51: WhitespaceAround: '{' is not preceded with whitespace. [WhitespaceAround] ```
int selected = UserPreferences.getFeedFilter();
String[] entryValues = context.getResources().getStringArray(R.array.nav_drawer_feed_filter_values);
for (int i = 0; i < entryValues.length; i++) {
+ if (Integer.parseInt(entryValues[i]) == selected) {
selectedIndexTemp = i;
+ }
}
final int selectedIndex = selectedIndexTemp;
+ String[] items = context.getResources().getStringArray(R.array.nav_drawer_feed_filter_options);
+ dialog.setSingleChoiceItems(items, selectedIndex, (d, which) -> {
if (selectedIndex != which) {
UserPreferences.setFeedFilter(entryValues[which]);
//Update subscriptions |
codereview_java_data_3150 | @ParameterizedTest
@MethodSource("org.kie.kogito.codegen.api.utils.KogitoContextTestUtils#contextBuilders")
public void givenADMNModelWhenMonitoringIsActiveThenGrafanaDashboardsAreGenerated(KogitoBuildContext.Builder contextBuilder) throws Exception {
- List<GeneratedFile> dashboards = generateTestDashboards(AddonsConfig.builder().withMonitoring(true).withPrometheusMonitoring(true).build(), contextBuilder);
- if (contextBuilder.build().hasRESTGloballyAvailable()) {
JGrafana vacationOperationalDashboard =
JGrafana.parse(new String(dashboards.stream().filter(x -> x.relativePath().contains("operational-dashboard-Vacations.json")).findFirst().get().contents()));
Are you sure this has to use the `hasRESTGloballyAvailable`? It looks strange to me ```suggestion if (contextBuilder.build().hasRESTForGenerator(codeGenerator)) { ```
@ParameterizedTest
@MethodSource("org.kie.kogito.codegen.api.utils.KogitoContextTestUtils#contextBuilders")
public void givenADMNModelWhenMonitoringIsActiveThenGrafanaDashboardsAreGenerated(KogitoBuildContext.Builder contextBuilder) throws Exception {
+ DecisionCodegen decisionCodeGenerator = getDecisionCodegen("src/test/resources/decision/models/vacationDays",
+ AddonsConfig.builder().withMonitoring(true).withPrometheusMonitoring(true).build(),
+ contextBuilder);
+ List<GeneratedFile> dashboards = generateTestDashboards(contextBuilder, decisionCodeGenerator);
+
+ if (contextBuilder.build().hasRESTForGenerator(decisionCodeGenerator)) {
JGrafana vacationOperationalDashboard =
JGrafana.parse(new String(dashboards.stream().filter(x -> x.relativePath().contains("operational-dashboard-Vacations.json")).findFirst().get().contents())); |
codereview_java_data_3157 | return true;
}
- private boolean validateDistinctAuthors(
final Collection<SignedData<RoundChangePayload>> roundChangeMsgs) {
final long distinctAuthorCount =
roundChangeMsgs.stream().map(SignedData::getAuthor).distinct().count();
You can name this with the negation in the title (negate the need for the bang in the if). e.g. hasDuplicateAuthors()
return true;
}
+ private boolean hasDuplicateAuthors(
final Collection<SignedData<RoundChangePayload>> roundChangeMsgs) {
final long distinctAuthorCount =
roundChangeMsgs.stream().map(SignedData::getAuthor).distinct().count(); |
codereview_java_data_3177 | for(Range r: extentRanges.getValue())
clippedRanges.add(ke.clip(r));
BatchInputSplit split = new BatchInputSplit(tableName, tableId, clippedRanges, new String[] {location});
- split.setMockInstance(mockInstance);
- split.setFetchedColumns(tableConfig.getFetchedColumns());
- split.setPrincipal(principal);
- split.setToken(token);
- split.setInstanceName(instance.getInstanceName());
- split.setZooKeepers(instance.getZooKeepers());
- split.setAuths(auths);
- split.setIterators(tableConfig.getIterators());
- split.setLogLevel(logLevel);
split.setScanThreads(scanThreads);
splits.add(split);
Same point as before -- would be nice to consolidate these setters where possible.
for(Range r: extentRanges.getValue())
clippedRanges.add(ke.clip(r));
BatchInputSplit split = new BatchInputSplit(tableName, tableId, clippedRanges, new String[] {location});
+ AccumuloInputSplit.updateSplit(split, instance, tableConfig, principal, token, auths, logLevel);
split.setScanThreads(scanThreads);
splits.add(split); |
codereview_java_data_3188 | * with regards to the expected schema, while RuleBuilder validates the semantics.
*
* @param ruleElement The rule element to parse
- * @param resourceLoader The resource loader to load the rule from jar
*
* @return A new instance of the rule described by this element
* @throws IllegalArgumentException if the element doesn't describe a valid rule.
*/
- public Rule buildRule(Element ruleElement, final ResourceLoader resourceLoader) {
checkRequiredAttributesArePresent(ruleElement);
String name = ruleElement.getAttribute(NAME);
With the changes I explained above, this argument would then be removed and the RuleFactory has a instance field for the resource loader.
* with regards to the expected schema, while RuleBuilder validates the semantics.
*
* @param ruleElement The rule element to parse
*
* @return A new instance of the rule described by this element
* @throws IllegalArgumentException if the element doesn't describe a valid rule.
*/
+ public Rule buildRule(Element ruleElement) {
checkRequiredAttributesArePresent(ruleElement);
String name = ruleElement.getAttribute(NAME); |
codereview_java_data_3199 | private static final Logger LOG = LogManager.getLogger();
private static List<String> nodeWhitelist;
public NodeWhitelistController(final PermissioningConfiguration configuration) {
nodeWhitelist = new ArrayList<>();
if (configuration != null && configuration.getNodeWhitelist() != null) {
nodeWhitelist.addAll(configuration.getNodeWhitelist());
}
}
We might need a flag to know if the user set the property or not. If the user didn't, we won't do any permissioning. An empty list can be ambiguous. It can indicate: The user didn't whitelist any node (node whitelisting toggle on - don't talk to any node) The user didn't specify the 'nodes-whitelist' property (node whitelisting toggled off) We can assume that a null list means that the property hasn't been set (as opposed to an empty list when the user set the property without a value). But I think a flag is more semantic.
private static final Logger LOG = LogManager.getLogger();
private static List<String> nodeWhitelist;
+ private static boolean nodeWhitelistSet = false;
public NodeWhitelistController(final PermissioningConfiguration configuration) {
nodeWhitelist = new ArrayList<>();
if (configuration != null && configuration.getNodeWhitelist() != null) {
nodeWhitelist.addAll(configuration.getNodeWhitelist());
+ nodeWhitelistSet = true;
}
} |
codereview_java_data_3204 | }
public boolean isForceTextMessageFormat() {
- if (!cryptoEnablePgpInline) {
return false;
}
-
- ComposeCryptoStatus cryptoStatus = getCurrentCryptoStatus();
- return cryptoStatus.isEncryptionEnabled() || cryptoStatus.isSigningEnabled();
}
public boolean isAllowSavingDraftRemotely() {
This is a bit double negativey Wouldn't ``` if (cryptoEnablePgpInline) { ComposeCryptoStatus .... } else { return false; } ``` be more readable.
}
public boolean isForceTextMessageFormat() {
+ if (cryptoEnablePgpInline) {
+ ComposeCryptoStatus cryptoStatus = getCurrentCryptoStatus();
+ return cryptoStatus.isEncryptionEnabled() || cryptoStatus.isSigningEnabled();
+ } else {
return false;
}
}
public boolean isAllowSavingDraftRemotely() { |
codereview_java_data_3211 | <h1>Error 503 Backend is unhealthy</h1>
<p>Backend is unhealthy</p>
<h3>Guru Mediation:</h3>
- <p>Details: cache-sea4446-SEA 1645538751 755287279</p>
<hr>
<p>Varnish cache server</p>
</body>
"wWith " -> "with"
<h1>Error 503 Backend is unhealthy</h1>
<p>Backend is unhealthy</p>
<h3>Guru Mediation:</h3>
+ <p>Details: cache-sea4432-SEA 1645538751 2222721781</p>
<hr>
<p>Varnish cache server</p>
</body> |
codereview_java_data_3215 | final FeedItem feedItem = getFeedItem(media); // some options option requires FeedItem
switch (item.getItemId()) {
case R.id.add_to_favorites_item:
- if(feedItem != null) {
DBWriter.addFavoriteItem(feedItem);
isFavorite = true;
invalidateOptionsMenu();
Missing space :) I know it hasn't been there before but I would prefer to fix the code style whenever we touch code.
final FeedItem feedItem = getFeedItem(media); // some options option requires FeedItem
switch (item.getItemId()) {
case R.id.add_to_favorites_item:
+ if (feedItem != null) {
DBWriter.addFavoriteItem(feedItem);
isFavorite = true;
invalidateOptionsMenu(); |
codereview_java_data_3221 | public class ZooReader {
private static final Logger log = LoggerFactory.getLogger(ZooReader.class);
- public static final RetryFactory DEFAULT_RETRY_FACTORY = Retry.builder().maxRetries(10)
.retryAfter(250, MILLISECONDS).incrementBy(250, MILLISECONDS).maxWait(5, TimeUnit.SECONDS)
.backOffFactor(1.5).logInterval(3, TimeUnit.MINUTES).createFactory();
- public static final RetryFactory DISABLED_RETRY_FACTORY = Retry.builder().maxRetries(0)
.retryAfter(250, MILLISECONDS).incrementBy(250, MILLISECONDS).maxWait(5, TimeUnit.SECONDS)
.backOffFactor(1.5).logInterval(3, TimeUnit.MINUTES).createFactory();
Can probably remove all this extra retry configuration since the max retries is zero here. I don't think these are all required parameters are they?
public class ZooReader {
private static final Logger log = LoggerFactory.getLogger(ZooReader.class);
+ private static final RetryFactory DEFAULT_RETRY_FACTORY = Retry.builder().maxRetries(10)
.retryAfter(250, MILLISECONDS).incrementBy(250, MILLISECONDS).maxWait(5, TimeUnit.SECONDS)
.backOffFactor(1.5).logInterval(3, TimeUnit.MINUTES).createFactory();
+ private static final RetryFactory DISABLED_RETRY_FACTORY = Retry.builder().maxRetries(0)
.retryAfter(250, MILLISECONDS).incrementBy(250, MILLISECONDS).maxWait(5, TimeUnit.SECONDS)
.backOffFactor(1.5).logInterval(3, TimeUnit.MINUTES).createFactory(); |
codereview_java_data_3225 | package com.hazelcast.jet.examples.cdc;
import com.hazelcast.jet.Jet;
import com.hazelcast.jet.cdc.CdcSinks;
import com.hazelcast.jet.cdc.ChangeRecord;
import com.hazelcast.jet.cdc.mysql.MySqlCdcSources;
should there a be a .`join()` call here?
package com.hazelcast.jet.examples.cdc;
import com.hazelcast.jet.Jet;
+import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.cdc.CdcSinks;
import com.hazelcast.jet.cdc.ChangeRecord;
import com.hazelcast.jet.cdc.mysql.MySqlCdcSources; |
codereview_java_data_3237 | }
}
- @Deprecated
public Date getSessionCredentitalsExpiration() {
credentialsLock.readLock().lock();
try {
```suggestion @Deprecated Use {@link #getSessionCredentialsExpiration()} instead. ```
}
}
+ @Deprecated Use {@link #getSessionCredentialsExpiration()} instead.
public Date getSessionCredentitalsExpiration() {
credentialsLock.readLock().lock();
try { |
codereview_java_data_3238 | package net.sourceforge.pmd.lang.java.typeresolution;
import java.lang.reflect.Method;
import java.util.List;
import net.sourceforge.pmd.lang.java.typeresolution.typedefinition.JavaTypeDefinition;
any reason for these fields not being final / `argTypes` an unmodifiable list?
package net.sourceforge.pmd.lang.java.typeresolution;
import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
import net.sourceforge.pmd.lang.java.typeresolution.typedefinition.JavaTypeDefinition; |
codereview_java_data_3241 | * }</pre>
*
* @param createSnapshotFn a function to create an object to store in the
- * state snapshot. It must be stateless
* @param <S> type of the snapshot object
*
* @since 3.1
```suggestion * state snapshot. It must be stateless. ```
* }</pre>
*
* @param createSnapshotFn a function to create an object to store in the
+ * state snapshot. It must be stateless.
* @param <S> type of the snapshot object
*
* @since 3.1 |
codereview_java_data_3251 | public class ConcurrentDeleteTableIT extends AccumuloClusterHarness {
- @Test(timeout = 3 * 60 * 1000)
public void testConcurrentDeleteTablesOps() throws Exception {
try (AccumuloClient c = Accumulo.newClient().from(getClientProps()).build()) {
String[] tables = getUniqueNames(2);
In the super class, we have a method that can be overridden called `defaultTimeoutSeconds`, which probably would work better for this. The timeout for that is scalable on the command-line with `-Dtimeout.factor=2` or similar. See `SplitIT.java` for an example.
public class ConcurrentDeleteTableIT extends AccumuloClusterHarness {
+ @Override
+ protected int defaultTimeoutSeconds() {
+ return 7 * 60;
+ }
+
+ @Test
public void testConcurrentDeleteTablesOps() throws Exception {
try (AccumuloClient c = Accumulo.newClient().from(getClientProps()).build()) {
String[] tables = getUniqueNames(2); |
codereview_java_data_3261 | }
public Object visit(ASTFieldDeclaration node, Object data) {
- List<Modifier> unnecessary = new ArrayList<>();
if (node.isSyntacticallyPublic()) {
unnecessary.add(Modifier.PUBLIC);
}
possibly better to use an `EnumSet<Modifier>` both for performance and avoiding duplicates
}
public Object visit(ASTFieldDeclaration node, Object data) {
+ Set<Modifier> unnecessary = EnumSet.noneOf(Modifier.class);
if (node.isSyntacticallyPublic()) {
unnecessary.add(Modifier.PUBLIC);
} |
codereview_java_data_3270 | if (!CastManager.isInitialized()) {
return;
}
}
Why was this line removed? Isn't the whole `onPause` function useless now?
if (!CastManager.isInitialized()) {
return;
}
+ castButtonVisibilityManager.setResumed(false);
} |
codereview_java_data_3272 | *
* @return
*/
- Map<String, DataVersion> getAclConfigVersion();
/**
* Update globalWhiteRemoteAddresses in acl yaml config file
It makes the interface incompatible to older versions, you'd better add a new method and deprecate the original ones.
*
* @return
*/
+ @Deprecated
+ String getAclConfigVersion();
/**
* Update globalWhiteRemoteAddresses in acl yaml config file |
codereview_java_data_3290 | }
@Test
- public void testPartitionsTableScan() throws IOException {
-
- // Make 4 Manifests
table.newFastAppend()
.appendFile(FILE_PARTITION_0)
.commit();
I haven't looked very closely, but this appears to be a really long test. My guess is that you're mixing test cases that should be in separate methods. Can you clean it up so that you're testing cases individually?
}
@Test
+ public void testPartitionsTableScanNoFilter() throws IOException {
table.newFastAppend()
.appendFile(FILE_PARTITION_0)
.commit(); |
codereview_java_data_3292 | this.snsClient = AmazonSNSClientBuilder.defaultClient();
}
this.webhookManager = webhookManager;
- this.publishExecutor = managedCachedThreadPoolFactory.get("webhook-publish", configuration.getMaxConcurrentWebhooks());
this.typeToArn = new ConcurrentHashMap<>();
}
Leaving a note here to double check our naming here, for both `managedCachedThreadPoolFactory` and `maxConcurrentWebhooks`
this.snsClient = AmazonSNSClientBuilder.defaultClient();
}
this.webhookManager = webhookManager;
+ this.publishExecutor = threadPoolFactory.get("webhook-publish", configuration.getMaxConcurrentWebhooks());
this.typeToArn = new ConcurrentHashMap<>();
} |
codereview_java_data_3305 | int retries = context.getConfiguration().getCount(Property.TSERV_BULK_RETRY);
if (retries == 0) {
- log.warn("Retries set to 0. All failed map file assignments will not be retried.");
completeFailures.putAll(assignmentFailures);
} else {
for (Entry<Path,List<KeyExtent>> entry : assignmentFailures.entrySet()) {
Minor grammatical improvement. (Kein vs. Nicht) ```suggestion log.warn("Retries set to 0. No failed map file assignments will be retried."); ```
int retries = context.getConfiguration().getCount(Property.TSERV_BULK_RETRY);
if (retries == 0) {
+ log.error("Retries set to 0. No failed map file assignments will be retried.");
completeFailures.putAll(assignmentFailures);
} else {
for (Entry<Path,List<KeyExtent>> entry : assignmentFailures.entrySet()) { |
codereview_java_data_3312 | private String brokerAddr;
- private Map<String, DataVersion> aclConfigDataVersion;
private String clusterName;
Add a new field other than changing it for compatibility.
private String brokerAddr;
+ @Deprecated
+ private DataVersion aclConfigDataVersion;
+
+ private Map<String, DataVersion> allAclConfigDataVersion;
private String clusterName; |
codereview_java_data_3317 | if ((messageRecord.isPending() || messageRecord.isFailed()) && pushDestination && !messageRecord.isForcedSms()) {
background = SENT_PUSH_PENDING;
triangleBackground = SENT_PUSH_PENDING_TRIANGLE;
- } else if (messageRecord.isPending() || messageRecord.isPendingSmsFallback()) {
background = SENT_SMS_PENDING;
triangleBackground = SENT_SMS_PENDING_TRIANGLE;
} else if (messageRecord.isPush()) {
You don't want to add failed to this one too?
if ((messageRecord.isPending() || messageRecord.isFailed()) && pushDestination && !messageRecord.isForcedSms()) {
background = SENT_PUSH_PENDING;
triangleBackground = SENT_PUSH_PENDING_TRIANGLE;
+ } else if (messageRecord.isPending() || messageRecord.isFailed() || messageRecord.isPendingSmsFallback()) {
background = SENT_SMS_PENDING;
triangleBackground = SENT_SMS_PENDING_TRIANGLE;
} else if (messageRecord.isPush()) { |
codereview_java_data_3321 | }
@VisibleForTesting
- P2PNetwork getP2PNetwork() {
- return networkRunner.getNetwork();
}
}
It's quite unfortunate to have to expose the whole `P2PNetwork`. Is it possible for this to only return the local enode (via delegation)?
}
@VisibleForTesting
+ Optional<EnodeURL> getLocalEnode() {
+ return networkRunner.getNetwork().getLocalEnode();
}
} |
codereview_java_data_3330 | private boolean checkAccount(){
Account currentAccount = sessionManager.getCurrentAccount();
if (currentAccount == null) {
- Timber.d("Current account is null");
ViewUtil.showLongToast(this, getResources().getString(R.string.user_not_logged_in));
sessionManager.forceLogin(this);
return false;
This changes are valid but irrelevant with this PR, please revert them.
private boolean checkAccount(){
Account currentAccount = sessionManager.getCurrentAccount();
if (currentAccount == null) {
ViewUtil.showLongToast(this, getResources().getString(R.string.user_not_logged_in));
sessionManager.forceLogin(this);
return false; |
codereview_java_data_3332 | }
callback.onSet(connection, response, info, statement, System.nanoTime() - startTime);
// if the response from the server has warnings, they'll be set on the ExecutionInfo. Log them
- // here, if enabled.
- if (logger.isWarnEnabled()
- && response.warnings != null
- && !response.warnings.isEmpty()
- && Boolean.getBoolean(RequestHandler.LOG_REQUEST_WARNINGS_PROPERTY)) {
- for (String warning : response.warnings) {
- logger.warn(warning);
- }
}
} catch (Exception e) {
callback.onException(
What will happen if that property `RequestHandler.LOG_REQUEST_WARNINGS_PROPERTY))` will be not set?
}
callback.onSet(connection, response, info, statement, System.nanoTime() - startTime);
// if the response from the server has warnings, they'll be set on the ExecutionInfo. Log them
+ // here, unless they've been disabled.
+ if (logger.isWarnEnabled() && response.warnings != null && !response.warnings.isEmpty()) {
+ logServerWarnings(response.warnings);
}
} catch (Exception e) {
callback.onException( |
codereview_java_data_3335 | ops.current().snapshot(snapshotId) : ops.current().currentSnapshot();
// snapshot could be null when the table just gets created
- Iterable<ManifestFile> manifests = (snapshot != null) ? snapshot.manifests() : CloseableIterable.empty();
- CloseableIterable<ManifestEntry> entries = new ManifestGroup(ops, manifests)
.filterData(rowFilter)
.filterFiles(fileFilter)
.filterPartitions(partitionFilter)
If there are no manifests, then entries should be `CloseableIterable.empty()`, not the manifest iterable. That doesn't need to be closeable.
ops.current().snapshot(snapshotId) : ops.current().currentSnapshot();
// snapshot could be null when the table just gets created
+ if (snapshot == null) {
+ return CloseableIterable.empty();
+ }
+ // when snapshot is not null
+ CloseableIterable<ManifestEntry> entries = new ManifestGroup(ops, snapshot.manifests())
.filterData(rowFilter)
.filterFiles(fileFilter)
.filterPartitions(partitionFilter) |
codereview_java_data_3337 | String iconColor = localNotification.getIconColor();
if (iconColor != null) {
- mBuilder.setColor(Color.parseColor(iconColor));
}
createActionIntents(localNotification, mBuilder);
this crash if the color is not valid, put it inside a try catch (check other plugins like Browser or Statusbar)
String iconColor = localNotification.getIconColor();
if (iconColor != null) {
+ try {
+ mBuilder.setColor(Color.parseColor(iconColor));
+ } catch (Exception ex) {
+ call.error("The iconColor string was not able to be parsed. Please provide a valid string hexidecimal color code.", ex);
+ return;
+ }
}
createActionIntents(localNotification, mBuilder); |
codereview_java_data_3344 | public Optional<Collection<RoundChange>> appendRoundChangeMessage(final RoundChange msg) {
if (!isMessageValid(msg)) {
- LOG.debug("RoundChange message was invalid.");
return Optional.empty();
}
Why is an invalid RoundChange debug, but an invalid Proposal an info? (see IbftBlockHeightManager) - I think I prefer info in both places (this is an exceptional behaviour and we want to see it even normally)
public Optional<Collection<RoundChange>> appendRoundChangeMessage(final RoundChange msg) {
if (!isMessageValid(msg)) {
+ LOG.info("RoundChange message was invalid.");
return Optional.empty();
} |
codereview_java_data_3346 | private long id;
private long distance;
- public long getId() { return this.id; }
public void setId(long id) { this.id = id; }
- public long getDistance() { return this.distance; }
public void setDistance(long distance) { this.distance = distance; }
Lets not have getters and setters, but instead just make fields public. Remember these classes are pure "data", there are no methods that need to enforce invariants that would require private fields. Making them public also makes their use simpler.
private long id;
private long distance;
+ public long getId() { return id; }
public void setId(long id) { this.id = id; }
+ public long getDistance() { return distance; }
public void setDistance(long distance) { this.distance = distance; } |
codereview_java_data_3358 | import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
-import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
Minor nitpick but should have space between casting of `context` i.e. `(Activity) context`
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; |
codereview_java_data_3365 | JobResult jobResult = new JobResult(jobId, config, coordinator, creationTime, completionTime,
error != null ? error.toString() : null);
- JobMetrics prevMetrics = jobMetrics.putIfAbsent(jobId, terminalMetrics);
if (prevMetrics != null) {
- logger.warning("Overwrote job metrics for job " + jobResult);
}
JobResult prev = jobResults.putIfAbsent(jobId, jobResult);
if (prev != null) {
We should just use `put`, not `putIfAbsent`: if a value was there, that was probably some error and we at least correct it. Even the logging 2 lines below says so.
JobResult jobResult = new JobResult(jobId, config, coordinator, creationTime, completionTime,
error != null ? error.toString() : null);
+ JobMetrics prevMetrics = jobMetrics.put(jobId, terminalMetrics);
if (prevMetrics != null) {
+ logger.warning("Overwriting job metrics for job " + jobResult);
}
JobResult prev = jobResults.putIfAbsent(jobId, jobResult);
if (prev != null) { |
codereview_java_data_3375 | @Test
public void printClassWithoutJavaDocButWithComment() {
- String code = "/** javadoc */ public class A { \n// stuff\n}";
CompilationUnit cu = JavaParser.parse(code);
PrettyPrinterConfiguration ignoreJavaDoc = new PrettyPrinterConfiguration().setPrintJavaDoc(false);
String content = cu.toString(ignoreJavaDoc);
- assertEquals("public class A {\n // stuff\n}\n", content);
}
}
Use the Utils.EOL constant instead of \n so the test doesn't fail on Windows :-(
@Test
public void printClassWithoutJavaDocButWithComment() {
+ String code = String.format("/** javadoc */ public class A { %s// stuff%s}", EOL, EOL);
CompilationUnit cu = JavaParser.parse(code);
PrettyPrinterConfiguration ignoreJavaDoc = new PrettyPrinterConfiguration().setPrintJavaDoc(false);
String content = cu.toString(ignoreJavaDoc);
+ assertEquals(String.format("public class A {%s // stuff%s}%s", EOL, EOL, EOL), content);
}
} |
codereview_java_data_3376 | final String fileType = tika.detect(tikaInputStream);
final String fileExtension = Files.getFileExtension(fileDetail.getFileName()).toLowerCase();
ImportFormatType format = ImportFormatType.of(fileExtension);
- if (!fileType.contains("msoffice")) {
// We had a problem where we tried to upload the downloaded file from the import options, it was somehow changed the
// extension we use this fix.
- if (!fileType.contains("application/vnd.ms-excel")) {
throw new GeneralPlatformDomainRuleException("error.msg.invalid.file.extension",
"Uploaded file extension is not recognized.");
- }
}
Workbook workbook = new HSSFWorkbook(clonedInputStreamWorkbook);
GlobalEntityType entityType=null;
the double `if` is a little bit weird; it would be nicer if this was a single if, with an `&&` ?
final String fileType = tika.detect(tikaInputStream);
final String fileExtension = Files.getFileExtension(fileDetail.getFileName()).toLowerCase();
ImportFormatType format = ImportFormatType.of(fileExtension);
+ if (!fileType.contains("msoffice") && !fileType.contains("application/vnd.ms-excel")) {
// We had a problem where we tried to upload the downloaded file from the import options, it was somehow changed the
// extension we use this fix.
throw new GeneralPlatformDomainRuleException("error.msg.invalid.file.extension",
"Uploaded file extension is not recognized.");
+
}
Workbook workbook = new HSSFWorkbook(clonedInputStreamWorkbook);
GlobalEntityType entityType=null; |
codereview_java_data_3382 | " Validate.notEmpty(mapArg, \"message %s %s\", \"msg\", \"msg\");",
" Validate.notEmpty(stringArg, \"message %s %s\", \"msg\", \"msg\");",
" Validate.notBlank(stringArg, \"message %s %s\", \"msg\", \"msg\");",
- " Validate.notBlank(stringArg, \"message %s %s\", \"msg\", compileTimeConstant);",
- " Validate.notBlank(stringArg, \"message %s %s\", \"msg\", localConstant);",
" Validate.noNullElements(arrayArg, \"message %s %s\", \"msg\", \"msg\");",
" Validate.noNullElements(iterableArg, \"message %s %s\", \"msg\", \"msg\");",
" Validate.validIndex(arrayArg, 1, \"message %s %s\", \"msg\", \"msg\");",
this test fails. usage of `compileTimeConstant` passes.
" Validate.notEmpty(mapArg, \"message %s %s\", \"msg\", \"msg\");",
" Validate.notEmpty(stringArg, \"message %s %s\", \"msg\", \"msg\");",
" Validate.notBlank(stringArg, \"message %s %s\", \"msg\", \"msg\");",
" Validate.noNullElements(arrayArg, \"message %s %s\", \"msg\", \"msg\");",
" Validate.noNullElements(iterableArg, \"message %s %s\", \"msg\", \"msg\");",
" Validate.validIndex(arrayArg, 1, \"message %s %s\", \"msg\", \"msg\");", |
codereview_java_data_3408 | } catch (Exception e) {
}
System.out.printf("%-32s %-32s %-4d %-20d %-20d %-20s %-20d %s%n",
UtilAll.frontStringAtLeast(mq.getTopic(), 32),
UtilAll.frontStringAtLeast(mq.getBrokerName(), 32),
mq.getQueueId(),
offsetWrapper.getBrokerOffset(),
offsetWrapper.getConsumerOffset(),
- messageQueueAllocationResult.containsKey(mq) ? messageQueueAllocationResult.get(mq) : "NA",
diff,
lastTime
);
Not that important here, but you can do the same with accessing `messageQueueAllocationResult` only once. `get()` and see if it is null.
} catch (Exception e) {
}
+ String clientIP = messageQueueAllocationResult.get(mq);
System.out.printf("%-32s %-32s %-4d %-20d %-20d %-20s %-20d %s%n",
UtilAll.frontStringAtLeast(mq.getTopic(), 32),
UtilAll.frontStringAtLeast(mq.getBrokerName(), 32),
mq.getQueueId(),
offsetWrapper.getBrokerOffset(),
offsetWrapper.getConsumerOffset(),
+ null != clientIP ? clientIP : "NA",
diff,
lastTime
); |
codereview_java_data_3415 | import org.apache.accumulo.core.client.lexicoder.Lexicoder;
import org.apache.accumulo.core.client.rfile.RFile;
/**
* Entry point for majority of Accumulo's public API. Other Accumulo API entry points are linked
* later.
Later? Could say linked below.
import org.apache.accumulo.core.client.lexicoder.Lexicoder;
import org.apache.accumulo.core.client.rfile.RFile;
+//CHECKSTYLE:OFF
/**
* Entry point for majority of Accumulo's public API. Other Accumulo API entry points are linked
* later. |
codereview_java_data_3419 | package com.alibaba.nacos.naming.push;
-import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.util.VersionUtil;
It can be replace by self StringUtils
package com.alibaba.nacos.naming.push;
+import com.alibaba.nacos.common.utils.StringUtils;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.util.VersionUtil; |
codereview_java_data_3423 | void subscribe(final String topic, final String subExpression) throws MQClientException;
/**
* Subscribe some topic
*
* @param fullClassName full class name,must extend org.apache.rocketmq.common.filter. MessageFilter
Please describe the reason of why this API should be deprecated, and list the version number that will remove this API.
void subscribe(final String topic, final String subExpression) throws MQClientException;
/**
+ * This method will be removed in the version 5.0.0,because filterServer was removed,and method <code>subscribe(final String topic, final MessageSelector messageSelector)</code>
+ * is recommended.
+ *
* Subscribe some topic
*
* @param fullClassName full class name,must extend org.apache.rocketmq.common.filter. MessageFilter |
codereview_java_data_3424 | });
}
public boolean update(Member newMember, ObjectEqual<Member> objEqual) {
Loggers.CLUSTER.debug("member information update : {}", newMember);
Please do not change the indent. Please use nacos codestyle to reformat your change. detail see source code `style/nacosCodeStyle.md.`
});
}
+ /**
+ * member information update accord objEqual.
+ *
+ * @param newMember need update
+ * @param objEqual condition equal
+ * @return
+ */
public boolean update(Member newMember, ObjectEqual<Member> objEqual) {
Loggers.CLUSTER.debug("member information update : {}", newMember); |
codereview_java_data_3431 | import org.jbpm.process.core.context.variable.Variable;
import org.jbpm.process.core.context.variable.VariableScope;
-public interface VariableDeclarations {
- String getType(String vname);
-
- Map<String, String> getTypes();
-
- static VariableDeclarations of(VariableScope vscope) {
HashMap<String, String> vs = new HashMap<>();
for (Variable variable : vscope.getVariables()) {
vs.put(variable.getName(), variable.getType().getStringType());
any reason why this is interface and then we create anonymous class?
import org.jbpm.process.core.context.variable.Variable;
import org.jbpm.process.core.context.variable.VariableScope;
+public class VariableDeclarations {
+ public static VariableDeclarations of(VariableScope vscope) {
HashMap<String, String> vs = new HashMap<>();
for (Variable variable : vscope.getVariables()) {
vs.put(variable.getName(), variable.getType().getStringType()); |
codereview_java_data_3442 | void setBottomSheetDetailsSmaller();
}
- interface ListView {
void updateListFragment(List<Place> placeList);
}
Lets rename this to something else, ListView is android framework keyword
void setBottomSheetDetailsSmaller();
}
+ interface NearbyListView {
void updateListFragment(List<Place> placeList);
} |
codereview_java_data_3448 | nextValue = profile.getBasalValues()[i + 1];
if (profileBlock.getDuration() * 60 != (nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds)
return false;
- if (Math.abs(profileBlock.getBasalAmount() - basalValue.value) > (basalValue.value > 5 ? 0.1 : 0.01))
return false;
}
return true;
Just checking: is this >5 or >=5? (profileBlock.getBasalAmount() could be 5.03 and basalValue.value could be 5?)
nextValue = profile.getBasalValues()[i + 1];
if (profileBlock.getDuration() * 60 != (nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds)
return false;
+ if (Math.abs(profileBlock.getBasalAmount() - basalValue.value) >= (profileBlock.getBasalAmount() >= 5 ? 0.1 : 0.01))
return false;
}
return true; |
codereview_java_data_3453 | this(accumuloPropsLocation, Collections.emptyMap());
}
- @SuppressFBWarnings(value = "URLCONNECTION_SSRF_FD",
- justification = "location of props is specified by an admin")
public SiteConfiguration(URL accumuloPropsLocation, Map<String,String> overrides) {
config = createMap(accumuloPropsLocation, overrides);
}
private static ImmutableMap<String,String> createMap(URL accumuloPropsLocation,
Map<String,String> overrides) {
CompositeConfiguration config = new CompositeConfiguration();
Not sure, but may be able to do the following : ```java overrides.forEach(result::put); ```
this(accumuloPropsLocation, Collections.emptyMap());
}
public SiteConfiguration(URL accumuloPropsLocation, Map<String,String> overrides) {
config = createMap(accumuloPropsLocation, overrides);
}
+ @SuppressFBWarnings(value = "URLCONNECTION_SSRF_FD",
+ justification = "location of props is specified by an admin")
private static ImmutableMap<String,String> createMap(URL accumuloPropsLocation,
Map<String,String> overrides) {
CompositeConfiguration config = new CompositeConfiguration(); |
codereview_java_data_3455 | import java.util.HashMap;
import java.util.Map;
import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
import com.alibaba.fastjson.JSON;
Will `topicConfigMap` `subGroupConfigMap` be used by multiple threads? If not, it would be better just use plain HashMap here.
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.alibaba.fastjson.JSON; |
codereview_java_data_3461 | public class AuditContactListener {
// Injection does not work because this class is not managed by CDI
private AuditRepository auditRepository;
/**
You could note that this is fixed in Java EE 7 :-)
public class AuditContactListener {
// Injection does not work because this class is not managed by CDI
+ // NOTE: JPA 2.1 will support CDI Injection in EntityListener - in Java EE 7
private AuditRepository auditRepository;
/** |
codereview_java_data_3470 | } finally {
master.shutdown();
master.destroy();
- UtilAll.deleteFile(new File(storePath));
}
}
It seems that this test only covers the consistent condition?
} finally {
master.shutdown();
master.destroy();
+ deleteDirectory(storePath);
}
} |
codereview_java_data_3479 | StorageComponent delegate() {
StorageComponent result = delegate;
if (result != null) return delegate;
result = factory.getBean(StorageComponent.class);
if (result instanceof TracingStorageComponent) {
result = ((TracingStorageComponent) result).delegate;
Should this be synchronized i.e. double check?
StorageComponent delegate() {
StorageComponent result = delegate;
if (result != null) return delegate;
+ // synchronization is not needed as redundant calls have no ill effects
result = factory.getBean(StorageComponent.class);
if (result instanceof TracingStorageComponent) {
result = ((TracingStorageComponent) result).delegate; |
codereview_java_data_3482 | private static final String DELIVERY_REPORT = "d_rpt";
static final String PART_COUNT = "part_count";
- protected static final String STATUS_WHERE = STATUS + " = ?";
-
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + ID + " INTEGER PRIMARY KEY, " +
THREAD_ID + " INTEGER, " + DATE_SENT + " INTEGER, " + DATE_RECEIVED + " INTEGER, " + MESSAGE_BOX + " INTEGER, " +
READ + " INTEGER DEFAULT 0, " + MESSAGE_ID + " TEXT, " + SUBJECT + " TEXT, " +
Is this used somewhere else? If it's only used in the one place below, there's no need to create a class-level contant.
private static final String DELIVERY_REPORT = "d_rpt";
static final String PART_COUNT = "part_count";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + ID + " INTEGER PRIMARY KEY, " +
THREAD_ID + " INTEGER, " + DATE_SENT + " INTEGER, " + DATE_RECEIVED + " INTEGER, " + MESSAGE_BOX + " INTEGER, " +
READ + " INTEGER DEFAULT 0, " + MESSAGE_ID + " TEXT, " + SUBJECT + " TEXT, " + |
codereview_java_data_3492 | return false;
} else {
HashMap<String, BrokerData> brokers = clusterInfo.getBrokerAddrTable();
- for (Entry<String, BrokerData> brokerNameEntry : brokers.entrySet()) {
- HashMap<Long, String> brokerIps = brokerNameEntry.getValue().getBrokerAddrs();
for (Entry<Long, String> brokerIdEntry : brokerIps.entrySet()) {
if (brokerIdEntry.getValue().contains(ip))
return true;
brokerNameEntry could be renamed to brokerEntry
return false;
} else {
HashMap<String, BrokerData> brokers = clusterInfo.getBrokerAddrTable();
+ for (Entry<String, BrokerData> brokerEntry : brokers.entrySet()) {
+ HashMap<Long, String> brokerIps = brokerEntry.getValue().getBrokerAddrs();
for (Entry<Long, String> brokerIdEntry : brokerIps.entrySet()) {
if (brokerIdEntry.getValue().contains(ip))
return true; |
codereview_java_data_3495 | s.put("hideSpecialAccounts", Settings.versions(
new V(1, new BooleanSetting(false))
));
- s.put("privacyMode", Settings.versions(
- new V(1, new BooleanSetting(false))
));
s.put("language", Settings.versions(
new V(1, new LanguageSetting())
I don't think this can just be renamed; it's saying that privacyMode is a BooleanSetting, which it's not.
s.put("hideSpecialAccounts", Settings.versions(
new V(1, new BooleanSetting(false))
));
+ s.put("keyguardPrivacy", Settings.versions(
+ new V(1, new BooleanSetting(false)),
+ new V(12,null)
));
s.put("language", Settings.versions(
new V(1, new LanguageSetting()) |
codereview_java_data_3497 | public HashMap<String, String> getRuntimeInfo() {
HashMap<String, String> result = this.storeStatsService.getRuntimeInfo();
- String commitLogStorePath = DefaultMessageStore.this.getMessageStoreConfig().getStorePathCommitLog();
- if (commitLogStorePath.contains(MessageStoreConfig.MULTI_PATH_SPLITTER)) {
double minPhysicsUsedRatio = Double.MAX_VALUE;
String[] paths = commitLogStorePath.trim().split(MessageStoreConfig.MULTI_PATH_SPLITTER);
for (String clPath : paths) {
double physicRatio = UtilAll.isPathExists(clPath) ?
Dose it support dledger mode? the original code getStorePathPhysic() has different value of commitLogStorePath in dledger mode
public HashMap<String, String> getRuntimeInfo() {
HashMap<String, String> result = this.storeStatsService.getRuntimeInfo();
+ {
double minPhysicsUsedRatio = Double.MAX_VALUE;
+ String commitLogStorePath = getStorePathPhysic();
String[] paths = commitLogStorePath.trim().split(MessageStoreConfig.MULTI_PATH_SPLITTER);
for (String clPath : paths) {
double physicRatio = UtilAll.isPathExists(clPath) ? |
codereview_java_data_3513 | final SortedMap<UInt256, UInt256> updatedStorage = updated.getUpdatedStorage();
if (!updatedStorage.isEmpty()) {
// Apply any storage updates
- MerklePatriciaTrie<Bytes32, BytesValue> storageTrie =
freshState
? wrapped.newAccountStorageTrie(Hash.EMPTY_TRIE_HASH)
: origin.storageTrie();
nit: should be final. ```suggestion final MerklePatriciaTrie<Bytes32, BytesValue> storageTrie = ```
final SortedMap<UInt256, UInt256> updatedStorage = updated.getUpdatedStorage();
if (!updatedStorage.isEmpty()) {
// Apply any storage updates
+ final MerklePatriciaTrie<Bytes32, BytesValue> storageTrie =
freshState
? wrapped.newAccountStorageTrie(Hash.EMPTY_TRIE_HASH)
: origin.storageTrie(); |
codereview_java_data_3520 | import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.cloud.dataflow.server.repository.DuplicateStreamDefinitionException;
-import org.springframework.cloud.dataflow.server.repository.NoSuchStreamDefinitionException;
-import org.springframework.cloud.dataflow.server.repository.StreamDefinitionRepository;
import org.springframework.cloud.dataflow.core.ModuleDefinition;
import org.springframework.cloud.dataflow.core.ModuleDeploymentId;
import org.springframework.cloud.dataflow.core.StreamDefinition;
need to re-org imports to address alphabetical order
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.dataflow.core.ModuleDefinition;
import org.springframework.cloud.dataflow.core.ModuleDeploymentId;
import org.springframework.cloud.dataflow.core.StreamDefinition; |
codereview_java_data_3524 | public void launchApp(String id) {
execute(ChromeDriverCommand.LAUNCH_APP, ImmutableMap.of("id", id));
}
-
- @Override
- public TouchScreen getTouch() {
- return new RemoteTouchScreen(this.getExecuteMethod());
- }
}
would be better to store as a local private variable (like locationContext / webStorage) and only inialize it once on construction. also fix the indentation here
public void launchApp(String id) {
execute(ChromeDriverCommand.LAUNCH_APP, ImmutableMap.of("id", id));
}
+
} |
codereview_java_data_3525 | ImmutableSet.of(DataOperations.OVERWRITE, DataOperations.REPLACE, DataOperations.DELETE);
private static final Set<String> VALIDATE_DATA_FILES_EXIST_SKIP_DELETE_OPERATIONS =
ImmutableSet.of(DataOperations.OVERWRITE, DataOperations.REPLACE);
- // delete files are only added in "overwrite" operations
private static final Set<String> VALIDATE_REPLACED_DATA_FILES_OPERATIONS =
- ImmutableSet.of(DataOperations.OVERWRITE);
private final String tableName;
private final TableOperations ops;
The rewrite deletes action will replace old deletes with new ones. Does that count add deletes operation?
ImmutableSet.of(DataOperations.OVERWRITE, DataOperations.REPLACE, DataOperations.DELETE);
private static final Set<String> VALIDATE_DATA_FILES_EXIST_SKIP_DELETE_OPERATIONS =
ImmutableSet.of(DataOperations.OVERWRITE, DataOperations.REPLACE);
+ // delete files can be added in "overwrite" or "delete" operations
private static final Set<String> VALIDATE_REPLACED_DATA_FILES_OPERATIONS =
+ ImmutableSet.of(DataOperations.OVERWRITE, DataOperations.DELETE);
private final String tableName;
private final TableOperations ops; |
codereview_java_data_3543 | invsum += monster.inventory(i);
TestEq(invsum, 10);
- // Method using a vector access object:
- ByteVector inventoryVector = monster.inventoryVector();
- TestEq(inventoryVector.length(), 5);
- invsum = 0;
- for (int i = 0; i < inventoryVector.length(); i++)
- invsum += inventoryVector.getAsUnsigned(i);
- TestEq(invsum, 10);
-
// Alternative way of accessing a vector:
ByteBuffer ibb = monster.inventoryAsByteBuffer();
invsum = 0;
Aren't indexing functions in Java typically called `at`? Or is `get` more typical?
invsum += monster.inventory(i);
TestEq(invsum, 10);
// Alternative way of accessing a vector:
ByteBuffer ibb = monster.inventoryAsByteBuffer();
invsum = 0; |
codereview_java_data_3554 | + "order by mgr, deptno";
RelNode r = checkPlanning(tester, preProgram, new HepPlanner(program), sql);
- RelCollation c = r.getInput(0).getTraitSet().getTrait(RelCollationTraitDef.INSTANCE);
- assertEquals("Collation is incorrect", "[3, 7]", c.toString());
}
@Test public void testWindowOnSortedInput1() {
From the tests you gave, i couldn't figure out what you are fixing, because both the input and output nodes collation are the same.
+ "order by mgr, deptno";
RelNode r = checkPlanning(tester, preProgram, new HepPlanner(program), sql);
+ RelCollation ci = r.getInput(0).getTraitSet().getTrait(RelCollationTraitDef.INSTANCE);
+ assertEquals("Window collation is incorrect", "[3, 7]", ci.toString());
+ RelCollation co = r.getTraitSet().getTrait(RelCollationTraitDef.INSTANCE);
+ assertEquals("Project collation is incorrect", "[0, 1]", co.toString());
}
@Test public void testWindowOnSortedInput1() { |
codereview_java_data_3563 | }
}
- // This is a set of WALs that are closed but may still be referenced byt tablets. A LinkedHashSet
// is used because its very import to know the order in which WALs were closed when deciding if a
- // WAL is eligible for removal.
LinkedHashSet<DfsLogger> closedLogs = new LinkedHashSet<>();
@VisibleForTesting
Might want to emphasize that this insertion ordering assumes we only have one log open (and thus one closed) at a time. This isn't future proof if we add multiple open logs, but as long as we declare that assumption, I think it's fine.
}
}
+ // This is a set of WALs that are closed but may still be referenced by tablets. A LinkedHashSet
// is used because its very import to know the order in which WALs were closed when deciding if a
+ // WAL is eligible for removal. Maintaining the order that logs were used in is currently a simple
+ // task because there is only one active log at a time.
LinkedHashSet<DfsLogger> closedLogs = new LinkedHashSet<>();
@VisibleForTesting |
codereview_java_data_3565 | /** This should be used as a {@link ClassRule} as it takes a very long time to start-up. */
class KafkaCollectorRule extends ExternalResource {
static final Logger LOGGER = LoggerFactory.getLogger(KafkaCollectorRule.class);
- static final String IMAGE = "openzipkin/zipkin-kafka";
static final int KAFKA_PORT = 19092;
static final String KAFKA_BOOTSTRAP_SERVERS = "localhost:" + KAFKA_PORT;
static final String KAFKA_TOPIC = "zipkin";
in others, we were specifying version tag. latest might be fine even if not necessarily repeatable... it would be less maintenance (and less thrashy than "master" tag) wdyt cc @anuraaga
/** This should be used as a {@link ClassRule} as it takes a very long time to start-up. */
class KafkaCollectorRule extends ExternalResource {
static final Logger LOGGER = LoggerFactory.getLogger(KafkaCollectorRule.class);
+ static final String IMAGE = "openzipkin/zipkin-kafka:latest";
static final int KAFKA_PORT = 19092;
static final String KAFKA_BOOTSTRAP_SERVERS = "localhost:" + KAFKA_PORT;
static final String KAFKA_TOPIC = "zipkin"; |
codereview_java_data_3576 | }
}
- /**
- * Service data changed event.
- */
- public static class ServiceRemovedEvent extends ServiceEvent {
-
- private static final long serialVersionUID = 2123694271992630822L;
-
- public ServiceRemovedEvent(Service service) {
- super(service);
- }
- }
}
I think this event is not useful. It can be replaced by ServiceMetadataEvent(service, true)
}
}
} |
codereview_java_data_3595 | Node<V> node = idToNode.get(entry.getKey());
Node<V> parent = idToNode.get(entry.getValue());
if (parent == null) { // handle headless trace
- if (rootNode == null)
rootNode = new Node<>();
rootNode.addChild(node);
} else {
parent.addChild(node);
rootNode = Node.MISSING_ROOT ^^ something like this makes the code more obvious, plus you can search references for Node.MISSING_ROOT, where you can't search references for null
Node<V> node = idToNode.get(entry.getKey());
Node<V> parent = idToNode.get(entry.getValue());
if (parent == null) { // handle headless trace
+ if (rootNode == null) {
rootNode = new Node<>();
+ rootNode.missingRootDummyNode = true;
+ }
rootNode.addChild(node);
} else {
parent.addChild(node); |
codereview_java_data_3596 | */
public abstract class JdbcLob extends TraceObject {
- final class Output extends PipedOutputStream {
private final Task task;
- Output(PipedInputStream snk, Task task) throws IOException {
super(snk);
this.task = task;
}
can we give this a more useful name? "Output" is rather generic. LobPipedOutputStream?
*/
public abstract class JdbcLob extends TraceObject {
+ final class LobPipedOutputStream extends PipedOutputStream {
private final Task task;
+ LobPipedOutputStream(PipedInputStream snk, Task task) throws IOException {
super(snk);
this.task = task;
} |
codereview_java_data_3601 | ((BigDecimal) obj).scale());
case TIMESTAMP:
return TimestampData.fromEpochMillis((Long) obj);
default:
return obj;
}
I think this should use the generator for generics and validate against generic data. That will catch more cases.
((BigDecimal) obj).scale());
case TIMESTAMP:
return TimestampData.fromEpochMillis((Long) obj);
+ case TIME:
+ return ((Long) obj).intValue();
default:
return obj;
} |
codereview_java_data_3614 | }
char replyCodeCategory = line.charAt(0);
- if ((replyCodeCategory == '4') || (replyCodeCategory == '5')) {
if (mEnhancedStatusCodesProvided) {
throw buildEnhancedNegativeSmtpReplyException(replyCode, results);
} else {
I meant something like 'isReplyCodeErrorCategory' ;)
}
char replyCodeCategory = line.charAt(0);
+ boolean isReplyCodeErrorCategory = (replyCodeCategory == '4') || (replyCodeCategory == '5');
+ if (isReplyCodeErrorCategory) {
if (mEnhancedStatusCodesProvided) {
throw buildEnhancedNegativeSmtpReplyException(replyCode, results);
} else { |
codereview_java_data_3618 | Set<Module> modules = kompile.parseModules(compiledDefinition, defModuleNameUpdated, specModuleNameUpdated, absSpecFile,
backend.excludedModuleTags(), readOnlyCache);
// avoid the module duplication bug #1838
- //Map<String, Module> modulesMap = modules.stream().collect(Collectors.toMap(Module::name, m -> m));
- Map<String, List<Module>> group = modules.stream().collect(Collectors.groupingBy(Module::name));
- Map<String, Module> modulesMap = group.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, x -> x.getValue().get(0)));
Definition parsedDefinition = compiledDefinition.getParsedDefinition();
Module specModule = getModule(specModuleNameUpdated, modulesMap, parsedDefinition);
Can this change also come out in a refactoring PR?
Set<Module> modules = kompile.parseModules(compiledDefinition, defModuleNameUpdated, specModuleNameUpdated, absSpecFile,
backend.excludedModuleTags(), readOnlyCache);
// avoid the module duplication bug #1838
+ Map<String, Module> modulesMap = modules.stream().collect(Collectors.toMap(Module::name, m -> m));
+ //Map<String, List<Module>> group = modules.stream().collect(Collectors.groupingBy(Module::name));
+ //Map<String, Module> modulesMap = group.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, x -> x.getValue().get(0)));
Definition parsedDefinition = compiledDefinition.getParsedDefinition();
Module specModule = getModule(specModuleNameUpdated, modulesMap, parsedDefinition); |
codereview_java_data_3625 | returnBase64(call, exif, bitmapOutputStream);
} else if (settings.getResultType() == CameraResultType.URI) {
returnFileURI(call, exif, bitmap, u, bitmapOutputStream);
- } else if (settings.getResultType() == CameraResultType.BASE64NOMETADATA) {
- returnBase64NoMetadata(call, exif, bitmapOutputStream);
} else {
call.reject(INVALID_RESULT_TYPE_ERROR);
}
Looks like you made changes on `CameraResultType` class, but didn't commit them. And you also have to do the changes on the types in @capacitor/core
returnBase64(call, exif, bitmapOutputStream);
} else if (settings.getResultType() == CameraResultType.URI) {
returnFileURI(call, exif, bitmap, u, bitmapOutputStream);
+ } else if (settings.getResultType() == CameraResultType.DATA_URL) {
+ returnDATA_URL(call, exif, bitmapOutputStream);
} else {
call.reject(INVALID_RESULT_TYPE_ERROR);
} |
codereview_java_data_3627 | }
ContentValues cv = new ContentValues();
- cv.put("tag", context.getPackageName() + "/.RoutingActivity");
cv.put("count", count);
context.getContentResolver().insert(
would prefer to get the launch activity programmatically if we can since this may be an unnoticed bug if we ever change from RoutingActivity something like `context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()).getComponent().getShortClassName()` might work (untested)
}
ContentValues cv = new ContentValues();
+ Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
+ String launchIntentClassname = launchIntent.getComponent().getClassName();
+ cv.put("tag", context.getPackageName() + "/" + launchIntentClassname);
cv.put("count", count);
context.getContentResolver().insert( |
codereview_java_data_3629 | import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Objects;
-import org.apache.accumulo.core.util.Base64;
import org.apache.hadoop.io.Writable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
I had thought these both (commons and our built-in utility for base64) might have been replaced in 2.0 with the built-in Base64 decoder, but I can't recall.
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
+import java.util.Base64;
import java.util.Objects;
import org.apache.hadoop.io.Writable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; |
codereview_java_data_3631 | OutputFile outFile = Files.localOutput(parquetFile);
try (FileAppender<Record> appender = Parquet.write(outFile)
.schema(FILE_SCHEMA)
- .withWriterVersion(WriterVersion.PARQUET_2_0) // V2 is needed to force dictionary encoding for FIXED type
.build()) {
GenericRecordBuilder builder = new GenericRecordBuilder(convert(FILE_SCHEMA, "table"));
// create 20 copies of each record to ensure dictionary-encoding
Why is this?
OutputFile outFile = Files.localOutput(parquetFile);
try (FileAppender<Record> appender = Parquet.write(outFile)
.schema(FILE_SCHEMA)
+ .withWriterVersion(writerVersion)
.build()) {
GenericRecordBuilder builder = new GenericRecordBuilder(convert(FILE_SCHEMA, "table"));
// create 20 copies of each record to ensure dictionary-encoding |
codereview_java_data_3632 | }
@Test
- public void testCaseIssue3106() {
- plsql.parse("CREATE OR REPLACE PROCEDURE bar\nIS\n v_link varchar2(10) := 'xxx';\nBEGIN\n EXECUTE IMMEDIATE 'drop database link ' || v_link;\nEND bar;");
}
}
Test name should be something like "testExecuteImmediateIssue3106" - the test before (#1454) is indeed about the case statement.... but #3106 is about execute immediate. Please put the test source in a separate file, so that we can better read it. In that file, you can use multiple lines and don't need escapes.
}
@Test
+ public void testExecuteImmediateIssue3106() {
+ plsql.parseResource("ExecuteImmediateIssue3106.pls");
}
} |
codereview_java_data_3637 | */
package javaslang.collection.euler;
import javaslang.collection.List;
import org.junit.Test;
import java.time.DayOfWeek;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.assertThat;
/**
Hi @ashrko619 What about `For(List.range(startYear, endYear + 1), List.range(1, 13))`? :)
*/
package javaslang.collection.euler;
+import javaslang.Tuple;
import javaslang.collection.List;
import org.junit.Test;
import java.time.DayOfWeek;
import java.time.LocalDate;
+import static javaslang.API.For;
import static org.assertj.core.api.Assertions.assertThat;
/** |
codereview_java_data_3655 | private static final String DEFAULT_VAR = "Var";
private static final String JSON_NODE = "com.fasterxml.jackson.databind.JsonNode";
private static final String DEFAULT_WORKFLOW_VAR = "workflowdata";
- private static final Set<String> DEFAULT_IMPORTS = new HashSet<>(Arrays.asList("org.jbpm.serverless.workflow.parser.util.ServerlessWorkflowUtils"));
-
public RuleFlowProcess createProcess(Workflow workflow) {
RuleFlowProcess process = new RuleFlowProcess();
any reason for this to be a Set specifically? You may use a collection and avoid the `new HashSet()` altogether.
private static final String DEFAULT_VAR = "Var";
private static final String JSON_NODE = "com.fasterxml.jackson.databind.JsonNode";
private static final String DEFAULT_WORKFLOW_VAR = "workflowdata";
public RuleFlowProcess createProcess(Workflow workflow) {
RuleFlowProcess process = new RuleFlowProcess(); |
codereview_java_data_3656 | mmsDatabase.delete(item.getMessageId());
MessageNotifier.updateNotification(context, item.getMasterSecret(), messageAndThreadId.second);
- if(item.getMasterSecret() == null)
- PebbleNotifier.sendMmsNotification(context, item.getMasterSecret(), messageAndThreadId.first, messageAndThreadId.second);
}
private void sendRetrievedAcknowledgement(DownloadItem item) {
I think you mean != null? If you want masterSecret checks, let's move them into PebbleNotifier. But you should get intelligent text even if it is null.
mmsDatabase.delete(item.getMessageId());
MessageNotifier.updateNotification(context, item.getMasterSecret(), messageAndThreadId.second);
+ PebbleNotifier.sendMmsNotification(context, item.getMasterSecret(), messageAndThreadId.first);
}
private void sendRetrievedAcknowledgement(DownloadItem item) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.