id stringlengths 23 26 | content stringlengths 182 2.49k |
|---|---|
codereview_java_data_1230 | * necessarily be computed on any node of the type they support).
*
* <p>Metrics support a concept of {@linkplain MetricOption options},
- * which can be passed to {@link Metric#compute(Metric, MetricOptions, Node) compute}
* or {@link MetricsUtil#computeMetric(Metric, Node, MetricOptions)}.
*
* <p>Metric instances are stateless by contract.
Since we define this as a new method, maybe we should use the same argument order as in MetricsUtil, so that MetricOptions comes last....
* necessarily be computed on any node of the type they support).
*
* <p>Metrics support a concept of {@linkplain MetricOption options},
+ * which can be passed to {@link Metric#compute(Metric, Node, MetricOptions) compute}
* or {@link MetricsUtil#computeMetric(Metric, Node, MetricOptions)}.
*
* <p>Metric instances are stateless by contract. |
codereview_java_data_1237 | List<Variable> variables = new ArrayList<>();
Set<String> keys = new HashSet<>();
- variables.add(
- Variable
- .newBuilder()
- .setName("INHERIT_ENV_VARS")
- .setValue(Joiner.on(" ").join(inheritVariables))
- .build()
- );
-
taskInfo
.getExecutor()
.getCommand()
If we are going to loop over these, no need to make it another variable. Doing it this way will end up setting an extra variable that will be unused. Can add the list instead as another getter and loop over it in the template functions to avoid duplication/unused vars
List<Variable> variables = new ArrayList<>();
Set<String> keys = new HashSet<>();
taskInfo
.getExecutor()
.getCommand() |
codereview_java_data_1245 | }
validateIdentityLinkArguments(identityId, type);
if (restApiInterceptor != null) {
- restApiInterceptor.deleteCaseInstanceIdentityLink(caseInstance, identityId, type);
}
- getIdentityLink(identityId, type, caseInstance.getId());
-
runtimeService.deleteUserIdentityLink(caseInstance.getId(), identityId, type);
response.setStatus(HttpStatus.NO_CONTENT.value());
Lets do this a bit more specific like when fetching a specific link. So just before we delete the link we can do `deleteCaseInstanceIdentityLink(caseInstance, link)`, where `link` comes from the `getIdentityLink` call.
}
validateIdentityLinkArguments(identityId, type);
+
+ IdentityLink link = getIdentityLink(identityId, type, caseInstance.getId());
+
if (restApiInterceptor != null) {
+ restApiInterceptor.deleteCaseInstanceIdentityLink(caseInstance, link);
}
runtimeService.deleteUserIdentityLink(caseInstance.getId(), identityId, type);
response.setStatus(HttpStatus.NO_CONTENT.value()); |
codereview_java_data_1246 | package org.flowable.engine.impl.webservice;
public class Operands {
Missing required license header
+/* 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
package org.flowable.engine.impl.webservice;
public class Operands { |
codereview_java_data_1253 | }
public static PrometheusMeterRegistry getPrometheusMeterRegistry() {
return prometheusMeterRegistry;
}
Can you add a null check with an error like "PrometheusRegistryProvider must be initialised" or similar?
}
public static PrometheusMeterRegistry getPrometheusMeterRegistry() {
+ if (prometheusMeterRegistry == null) {
+ throw new IllegalStateException("PrometheusRegistryProvider has not been initialized");
+ }
return prometheusMeterRegistry;
} |
codereview_java_data_1254 | engineeringMode = engineeringModeSemaphore.exists() && engineeringModeSemaphore.isFile();
devBranch = BuildConfig.VERSION.contains("dev");
- if (!isDevModeOrRelease()) {
Notification n = new Notification(Notification.TOAST_ALARM, gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL);
bus().post(new EventNewNotification(n));
}
The name makes it easy to confuse dev-branch and engineering-mode. Should be `isEngineeringModeOrRelease`.
engineeringMode = engineeringModeSemaphore.exists() && engineeringModeSemaphore.isFile();
devBranch = BuildConfig.VERSION.contains("dev");
+ if (!isEngineeringModeOrRelease()) {
Notification n = new Notification(Notification.TOAST_ALARM, gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL);
bus().post(new EventNewNotification(n));
} |
codereview_java_data_1255 | } catch (Exception e) {
log.warn("exception while doing multi-scan ", e);
addResult(e);
- } catch (Error t) {
- log.warn("Error while doing multi-scan ", t);
- addResult(t);
- throw t;
} finally {
Thread.currentThread().setName(oldThreadName);
runState.set(ScanRunState.FINISHED);
Is there value in adding this to the result if we're re-throwing?
} catch (Exception e) {
log.warn("exception while doing multi-scan ", e);
addResult(e);
} finally {
Thread.currentThread().setName(oldThreadName);
runState.set(ScanRunState.FINISHED); |
codereview_java_data_1258 | public class GenerateCoverage implements AutoCloseable {
private final boolean cover;
private final FileUtil files;
- private final PrintWriter allFiles;
public GenerateCoverage(boolean cover, FileUtil files) {
this.cover = cover;
this.files = files;
files.resolveKompiled(".").mkdirs();
try {
- allFiles = new PrintWriter(new BufferedWriter(new FileWriter(files.resolveKompiled("allRules.txt").getAbsolutePath())));
} catch (IOException e) {
throw KEMException.internalError("Could not write list of rules to coverage document.", e);
}
rename this to `allRulesFile` or something? `allFiles` sounds strange
public class GenerateCoverage implements AutoCloseable {
private final boolean cover;
private final FileUtil files;
+ private final PrintWriter allRulesFile;
public GenerateCoverage(boolean cover, FileUtil files) {
this.cover = cover;
this.files = files;
files.resolveKompiled(".").mkdirs();
try {
+ allRulesFile = new PrintWriter(new BufferedWriter(new FileWriter(files.resolveKompiled("allRules.txt").getAbsolutePath())));
} catch (IOException e) {
throw KEMException.internalError("Could not write list of rules to coverage document.", e);
} |
codereview_java_data_1264 | private final Object executionLock = new Object();
private final ILogger logger;
private String jobName;
- private List<File> localFiles = new ArrayList<>();
// dest vertex id --> dest ordinal --> sender addr --> receiver tasklet
private Map<Integer, Map<Integer, Map<Address, ReceiverTasklet>>> receiverMap = emptyMap();
this list is accessed concurrently, but is not thread-safe
private final Object executionLock = new Object();
private final ILogger logger;
private String jobName;
+
+ // key: resource identifier
+ private ConcurrentMap<String, File> localFiles = new ConcurrentHashMap<>();
// dest vertex id --> dest ordinal --> sender addr --> receiver tasklet
private Map<Integer, Map<Integer, Map<Address, ReceiverTasklet>>> receiverMap = emptyMap(); |
codereview_java_data_1270 | filesMatch(Lists.newArrayList("C", "D", "E"), appendsBetweenScan(2, 5));
Assert.assertTrue(listener1.event().fromSnapshotId() == 2);
Assert.assertTrue(listener1.event().toSnapshotId() == 5);
}
@Test
I'm in favor of check all fields as it's the only test verifying IncrementalScanEvent, but others may have different thought on this.
filesMatch(Lists.newArrayList("C", "D", "E"), appendsBetweenScan(2, 5));
Assert.assertTrue(listener1.event().fromSnapshotId() == 2);
Assert.assertTrue(listener1.event().toSnapshotId() == 5);
+ Assert.assertEquals(table.schema(), listener1.event().projection());
+ Assert.assertEquals(Expressions.alwaysTrue(), listener1.event().filter());
+ Assert.assertEquals("test", listener1.event().tableName());
}
@Test |
codereview_java_data_1272 | if (rule instanceof XPathRule || rule instanceof RuleReference && ((RuleReference) rule).getRule() instanceof XPathRule) {
lines.add("**This rule is defined by the following XPath expression:**");
- lines.add("```xpath");
lines.addAll(toLines(StringUtils.stripToEmpty(rule.getProperty(XPathRule.XPATH_DESCRIPTOR))));
lines.add("```");
} else {
For the other languages, I used a space before the language hint... But it actually doesn't matter...
if (rule instanceof XPathRule || rule instanceof RuleReference && ((RuleReference) rule).getRule() instanceof XPathRule) {
lines.add("**This rule is defined by the following XPath expression:**");
+ lines.add("``` xpath");
lines.addAll(toLines(StringUtils.stripToEmpty(rule.getProperty(XPathRule.XPATH_DESCRIPTOR))));
lines.add("```");
} else { |
codereview_java_data_1274 | logger.fine("processing ancestor " + ancestor.value());
}
DependencyLinkSpan ancestorLink = ancestor.value();
- if (ancestorLink != null &&
ancestorLink.kind == DependencyLinkSpan.Kind.SERVER) {
parent = ancestorLink.service;
break;
similarly here, if we use a sentinel instead of null, I think the code is more self-describing.. ``` if (ancestor == Node.MISSING_ROOT) { // explain } else ... existing code ```
logger.fine("processing ancestor " + ancestor.value());
}
DependencyLinkSpan ancestorLink = ancestor.value();
+ if (!ancestor.isSyntheticRootForPartialTree() &&
ancestorLink.kind == DependencyLinkSpan.Kind.SERVER) {
parent = ancestorLink.service;
break; |
codereview_java_data_1276 | private static PendingIntent createProgressStringIntent(Context context) {
Intent startingIntent = new Intent(context, MediaButtonReceiver.class);
startingIntent.setAction(MediaButtonReceiver.NOTIFY_PROGRESS_STRING_RECEIVER);
- startingIntent.putExtra(MediaButtonReceiver.DUMMY_VALUE,"DUMMY_VALUE");
return PendingIntent.getBroadcast(context, 0, startingIntent, 0);
}
Maybe you can use `MediaButtonReceiver.DUMMY_VALUE` in place of `"DUMMY_VALUE"` I assume with the extra, it won't work?
private static PendingIntent createProgressStringIntent(Context context) {
Intent startingIntent = new Intent(context, MediaButtonReceiver.class);
startingIntent.setAction(MediaButtonReceiver.NOTIFY_PROGRESS_STRING_RECEIVER);
+ startingIntent.putExtra(MediaButtonReceiver.DUMMY_VALUE,MediaButtonReceiver.DUMMY_VALUE);
return PendingIntent.getBroadcast(context, 0, startingIntent, 0);
} |
codereview_java_data_1284 | public abstract class RestJobsService implements JobsService {
public static final String JOBS_PATH = "/jobs";
private URI jobsServiceUri;
Wouldn't it have more sense to thrown an exception in case jobServiceUrl is null? From my point of view it is not valid value and we should fail fast.
public abstract class RestJobsService implements JobsService {
+ @SuppressWarnings("squid:S1075")
public static final String JOBS_PATH = "/jobs";
private URI jobsServiceUri; |
codereview_java_data_1300 | negate = true;
}
- String profileName = "";
- if (cl.hasOption(profileNameOpt.getOpt())) {
- profileName = cl.getOptionValue(profileNameOpt.getOpt());
- }
-
final Authorizations auths = getAuths(cl, shellState);
final BatchScanner scanner = shellState.getAccumuloClient().createBatchScanner(tableName,
auths, numThreads);
The super class `ScanCommand` has a protected method called `addScanIterators()`. I am not completely sure, but I think you may be able to call it to setup the profile iters. If so, very little changes would be needed for this class.
negate = true;
}
final Authorizations auths = getAuths(cl, shellState);
final BatchScanner scanner = shellState.getAccumuloClient().createBatchScanner(tableName,
auths, numThreads); |
codereview_java_data_1303 | @Inject
public MailTemplateHelpers(SandboxManager sandboxManager, SingularityConfiguration singularityConfiguration) {
- taskDatePattern = singularityConfiguration.getDefaultDatePattern();
- timeZone = singularityConfiguration.getTimeZone();
this.uiBaseUrl = singularityConfiguration.getUiConfiguration().getBaseUrl();
this.sandboxManager = sandboxManager;
this.smtpConfiguration = singularityConfiguration.getSmtpConfiguration();
lets follow the format of the ones below with this.x = ...
@Inject
public MailTemplateHelpers(SandboxManager sandboxManager, SingularityConfiguration singularityConfiguration) {
+ this.taskDatePattern = singularityConfiguration.getMailerDatePattern();
+ this.timeZone = singularityConfiguration.getMailerTimeZone();
this.uiBaseUrl = singularityConfiguration.getUiConfiguration().getBaseUrl();
this.sandboxManager = sandboxManager;
this.smtpConfiguration = singularityConfiguration.getSmtpConfiguration(); |
codereview_java_data_1305 | .observeOn(AndroidSchedulers.mainThread())
.subscribe(this::populatePlaces,
throwable -> {
- if (throwable instanceof UnknownHostException || throwable instanceof ConnectException) {
- showErrorMessage(getString(R.string.slow_internet));
- } else {
- showErrorMessage(throwable.getMessage());
- }
progressBar.setVisibility(View.GONE);
});
nearbyMapFragment.setBundleForUpdtes(bundle);
May be we should replace this with `showErrorMessage(R.string.error_loading_nearby)` with `error_loading_nearby` as string for "Error while loading Nearby locations that need images" or something similar. (I guess conveying the fact "... Nearby locations that need images" in the error would be informative part of the error though not related to the actual error that has occured ;-)) We could put `throwable.getMessage()` where it's appropriate, the log. This way the exception isn't visible to the user. Alternatively, we could try and find the possible exceptions that happen and provide a more user-friendly message for each exception. This should improve the user experience. Anyway, showing the exception message to the user would in no way be helpful to the non-technical users.
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::populatePlaces,
throwable -> {
+ Timber.d(throwable);
+ showErrorMessage(getString(R.string.error_fetching_nearby_places));
progressBar.setVisibility(View.GONE);
});
nearbyMapFragment.setBundleForUpdtes(bundle); |
codereview_java_data_1308 | * If true, a default {@link OAuth2AuthorizedClient} can be discovered from the current Authentication. It is
* recommended to be cautious with this feature since all HTTP requests will receive the access token if it can be
* resolved from the current Authentication.
- *
* @param defaultOAuth2AuthorizedClient true if a default {@link OAuth2AuthorizedClient} should be used, else false.
* Default is false.
*/
Please remove any changes that are formatting related. Only code changes should be included.
* If true, a default {@link OAuth2AuthorizedClient} can be discovered from the current Authentication. It is
* recommended to be cautious with this feature since all HTTP requests will receive the access token if it can be
* resolved from the current Authentication.
* @param defaultOAuth2AuthorizedClient true if a default {@link OAuth2AuthorizedClient} should be used, else false.
* Default is false.
*/ |
codereview_java_data_1311 | runTimeConfiguration,
liveReload.isLiveReload());
- Map<String, byte[]> generatedClasses = new HashMap<>();
- generatedKogitoClasses.forEach(g -> generatedClasses.putAll(g.getGeneratedClasses()));
// Json schema files
- generatedFiles.addAll(generateJsonSchema(context, aggregatedIndex, generatedClasses));
// Write files to disk
dumpFilesToDisk(context.getAppPaths(), generatedFiles);
I think we migth avoid anynomous class here by using for (KogitoGeneratedClassesBuildItem g: generatedKogitoClasses) { generatedClasses.putAll(g.generatedClasses());}
runTimeConfiguration,
liveReload.isLiveReload());
+ Map<String, byte[]> classes = new HashMap<>();
+ for (KogitoGeneratedClassesBuildItem generatedKogitoClass : generatedKogitoClasses) {
+ classes.putAll(generatedKogitoClass.getGeneratedClasses());
+ }
// Json schema files
+ generatedFiles.addAll(generateJsonSchema(context, aggregatedIndex, classes));
// Write files to disk
dumpFilesToDisk(context.getAppPaths(), generatedFiles); |
codereview_java_data_1317 | /**
* Data Flow Stream property key prefix.
*/
- public static final String STREAM_PREFIX = PREFIX + "stream.";
/**
* Stream name property key.
any `PREFIX` vars that are only used here should be `private`
/**
* Data Flow Stream property key prefix.
*/
+ private static final String STREAM_PREFIX = PREFIX + "stream.";
/**
* Stream name property key. |
codereview_java_data_1323 | exceptions.add(line);
}
} catch (IOException ioe) {
- ioe.printStackTrace();
}
}
Could you change this printStackTrace please? We should just rethrow it as `throw new RuntimeException(ioe);` since if we get an error here, it doesn't make sense to continue with that rule at all, so we should simply abort.
exceptions.add(line);
}
} catch (IOException ioe) {
+ throw new RuntimeException(ioe);
}
} |
codereview_java_data_1327 | }
public static void main(String[] args) {
- System.setProperty("hazelcast.logging.type", "log4j");
JetInstance jet = Jet.newJetInstance();
Jet.newJetInstance();
new BatchCoGroup(jet).go();
The result looks like this: ``` result: 12->([PageVisit{3}, PageVisit{4}], [AddToCart{23}, AddToCart{24}], [Payment{33}, Payment{34}]) 11->([PageVisit{1}, PageVisit{2}], [AddToCart{21}, AddToCart{22}], [Payment{31}, Payment{32}]) ``` Would be good if the `Event` objects would print their `userId`s too, because then we could see that the result is correct.
}
public static void main(String[] args) {
JetInstance jet = Jet.newJetInstance();
Jet.newJetInstance();
new BatchCoGroup(jet).go(); |
codereview_java_data_1329 | // possible race condition here, if table is renamed
String tableName = Tables.getTableName(context, tableId);
AccumuloConfiguration acuTableConf =
- new ConfigurationCopy(context.tableOperations().getPropertiesMap(tableName));
Configuration conf = context.getHadoopConf();
Do we still need the old ConfigurationCopy constructor now that these have been changed to use the constructor that uses a Map? If not, I would delete the constructor that takes an Iterable. It's safe to make that change, since it's internal only, and not public API.
// possible race condition here, if table is renamed
String tableName = Tables.getTableName(context, tableId);
AccumuloConfiguration acuTableConf =
+ new ConfigurationCopy(context.tableOperations().getConfiguration(tableName));
Configuration conf = context.getHadoopConf(); |
codereview_java_data_1335 | import org.flowable.common.engine.impl.el.function.VariableLowerThanOrEqualsExpressionFunction;
import org.flowable.common.engine.impl.el.function.VariableNotEqualsExpressionFunction;
import org.flowable.common.engine.impl.history.HistoryLevel;
-import org.flowable.common.engine.impl.interceptor.*;
import org.flowable.common.engine.impl.logging.LoggingSession;
import org.flowable.common.engine.impl.logging.LoggingSessionFactory;
import org.flowable.common.engine.impl.persistence.GenericManagerFactory;
Project standards do not allow package imports; please leave the individual imports.
import org.flowable.common.engine.impl.el.function.VariableLowerThanOrEqualsExpressionFunction;
import org.flowable.common.engine.impl.el.function.VariableNotEqualsExpressionFunction;
import org.flowable.common.engine.impl.history.HistoryLevel;
+import org.flowable.common.engine.impl.interceptor.Command;
+import org.flowable.common.engine.impl.interceptor.CommandConfig;
+import org.flowable.common.engine.impl.interceptor.CommandContext;
+import org.flowable.common.engine.impl.interceptor.CommandInterceptor;
+import org.flowable.common.engine.impl.interceptor.EngineConfigurationConstants;
+import org.flowable.common.engine.impl.interceptor.SessionFactory;
+import org.flowable.common.engine.impl.interceptor.InstantiateErrorHandler;
import org.flowable.common.engine.impl.logging.LoggingSession;
import org.flowable.common.engine.impl.logging.LoggingSessionFactory;
import org.flowable.common.engine.impl.persistence.GenericManagerFactory; |
codereview_java_data_1338 | Object timerMetric = metric.startTiming("getpendingdomainrolememberslist_timing", null, principalDomain);
logPrincipal(ctx);
validateRequest(ctx.request(), caller);
- Principal ctxPrincipal = ((RsrcCtxWrapper) ctx).principal();
if (LOG.isDebugEnabled()) {
- LOG.debug("getpendingdomainrolememberslist:(" + ctxPrincipal + ")");
}
DomainRoleMembership domainRoleMembership = dbService.getPendingDomainRoleMembersList(ctx);
metric.stopTiming(timerMetric, null, principalDomain);
since we get the principal object only for debug we should included it within the if block or just reference it directly in the debug call
Object timerMetric = metric.startTiming("getpendingdomainrolememberslist_timing", null, principalDomain);
logPrincipal(ctx);
validateRequest(ctx.request(), caller);
if (LOG.isDebugEnabled()) {
+ LOG.debug("getpendingdomainrolememberslist:(" + ((RsrcCtxWrapper) ctx).principal() + ")");
}
DomainRoleMembership domainRoleMembership = dbService.getPendingDomainRoleMembersList(ctx);
metric.stopTiming(timerMetric, null, principalDomain); |
codereview_java_data_1345 | @Nonnull
public static synchronized JetInstance getInstance() {
if (supplier == null) {
- supplier = memoizeConcurrent(JetBootstrap::createStandaloneInstance);
}
return supplier.get();
}
we may need to disable DiscoveryConfig too by setting an empty config `join.setDiscoveryConfig(new DiscoveryConfig());` And disable advanced network config `hzconfig.getAdvancedNetworkConfig().setEnabled(false);`
@Nonnull
public static synchronized JetInstance getInstance() {
if (supplier == null) {
+ supplier = new ConcurrentMemoizingSupplier<>(() -> new InstanceProxy(createStandaloneInstance()));
}
return supplier.get();
} |
codereview_java_data_1349 | Object getParameter(String key);
/**
- * get config context
*
* @return configContext
*/
Capitalize the first letter
Object getParameter(String key);
/**
+ * Get config context
*
* @return configContext
*/ |
codereview_java_data_1351 | package org.flowable.editor.language.xml;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.AssertionsForClassTypes.tuple;
import org.flowable.bpmn.BpmnAutoLayout;
import org.flowable.bpmn.model.BpmnModel;
Please use only `Assertions`.
package org.flowable.editor.language.xml;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.tuple;
import org.flowable.bpmn.BpmnAutoLayout;
import org.flowable.bpmn.model.BpmnModel; |
codereview_java_data_1357 | }
@Override public boolean decode(byte[] span, Collection<Span> out) { // ex DependencyLinker
- Span result = decodeOne(ReadBuffer.wrap(span, 0));
if (result == null) return false;
out.add(result);
return true;
}
@Override public boolean decodeList(byte[] spans, Collection<Span> out) { // ex getTrace
- return new V1JsonSpanReader().readList(ReadBuffer.wrap(spans, 0), out);
}
@Override public boolean decodeList(ByteBuffer spans, Collection<Span> out) {
adding the methods here allows us to not break the BytesDecoder interface, yet still allow us the overloads for our builtin types
}
@Override public boolean decode(byte[] span, Collection<Span> out) { // ex DependencyLinker
+ Span result = decodeOne(ReadBuffer.wrap(span));
if (result == null) return false;
out.add(result);
return true;
}
@Override public boolean decodeList(byte[] spans, Collection<Span> out) { // ex getTrace
+ return new V1JsonSpanReader().readList(ReadBuffer.wrap(spans), out);
}
@Override public boolean decodeList(ByteBuffer spans, Collection<Span> out) { |
codereview_java_data_1366 | removedTasks.add(queue.remove().getData());
}
- assertThat(queue.getReadFileNumber()).isEqualTo(0);
// Check that all tasks were read correctly.
removedTasks.add(queue.remove().getData());
If the first file has been read and closed, shouldn't the readFile number increment to 1?? ```suggestion assertThat(queue.getReadFileNumber()).isEqualTo(1); ```
removedTasks.add(queue.remove().getData());
}
+ // read one more to make sure we are reading from the next file
+ removedTasks.add(queue.remove().getData());
+ assertThat(queue.getReadFileNumber()).isEqualTo(1);
// Check that all tasks were read correctly.
removedTasks.add(queue.remove().getData()); |
codereview_java_data_1378 | TableFilter filter = readSimpleTableFilter();
command.setTableFilter(filter);
command.setSetClauseList(readUpdateSetClause(filter));
- if (readIf(FROM)) {
- TableFilter fromTable = readTableFilter();
- command.setFromTableFilter(fromTable);
}
if (readIf(WHERE)) {
command.setCondition(readExpression());
I think it would be better to restrict this feature to PostgreSQL compatibility mode. It is completely non-standard and non-portable. You need to add a new flag to `org.h2.engine.Mode`. The SQL Standard has a more powerful command for this purpose and current H2 and many other DBMS support it well (but PostgreSQL doesn't).
TableFilter filter = readSimpleTableFilter();
command.setTableFilter(filter);
command.setSetClauseList(readUpdateSetClause(filter));
+ if (database.getMode().allowUsingFromClauseInUpdateStatement && readIf(FROM)) {
+ TableFilter fromTable = readTableFilter();
+ command.setFromTableFilter(fromTable);
}
if (readIf(WHERE)) {
command.setCondition(readExpression()); |
codereview_java_data_1390 | throw new JobNotFoundException(jobId);
}
- DAG dag = deserializeDag(masterContext, jobRecord);
- Set<String> ownedObservables = ownedObservables(dag);
-
completeObservables(ownedObservables, error);
JobConfig config = jobRecord.getConfig();
deserializing the DAG is expensive operation. We did a lot of optimization so that there is as little overhead as possible during Job Completion and this undoes it. We can know which observables are known in MasterContext during job initialization without having to deserialize it again.
throw new JobNotFoundException(jobId);
}
+ Set<String> ownedObservables = jobRecord.getOwnedObservables();
completeObservables(ownedObservables, error);
JobConfig config = jobRecord.getConfig(); |
codereview_java_data_1393 | }
}
- public long getLockTimeout() {
Setting setting = findSetting(
SetTypes.getTypeName(SetTypes.DEFAULT_LOCK_TIMEOUT));
return setting == null ? Constants.INITIAL_LOCK_TIMEOUT : setting.getIntValue();
why does this return long?
}
}
+ public int getLockTimeout() {
Setting setting = findSetting(
SetTypes.getTypeName(SetTypes.DEFAULT_LOCK_TIMEOUT));
return setting == null ? Constants.INITIAL_LOCK_TIMEOUT : setting.getIntValue(); |
codereview_java_data_1396 | Log.e("Surface","Change");
Camera.Parameters parameters = mCamera.getParameters();
int state = Camera2.getState();
- if(state == 1 ) { parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); }
- else if(state == 2) { parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); }
- else { parameters.setFlashMode(Camera.Parameters.FLASH_MODE_ON); }
-
try{
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, w, h);
if (mSupportFocus.contains(Camera.Parameters.FOCUS_MODE_AUTO))
Move the if stmts body to another line. If you want you may not use brackets as well.
Log.e("Surface","Change");
Camera.Parameters parameters = mCamera.getParameters();
int state = Camera2.getState();
+ if(state == 1 )
+ parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
+ else if(state == 2)
+ parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
+ else
+ parameters.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
try{
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, w, h);
if (mSupportFocus.contains(Camera.Parameters.FOCUS_MODE_AUTO)) |
codereview_java_data_1402 | import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import java.util.List;
Why should the first letter be changed to lowercase?
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
+import com.alibaba.nacos.api.selector.AbstractSelector;
import java.util.List; |
codereview_java_data_1414 | *
* @param <T> type of the emitted item
*/
- public interface SourceBuffer<T> extends Serializable {
/**
* Returns the number of items the buffer holds.
This doesn't need to be serializable.
*
* @param <T> type of the emitted item
*/
+ public interface SourceBuffer<T> {
/**
* Returns the number of items the buffer holds. |
codereview_java_data_1427 | /** Exception during XPath evaluation. */
public class XPathEvaluationException extends RuntimeException {
- XPathEvaluationException(Throwable cause) {
super(cause);
}
is package-private the intended visibility? or you just missed the access modifier?
/** Exception during XPath evaluation. */
public class XPathEvaluationException extends RuntimeException {
+ public XPathEvaluationException(Throwable cause) {
super(cause);
} |
codereview_java_data_1433 | }
- public static JSONObject createJsonObject(String response){
- JSONObject jsonObject = null;
- try {
- jsonObject = new JSONObject(response);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return jsonObject;
- }
-
}
This looks more like a generic utils method, so it would be more properly to move it to **openfoodfacts.github.scrachx.openfood.utils.Utils.java** class.
}
} |
codereview_java_data_1434 | import org.apache.spark.sql.types.DataTypes;
import org.junit.AfterClass;
import org.junit.Assert;
-import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
I don't think it is a good idea for tests to create `Timestamp` or `Date` objects because those representations are tied to a time zone in the JVM implementation. If you have to use them, then pass an instant in milliseconds or microseconds that is produced by Iceberg's literals: `Literal.of("2020-02-02 01:00:00").to(TimestampType.withoutZone()).value()`
import org.apache.spark.sql.types.DataTypes;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test; |
codereview_java_data_1438 | if (file == null) {
writeMemoryToFile();
}
- return fileProviderInterface.getUriForProvidedFile(file, mimeType);
}
private void writeMemoryToFile() throws IOException {
This mixes two concepts. I think it's better if this class only knows about files. Constructing the content URI should be the responsibility of another class.
if (file == null) {
writeMemoryToFile();
}
+ return fileProviderInterface.getUriForProvidedFile(file, encoding, mimeType);
}
private void writeMemoryToFile() throws IOException { |
codereview_java_data_1442 | DataFile copy();
/**
- * @return List of offsets for blocks of a file, if applicable, null otherwise.
* When available, this information is used for planning scan tasks whose boundaries
- * are determined by these offsets.It is important that the returned list is sorted
- * in ascending order.
*/
List<Long> splitOffsets();
}
Nit: missing a space. I think we should phrase the new content a little differently. "It is important" isn't very clear. I think it should be "offsets will be returned in sorted order."
DataFile copy();
/**
+ * @return List of recommended split locations, if applicable, null otherwise.
* When available, this information is used for planning scan tasks whose boundaries
+ * are determined by these offsets. The returned list must be sorted in ascending order.
*/
List<Long> splitOffsets();
} |
codereview_java_data_1444 | // Only remove per request handler if the channel is registered
// or open since DefaultChannelPipeline would remove handlers if
// channel is closed and unregistered
- // See DefaultChannelPipeline.java#L1403
if (channel.isOpen() || channel.isRegistered()) {
removeIfExists(channel.pipeline(),
HttpStreamsClientHandler.class,
I think this line number is out of date.
// Only remove per request handler if the channel is registered
// or open since DefaultChannelPipeline would remove handlers if
// channel is closed and unregistered
if (channel.isOpen() || channel.isRegistered()) {
removeIfExists(channel.pipeline(),
HttpStreamsClientHandler.class, |
codereview_java_data_1453 | return joinClause;
}
@SuppressWarnings("unchecked")
public <T, T1, R> DistributedBiFunction<?, ? super T1, ?> adaptHashJoinOutputFn(
@Nonnull DistributedBiFunction<? super T, ? super T1, ? extends R> mapToOutputFn
we could add `@Nonnull` to output values as well
return joinClause;
}
+ @Nonnull
@SuppressWarnings("unchecked")
public <T, T1, R> DistributedBiFunction<?, ? super T1, ?> adaptHashJoinOutputFn(
@Nonnull DistributedBiFunction<? super T, ? super T1, ? extends R> mapToOutputFn |
codereview_java_data_1459 | TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
-// resetFood();
updateEarliestDataChange(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
This has to be handled some way
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
log.error("Unhandled exception", e); |
codereview_java_data_1464 | try {
return classLoader.loadClass(mainClass);
} catch (ClassNotFoundException e) {
- System.err.println("Cannot load main class: " + mainClass);
throw e;
}
}
should say cannot find or load main class, I think?
try {
return classLoader.loadClass(mainClass);
} catch (ClassNotFoundException e) {
+ System.err.println("Cannot find or load main class: " + mainClass);
throw e;
}
} |
codereview_java_data_1481 | if (audioPlayer == null) {
return;
}
- audioPlayer.backToCover(true);
float condensedSlideOffset = Math.max(0.0f, Math.min(0.2f, slideOffset - 0.2f)) / 0.2f;
audioPlayer.getExternalPlayerHolder().setAlpha(1 - condensedSlideOffset);
Should this really be a smooth scroll? Also, I would only do that when the fragment is already out of view. When pressing the back button, one can otherwise see the whole screen scrolling by while the bottom sheet closes.
if (audioPlayer == null) {
return;
}
+
+ if (slideOffset == 0.0f) { //STATE_COLLAPSED
+ audioPlayer.backToCover();
+ }
float condensedSlideOffset = Math.max(0.0f, Math.min(0.2f, slideOffset - 0.2f)) / 0.2f;
audioPlayer.getExternalPlayerHolder().setAlpha(1 - condensedSlideOffset); |
codereview_java_data_1482 | import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
-import java.util.HashMap;
-import java.util.Map;
-
/**
* @author Frederik Heremans
*/
Project standards are to include all java packages first as was originally done in this file.
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
/**
* @author Frederik Heremans
*/ |
codereview_java_data_1498 | }
private Set<EnodeURL> loadStaticNodes() throws IOException {
- final String STATIC_NODES_FILENAME = "static-nodes.json";
- final Path staticNodesPath = dataDir().resolve(STATIC_NODES_FILENAME);
return StaticNodesParser.fromPath(staticNodesPath);
}
can this be made a constant
}
private Set<EnodeURL> loadStaticNodes() throws IOException {
+ final String staticNodesFilname = "static-nodes.json";
+ final Path staticNodesPath = dataDir().resolve(staticNodesFilname);
return StaticNodesParser.fromPath(staticNodesPath);
} |
codereview_java_data_1499 | */
@Override
public Value getTopValue() {
- String value =
- Integer.toString(yieldNexts.get()) + ',' + yieldSeeks.get() + ',' + rebuilds.get();
return new Value(value);
}
```suggestion yieldNexts.get() + "," + yieldSeeks.get() + "," + rebuilds.get(); ``` Could do this if we wanted to avoid using the first `Integer.toString` as well. Either way, LGTM.
*/
@Override
public Value getTopValue() {
+ String value = yieldNexts.get() + "," + yieldSeeks.get() + "," + rebuilds.get();
return new Value(value);
} |
codereview_java_data_1513 | public boolean has(Part part) {
return annotations.containsKey(part);
}
-
- public Part findKeyForAnnotationWithReplacementPart(Part part) {
- for (HashMap.Entry<Part, CryptoResultAnnotation> entry : annotations.entrySet()) {
- if (part == entry.getValue().getReplacementData()) {
- return entry.getKey();
- }
- }
- return null;
- }
}
this would be such a nice one-liner with kotlin ;-)
public boolean has(Part part) {
return annotations.containsKey(part);
}
} |
codereview_java_data_1527 | */
public static final int DOMAIN_NOT_FOUND_1 = 90120;
/**
* The error with code <code>90121</code> is thrown when
* a database operation is started while the virtual machine exits
when changing existing entries in this class, please provide backwards compat constants with the old names that point to the new names (and are marked deprecated), since this file is part of stable API
*/
public static final int DOMAIN_NOT_FOUND_1 = 90120;
+ /**
+ * Deprecated since 1.4.198. Use {@link #DOMAIN_NOT_FOUND_1} instead.
+ */
+ @Deprecated
+ public static final int USER_DATA_TYPE_NOT_FOUND_1 = DOMAIN_NOT_FOUND_1;
+
/**
* The error with code <code>90121</code> is thrown when
* a database operation is started while the virtual machine exits |
codereview_java_data_1530 | Job job = jet.newJob(pipeline);
assertJobStatusEventually(job, RUNNING);
- // and connection is cut
MILLISECONDS.sleep(ThreadLocalRandom.current().nextInt(0, 500));
proxy.setConnectionCut(true);
// and some time passes
All tests in this class are NightlyTest. Can we move this category to class level to have it more clear?
Job job = jet.newJob(pipeline);
assertJobStatusEventually(job, RUNNING);
+ // and snapshotting is ongoing (we have no exact way of identifying
+ // the moment, but random sleep will catch it at least some of the time)
MILLISECONDS.sleep(ThreadLocalRandom.current().nextInt(0, 500));
+
+ // and connection is cut
proxy.setConnectionCut(true);
// and some time passes |
codereview_java_data_1532 | editText.setHint(text);
editText.setId(position);
editText.setKeyListener(keyListener);
editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
editText.setSingleLine();
editText.setPadding(dpsToPixels(10), 0, dpsToPixels(10), 0);
I guess we won't be able to move to the next nutrition facts field using the soft key if we add this to each extra nutrient we add.
editText.setHint(text);
editText.setId(position);
editText.setKeyListener(keyListener);
+ lastEditText.setNextFocusDownId(editText.getId());
+ lastEditText.setImeOptions(EditorInfo.IME_ACTION_NEXT);
+ lastEditText = editText;
editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
editText.setSingleLine();
editText.setPadding(dpsToPixels(10), 0, dpsToPixels(10), 0); |
codereview_java_data_1545 | if (hash) {
String encodedKey = "";
try {
- byte[] encodedBytes = MessageDigest.getInstance(Constants.NON_CRYPTO_USE_HASH_ALGORITHM)
.digest(entry.getKey().getBytes(UTF_8));
encodedKey = new String(encodedBytes, UTF_8);
} catch (NoSuchAlgorithmException e) {
- out.println("Failed to convert key to " + Constants.NON_CRYPTO_USE_HASH_ALGORITHM
- + " hash: " + e.getMessage());
}
out.printf("%-20s", encodedKey.substring(0, 8));
} else
Since this use of the digest is specific to this specific metric utility's serialization, we can probably just use a local constant, rather than one in `Constants.java` (which I'd personally like to phase out over time).
if (hash) {
String encodedKey = "";
try {
+ byte[] encodedBytes = MessageDigest.getInstance(KEY_HASH_ALGORITHM)
.digest(entry.getKey().getBytes(UTF_8));
encodedKey = new String(encodedBytes, UTF_8);
} catch (NoSuchAlgorithmException e) {
+ out.println(
+ "Failed to convert key to " + KEY_HASH_ALGORITHM + " hash: " + e.getMessage());
}
out.printf("%-20s", encodedKey.substring(0, 8));
} else |
codereview_java_data_1546 | sessionManager.forceLogin(context);
return;
}
- contribution.setCreator(sessionManager.getRawUserName());
}
if (contribution.getDescription() == null) {
IMO it would be more appropriate to use something called `getAuthorName`. `getAuthorName` would return raw username if the value is set for `KEY_RAWUSERNAME` or else it will return `username`. This would handle the `null` issue that @neslihanturan faced. - Having I believe it would be better than the author name getting set as null. - We cannot ask the users to log out and log in to fix this issue. Ideally, the issue will fix automatically when the next time account is created.
sessionManager.forceLogin(context);
return;
}
+ contribution.setCreator(sessionManager.getAuthorName());
}
if (contribution.getDescription() == null) { |
codereview_java_data_1553 | // We only need to check the validity of recent chunks for calling sync()
// after writeStoreHeader() in the method storeNow().
// @since 2019-08-09 little-pan
- final Chunk[] lastCandidates = new Chunk[SYNC_MAX_DIFF + 2/* last + new chunk(maybe write header failed)*/];
// find out which chunk and version are the newest, and as the last chunk
// Step-1: read the newest chunk from the first two blocks(file header)
Please do not use "final" to qualify method variables, contrary to the style of this code base, unless it is used in anonymous inner class. This does not contribute much to code readability.
// We only need to check the validity of recent chunks for calling sync()
// after writeStoreHeader() in the method storeNow().
// @since 2019-08-09 little-pan
+ Chunk[] lastCandidates = new Chunk[SYNC_MAX_DIFF + 2/* last + new chunk(maybe write header failed)*/];
// find out which chunk and version are the newest, and as the last chunk
// Step-1: read the newest chunk from the first two blocks(file header) |
codereview_java_data_1555 | if (StringUtils.isBlank(type)) {
// simple judgment of file type based on suffix
if (configInfo.getDataId().contains(SPOT)) {
- String extName = configInfo.getDataId().substring(configInfo.getDataId().lastIndexOf(SPOT) + 1).toLowerCase();
try {
type = FileTypeEnum.valueOf(extName).getFileType();
} catch (Exception ex) {
extName toLowerCase() toUpperCase() ,BUG
if (StringUtils.isBlank(type)) {
// simple judgment of file type based on suffix
if (configInfo.getDataId().contains(SPOT)) {
+ String extName = configInfo.getDataId().substring(configInfo.getDataId().lastIndexOf(SPOT) + 1).toUpperCase();
try {
type = FileTypeEnum.valueOf(extName).getFileType();
} catch (Exception ex) { |
codereview_java_data_1556 | final Callback<ForgotPasswordResult> callback) {
final InternalCallback internalCallback = new InternalCallback<ForgotPasswordResult>(callback);
- internalCallback.async(_forgotPassword(username, internalCallback, null));
}
/**
Do we actually need clientMetadata for forgotPassword?
final Callback<ForgotPasswordResult> callback) {
final InternalCallback internalCallback = new InternalCallback<ForgotPasswordResult>(callback);
+ internalCallback.async(_forgotPassword(username, internalCallback,
+ Collections.<String, String>emptyMap()));
}
/** |
codereview_java_data_1560 | MockPacketDataFactory.mockNeighborsPacket(discoPeer, otherPeer, otherPeer2);
controller.onMessage(neighborsPacket, discoPeer);
- verify(controller, times(0)).bond(eq(otherPeer));
- verify(controller, times(1)).bond(eq(otherPeer2));
}
@Test
nit: I don't think we need the `eq` here. The default is equals comparison so you typically only use `eq` if you need to use other matchers for some params (because all params must use matchers if any do).
MockPacketDataFactory.mockNeighborsPacket(discoPeer, otherPeer, otherPeer2);
controller.onMessage(neighborsPacket, discoPeer);
+ verify(controller, times(0)).bond(otherPeer);
+ verify(controller, times(1)).bond(otherPeer2);
}
@Test |
codereview_java_data_1562 | }
public R startsWith(BoundReference<String> ref, Literal<String> lit) {
- return null;
}
public <T> R predicate(BoundPredicate<T> pred) {
I think this should throw an `UnsupportedOperationException`. The problem is that the all of the visitors were written without this method and we need to ensure that either they support `startsWith` or fail when it is encountered. In fact, the other methods probably should too, but that doesn't need to be done in this PR.
}
public R startsWith(BoundReference<String> ref, Literal<String> lit) {
+ throw new UnsupportedOperationException("Unsupported operation.");
}
public <T> R predicate(BoundPredicate<T> pred) { |
codereview_java_data_1563 | }
});
}
- if (LOG.isTraceEnabled()) {
- LOG.trace("Children nodes: {}", validChildren.size());
- validChildren.forEach(c -> LOG.trace("- {}", c));
- }
return validChildren;
}
This could also be simplified: ```suggestion LOG.trace("Children nodes (size: {}): {}", validChildren.size(), validChildren); ```
}
});
}
+ LOG.trace("Children nodes (size: {}): {}", validChildren.size(), validChildren);
return validChildren;
} |
codereview_java_data_1564 | package org.flowable.cmmn.test.runtime;
import static org.assertj.core.api.Assertions.assertThat;
@mkiener this file needs the license header added. Thanks.
+/* 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
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
package org.flowable.cmmn.test.runtime;
import static org.assertj.core.api.Assertions.assertThat; |
codereview_java_data_1573 | */
public interface ScanExecutor {
- public interface Config {
/**
* @return the unique name used to identified executor in config
*/
public is redundant
*/
public interface ScanExecutor {
+ interface Config {
/**
* @return the unique name used to identified executor in config
*/ |
codereview_java_data_1598 | return "(" + _1 + ", " + _2 + ")";
}
- public static <T1, T2> Tuple2<Seq<T1>, Seq<T2>> sequence(Seq<Tuple2<T1, T2>> tuples) {
Objects.requireNonNull(tuples, "tuples is null");
- return new Tuple2<>(tuples.map(Tuple2::_1), tuples.map(Tuple2::_2));
}
}
\ No newline at end of file
Great idea! Please let's tweak the parameter types a bit: ``` java public static <T1, T2> Tuple2<Seq<T1>, Seq<T2>> sequence(Iterable<Tuple2<? extends T1, ? extends T2>> tuples) ``` _(Note: I did not suggest `Iterable<? extends Tuple...` because Tuples are final.)_
return "(" + _1 + ", " + _2 + ")";
}
+ public static <T1, T2> Tuple2<List<? extends T1>, List<? extends T2>> sequence(Iterable<Tuple2<? extends T1, ? extends T2>> tuples) {
Objects.requireNonNull(tuples, "tuples is null");
+ return new Tuple2<>(Iterator.ofAll(tuples).map(Tuple2::_1).toList(), Iterator.ofAll(tuples).map(Tuple2::_2).toList());
}
}
\ No newline at end of file |
codereview_java_data_1607 | package org.apache.rocketmq.broker.grpc.adapter;
import io.grpc.stub.ServerCallStreamObserver;
public class InvocationContext<R, W> {
final private R request;
Should this constant value should be configurable?
package org.apache.rocketmq.broker.grpc.adapter;
import io.grpc.stub.ServerCallStreamObserver;
+import java.util.concurrent.TimeUnit;
public class InvocationContext<R, W> {
final private R request; |
codereview_java_data_1612 | nodeMetaModel.getTypeNameGenerified(),
nodeMetaModel.getTypeNameGenerified()
));
- this.addOrReplaceWhenSameSignature(nodeCoid, cloneMethod);
}
}
Whyyyy so many explicit this's? :-(
nodeMetaModel.getTypeNameGenerified(),
nodeMetaModel.getTypeNameGenerified()
));
+ addOrReplaceWhenSameSignature(nodeCoid, cloneMethod);
}
} |
codereview_java_data_1619 | return tokenSignature;
}
- public String getCustomAuthorizerName() {
return customAuthorizerName;
}
- public String getCustomAuthorizerLamdbaArn() {
return customAuthorizerLambdaArn;
}
Sorry, dumb question maybe, is this visibility difference intentional?
return tokenSignature;
}
+ String getCustomAuthorizerName() {
return customAuthorizerName;
}
+ String getCustomAuthorizerLamdbaArn() {
return customAuthorizerLambdaArn;
} |
codereview_java_data_1634 | import fr.free.nrw.commons.location.LatLng;
public class Converters {
@TypeConverter
public static Date fromTimestamp(Long value) {
return value == null ? null : new Date(value);
``` /** * Gson objects are very heavy. The app should ideally be using just one instance of it instead of creating new instances everywhere. * @return returns a singleton Gson instance */ @Provides @Singleton public Gson provideGson() { return GsonUtil.getDefaultGson(); } ``` It would be handy if we could not create `Gson`s here though I don't know how this class is instantiated by room
import fr.free.nrw.commons.location.LatLng;
public class Converters {
+ private static Gson gson;
+ public static Gson getGson(){
+ if(null==gson){
+ gson=new Gson();
+ }
+ return gson;
+ }
@TypeConverter
public static Date fromTimestamp(Long value) {
return value == null ? null : new Date(value); |
codereview_java_data_1636 | return new GetClusterMetadataOperation();
case GET_JOB_METRICS_OP:
return new GetJobMetricsOperation();
- case GET_JOB_METRICS_FROM_MEMBER_OP:
- return new GetJobMetricsFromMemberOperation();
default:
throw new IllegalArgumentException("Unknown type id " + typeId);
}
GetLocalJobMetrics would be better name
return new GetClusterMetadataOperation();
case GET_JOB_METRICS_OP:
return new GetJobMetricsOperation();
+ case GET_LOCAL_JOB_METRICS_OP:
+ return new GetLocalJobMetricsOperation();
default:
throw new IllegalArgumentException("Unknown type id " + typeId);
} |
codereview_java_data_1645 | private final BiConsumer<? super A, ? super T> accumulateF;
private final Function<A, R> finishAccumulationF;
private final BinaryOperator<A> combineAccF;
- private final FlatMapper<Punctuation, Session<K, R>> expiredSesFlatmapper;
SessionWindowP(
long sessionTimeout,
expiredSessionTraverser would be better name. Had to guess what "ses" means
private final BiConsumer<? super A, ? super T> accumulateF;
private final Function<A, R> finishAccumulationF;
private final BinaryOperator<A> combineAccF;
+ private final FlatMapper<Punctuation, Session<K, R>> expiredSessionFlatmapper;
SessionWindowP(
long sessionTimeout, |
codereview_java_data_1650 | * Returns a sink constructed directly from the given Core API processor
* meta-supplier.
* <p>
- * Default local parallelism for this source is specified by the given
* {@link ProcessorMetaSupplier#preferredLocalParallelism() metaSupplier}.
*
* @param sinkName user-friendly sink name
Should be "The default..."
* Returns a sink constructed directly from the given Core API processor
* meta-supplier.
* <p>
+ * The default local parallelism for this source is specified by the given
* {@link ProcessorMetaSupplier#preferredLocalParallelism() metaSupplier}.
*
* @param sinkName user-friendly sink name |
codereview_java_data_1651 | */
@Override
public Single<List<Label>> getLabels(Boolean refresh) {
- Long lastModifiedDate = UpdateSinceLastUpload("labels");
- if (lastModifiedDate > 1) {
// if (refresh || tableIsEmpty(labelDao)) {
return productApi.getLabels()
.map(LabelsWrapper::map)
Ideally: replace Long by a simple class containing an Enum ( ERROR, UPTODATE, TO_DOWNLOAD and SKIPPED) and the timestamp. It's more explicit
*/
@Override
public Single<List<Label>> getLabels(Boolean refresh) {
+ Long lastModifiedDate = updateSinceLastUpload("labels");
+ if (lastModifiedDate > TAXONOMY_UP_TO_DATE) {
// if (refresh || tableIsEmpty(labelDao)) {
return productApi.getLabels()
.map(LabelsWrapper::map) |
codereview_java_data_1659 | package org.apache.rocketmq.remoting.netty;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider;
what about using try-with-resources to deal with resource auto close
package org.apache.rocketmq.remoting.netty;
import io.netty.handler.ssl.ClientAuth;
+import io.netty.handler.ssl.OpenSsl;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider; |
codereview_java_data_1678 | @Override
public void init() {
if (serializationService.getManagedContext() != null) {
- Processor toInit = processor;
- if (processor instanceof ProcessorWrapper) {
- toInit = ((ProcessorWrapper) processor).getWrapped();
- }
Object initialized = serializationService.getManagedContext().initialize(toInit);
assert initialized == toInit : "different object returned";
}
can be replaced with `? :` expression
@Override
public void init() {
if (serializationService.getManagedContext() != null) {
+ Processor toInit = processor instanceof ProcessorWrapper
+ ? ((ProcessorWrapper) processor).getWrapped() : processor;
Object initialized = serializationService.getManagedContext().initialize(toInit);
assert initialized == toInit : "different object returned";
} |
codereview_java_data_1681 | public static boolean isMultiStatement(String sql) {
- final int index = sql.indexOf(';');
- return index != -1 && index != sql.length() - 1;
}
// INSERT' ' | INSTALL ' '
whether to consider value of insert has ';'
public static boolean isMultiStatement(String sql) {
+ int index = ParseUtil.findNextBreak(sql);
+ return index + 1 < sql.length() && !ParseUtil.isEOF(sql, index);
}
// INSERT' ' | INSTALL ' ' |
codereview_java_data_1685 | + " tserver.walog.max.size >= this property."),
TSERV_MEM_MGMT("tserver.memory.manager", "org.apache.accumulo.server.tabletserver.LargestFirstMemoryManager", PropertyType.CLASSNAME,
"An implementation of MemoryManger that accumulo will use."),
- TSERV_SESSION_MAXIDLE("tserver.session.idle.max", "1m", PropertyType.TIMEDURATION, "maximum idle time for a session"),
- TSERV_UPDATE_SESSION_MAXIDLE("tserver.session.update.idle.max", "1m", PropertyType.TIMEDURATION, "maximum idle time for an update session"),
TSERV_READ_AHEAD_MAXCONCURRENT("tserver.readahead.concurrent.max", "16", PropertyType.COUNT,
"The maximum number of concurrent read ahead that will execute. This effectively"
+ " limits the number of long running scans that can run concurrently per tserver."),
Could you make the new property description a complete sentence, please?
+ " tserver.walog.max.size >= this property."),
TSERV_MEM_MGMT("tserver.memory.manager", "org.apache.accumulo.server.tabletserver.LargestFirstMemoryManager", PropertyType.CLASSNAME,
"An implementation of MemoryManger that accumulo will use."),
+ TSERV_SESSION_MAXIDLE("tserver.session.idle.max", "1m", PropertyType.TIMEDURATION, "When a tablet server's SimpleTimer thread triggers to check "
+ + "idle sessions, this configurable option will be used to evaluate scan sessions to determine if they can be closed due to inactivity"),
+ TSERV_UPDATE_SESSION_MAXIDLE("tserver.session.update.idle.max", "1m", PropertyType.TIMEDURATION,
+ "When a tablet server's SimpleTimer thread triggers to check "
+ + "idle sessions, this configurable option will be used to evaluate update sessions to determine if they can be closed due to inactivity"),
TSERV_READ_AHEAD_MAXCONCURRENT("tserver.readahead.concurrent.max", "16", PropertyType.COUNT,
"The maximum number of concurrent read ahead that will execute. This effectively"
+ " limits the number of long running scans that can run concurrently per tserver."), |
codereview_java_data_1695 | public void setCurrentGroupExprData(Expression expr, Object obj) {
Integer index = exprToIndexInGroupByData.get(expr);
if (index != null) {
- if (currentGroupByExprData[index] != null) {
- throw DbException.throwInternalError();
- }
currentGroupByExprData[index] = obj;
return;
}
Looks like `assert` should be used instead. All existing callers of this method ensure that current value is `null` by theirself.
public void setCurrentGroupExprData(Expression expr, Object obj) {
Integer index = exprToIndexInGroupByData.get(expr);
if (index != null) {
+ assert currentGroupByExprData[index] != null;
currentGroupByExprData[index] = obj;
return;
} |
codereview_java_data_1700 | }
/**
- * Set the job ID.
*/
public TestProcessorMetaSupplierContext setJobId(long jobId) {
this.jobId = jobId;
It should say "_Sets_ the job ID." Likewise in the methods below.
}
/**
+ * Sets the job ID.
*/
public TestProcessorMetaSupplierContext setJobId(long jobId) {
this.jobId = jobId; |
codereview_java_data_1704 | }
private SearchRow getSearchRow(SearchRow row, int columnId, Value v, boolean max) {
- Column column = columnId == SearchRow.ROWID_INDEX ?
- table.getRowIdColumn() :
- table.getColumn(columnId);
- int vType = v.getType();
- int resType = Value.getHigherOrder(column.getType(), vType);
- if(vType != resType) {
- v = column.convert(v, session.getDatabase().getMode());
- }
if (row == null) {
row = table.getTemplateRow();
} else {
this new chunk of logic seems like it need some explanation beyond "replace magic constant" ? is it fixing a bug?
}
private SearchRow getSearchRow(SearchRow row, int columnId, Value v, boolean max) {
if (row == null) {
row = table.getTemplateRow();
} else { |
codereview_java_data_1707 | "\r\n" +
"dGhpcyBpcyBzb21lIG1vcmUgdGVzdCB0ZXh0Lg==\r\n"));
- checkAddresses(msg.getFrom(), "adam@example.org");
- checkAddresses(msg.getRecipients(RecipientType.TO), "eva@example.org");
- streamToString(MimeUtility.decodeBody(msg.getBody()));
}
@Test
These two checks seem unrelated to the actual check you want to perform.
"\r\n" +
"dGhpcyBpcyBzb21lIG1vcmUgdGVzdCB0ZXh0Lg==\r\n"));
+ MimeUtility.decodeBody(msg.getBody());
}
@Test |
codereview_java_data_1711 | }
public static String getSpcifyDelayOffsetStorePath(final String rootDir) {
- return rootDir + File.separator + "dragon" + File.separator + "delayOffset.json";
}
public static String getTranStateTableStorePath(final String rootDir) {
"dragon" here is a little confusing.
}
public static String getSpcifyDelayOffsetStorePath(final String rootDir) {
+ return rootDir + File.separator + "config" + File.separator + "customDelayOffset.json";
}
public static String getTranStateTableStorePath(final String rootDir) { |
codereview_java_data_1713 | * Returns a handler for manipulating the metric with the specified name.
*/
public static Metric metric(String name) {
- return MetricsImpl.metric(name, Unit.COUNT, false);
}
/**
I 'd rather have this as a separate method, than a flag. i.e. `Metric.threadSafeMetric()`
* Returns a handler for manipulating the metric with the specified name.
*/
public static Metric metric(String name) {
+ return MetricsImpl.metric(name, Unit.COUNT);
}
/** |
codereview_java_data_1719 | this.valueDeserializer = valueDeserializer;
}
- public static StoredNodeFactory<BytesValue> create() {
- return new StoredNodeFactory<>(
- (h) -> Optional.empty(), Function.identity(), Function.identity());
- }
-
@Override
public Node<V> createExtension(final BytesValue path, final Node<V> child) {
return handleNewNode(new ExtensionNode<>(path, child, this));
This seems fairly misleading - it doesn't really create a very useful `StoredNodeFactory`. Looks like we really just wanted to split out the decoding functionality to be separate from the retrieve and create functionality.
this.valueDeserializer = valueDeserializer;
}
@Override
public Node<V> createExtension(final BytesValue path, final Node<V> child) {
return handleNewNode(new ExtensionNode<>(path, child, this)); |
codereview_java_data_1724 | private static final String HIVE_ACQUIRE_LOCK_TIMEOUT_MS = "iceberg.hive.lock-timeout-ms";
private static final String HIVE_LOCK_CHECK_MIN_WAIT_MS = "iceberg.hive.lock-check-min-wait-ms";
private static final String HIVE_LOCK_CHECK_MAX_WAIT_MS = "iceberg.hive.lock-check-max-wait-ms";
- private static final String HIVE_TABLE_LEVEL_LOCK_EVICT_MS = "iceberg.hive.table-level-lock-evict-ms";
private static final String HIVE_ICEBERG_METADATA_REFRESH_MAX_RETRIES = "iceberg.hive.metadata-refresh-max-retries";
private static final long HIVE_ACQUIRE_LOCK_TIMEOUT_MS_DEFAULT = 3 * 60 * 1000; // 3 minutes
private static final long HIVE_LOCK_CHECK_MIN_WAIT_MS_DEFAULT = 50; // 50 milliseconds
private static final long HIVE_LOCK_CHECK_MAX_WAIT_MS_DEFAULT = 5 * 1000; // 5 seconds
Nit / non-blocking: can you use a long here? Some people might want to go really hard and do LONG_MAX (though I sure hope not), and it would match the other configs around it. Up to you / not really a big deal.
private static final String HIVE_ACQUIRE_LOCK_TIMEOUT_MS = "iceberg.hive.lock-timeout-ms";
private static final String HIVE_LOCK_CHECK_MIN_WAIT_MS = "iceberg.hive.lock-check-min-wait-ms";
private static final String HIVE_LOCK_CHECK_MAX_WAIT_MS = "iceberg.hive.lock-check-max-wait-ms";
private static final String HIVE_ICEBERG_METADATA_REFRESH_MAX_RETRIES = "iceberg.hive.metadata-refresh-max-retries";
+ private static final String HIVE_TABLE_LEVEL_LOCK_EVICT_MS = "iceberg.hive.table-level-lock-evict-ms";
private static final long HIVE_ACQUIRE_LOCK_TIMEOUT_MS_DEFAULT = 3 * 60 * 1000; // 3 minutes
private static final long HIVE_LOCK_CHECK_MIN_WAIT_MS_DEFAULT = 50; // 50 milliseconds
private static final long HIVE_LOCK_CHECK_MAX_WAIT_MS_DEFAULT = 5 * 1000; // 5 seconds |
codereview_java_data_1726 | if (result.isPresent()) {
Result toReturn = result.get();
- LOG.fine(String.format("Detected dialect: %s", toReturn.dialect));
return toReturn;
}
can we leave this one as info? One has the ability to set java log levels... although it seemingly is too complicated for many users. But those that log issues this is pretty important information to see by default in the console when we potentially need to troubleshoot things.
if (result.isPresent()) {
Result toReturn = result.get();
+ LOG.info(String.format("Detected dialect: %s", toReturn.dialect));
return toReturn;
} |
codereview_java_data_1729 | protected void onDraw(Canvas canvas)
{
if (GRID_ENABLED) {
- DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
- int screenWidth = metrics.widthPixels;
- int screenHeight = metrics.heightPixels;
canvas.drawLine(2 * (screenWidth / 3), 0, 2 * (screenWidth / 3), screenHeight, paint);
canvas.drawLine((screenWidth / 3), 0, (screenWidth / 3), screenHeight, paint);
Use the functions already available in `Utils.java` for screen width and height.
protected void onDraw(Canvas canvas)
{
if (GRID_ENABLED) {
+ int screenWidth = Utils.getScreenWidth(getContext());
+ int screenHeight = Utils.getScreenHeight(getContext());
canvas.drawLine(2 * (screenWidth / 3), 0, 2 * (screenWidth / 3), screenHeight, paint);
canvas.drawLine((screenWidth / 3), 0, (screenWidth / 3), screenHeight, paint); |
codereview_java_data_1732 | jobRepository = new JobRepository(jetInstance);
jobExecutionService = new JobExecutionService(nodeEngine, taskletExecutionService, jobRepository);
jobCoordinationService = createJobCoordinationService();
- nodeEngine.getMetricsRegistry().registerDynamicMetricsProvider(jobCoordinationService);
MetricsService metricsService = nodeEngine.getService(MetricsService.SERVICE_NAME);
metricsService.registerPublisher(nodeEngine -> new JobMetricsPublisher(jobExecutionService,
can we group the registrations together(with jobExecutionService)
jobRepository = new JobRepository(jetInstance);
jobExecutionService = new JobExecutionService(nodeEngine, taskletExecutionService, jobRepository);
jobCoordinationService = createJobCoordinationService();
MetricsService metricsService = nodeEngine.getService(MetricsService.SERVICE_NAME);
metricsService.registerPublisher(nodeEngine -> new JobMetricsPublisher(jobExecutionService, |
codereview_java_data_1733 | private final Map<String, ClassLoaderEntry> dataEntries = new ConcurrentHashMap<>();
private final Map<String, ClassLoaderEntry> classEntries = new ConcurrentHashMap<>();
- public ResourceStore(Path rootDir, NodeEngineImpl nodeEngine) {
this.log = nodeEngine.getLogger(getClass());
this.storageDirectory = uncheckCall(() -> Files.createTempDirectory(rootDir, "hazelcast-jet-resources"));
}
preferable to use `NodeEngine` here.
private final Map<String, ClassLoaderEntry> dataEntries = new ConcurrentHashMap<>();
private final Map<String, ClassLoaderEntry> classEntries = new ConcurrentHashMap<>();
+ public ResourceStore(Path rootDir, NodeEngine nodeEngine) {
this.log = nodeEngine.getLogger(getClass());
this.storageDirectory = uncheckCall(() -> Files.createTempDirectory(rootDir, "hazelcast-jet-resources"));
} |
codereview_java_data_1735 | import org.apache.accumulo.core.file.blockfile.cache.CacheEntry.Weighbable;
import org.apache.accumulo.core.file.blockfile.cache.impl.ClassSize;
import org.apache.accumulo.core.file.blockfile.cache.impl.SizeConstants;
-import org.apache.accumulo.core.file.blockfile.impl.CachableBlockFile;
import org.apache.accumulo.core.file.rfile.MultiLevelIndex.IndexEntry;
public class BlockIndex implements Weighbable {
- public static BlockIndex getIndex(CachableBlockFile.CachedBlockRead cacheBlock,
- IndexEntry indexEntry) throws IOException {
BlockIndex blockIndex = cacheBlock.getIndex(BlockIndex::new);
if (blockIndex == null)
It would be nice to import CachedBlockRead
import org.apache.accumulo.core.file.blockfile.cache.CacheEntry.Weighbable;
import org.apache.accumulo.core.file.blockfile.cache.impl.ClassSize;
import org.apache.accumulo.core.file.blockfile.cache.impl.SizeConstants;
import org.apache.accumulo.core.file.rfile.MultiLevelIndex.IndexEntry;
public class BlockIndex implements Weighbable {
+ public static BlockIndex getIndex(CachedBlockRead cacheBlock, IndexEntry indexEntry)
+ throws IOException {
BlockIndex blockIndex = cacheBlock.getIndex(BlockIndex::new);
if (blockIndex == null) |
codereview_java_data_1738 | }
@Override
- public String getTimestamp(long tid) {
verifyReserved(tid);
try {
Consider returning an empty string (or N/A, or unavailable?) instead of throwing an exception? This is for information and continuing without this data point (especially if the exception was transient) may allow other operations to continue if they can. What is returned versus what is displayed may want to consider a user wanting to parse the output (say with awk or sort) along what is clear to a user.
}
@Override
+ public String timeTopCreated(long tid) {
verifyReserved(tid);
try { |
codereview_java_data_1742 | plugin.getInstance().checkPermissions(savedPermissionCall);
} else {
// handle permission requests by other methods on the plugin
- plugin.getInstance().onRequestPermissionsResult(savedPermissionCall, getPermissionStates(plugin.getInstance()));
if (!savedPermissionCall.isReleased() && !savedPermissionCall.isSaved()) {
savedPermissionCall.release(this);
Do we want to call the plugin instance version? ```suggestion plugin.getInstance().onRequestPermissionsResult(savedPermissionCall, plugin.getInstance().getPermissionStates()); ```
plugin.getInstance().checkPermissions(savedPermissionCall);
} else {
// handle permission requests by other methods on the plugin
+ plugin.getInstance().onRequestPermissionsResult(savedPermissionCall, plugin.getInstance().getPermissionStates());
if (!savedPermissionCall.isReleased() && !savedPermissionCall.isSaved()) {
savedPermissionCall.release(this); |
codereview_java_data_1757 | import net.pms.formats.Format;
import net.pms.formats.v2.SubtitleType;
import net.pms.image.ImageFormat;
-import net.pms.image.ImageInfo;
import net.pms.image.ImagesUtil;
import net.pms.image.ImagesUtil.ScaleType;
import net.pms.util.FileUtil;
This seems unused?
import net.pms.formats.Format;
import net.pms.formats.v2.SubtitleType;
import net.pms.image.ImageFormat;
import net.pms.image.ImagesUtil;
import net.pms.image.ImagesUtil.ScaleType;
import net.pms.util.FileUtil; |
codereview_java_data_1762 | public class Planner {
/**
- * Minimum frequency of watermarks. This is not technically necessary, but
- * improves debugging by avoiding too large gaps between WMs and the user
- * can better observe if input to WM coalescing is lagging.
*/
- private static final int MINIMUM_WATERMARK_RATE = 1_000;
public final DAG dag = new DAG();
public final Map<Transform, PlannerVertex> xform2vertex = new HashMap<>();
wouldn't it be better to call it `MAXIMUM_WATERMARK_GAP` or similar?
public class Planner {
/**
+ * Maximum gap between two consecutive watermarks. This is not technically
+ * necessary, but improves debugging by avoiding too large gaps between WMs
+ * and the user can better observe if input to WM coalescing is lagging.
*/
+ private static final int MAXIMUM_WATERMARK_GAP = 1_000;
public final DAG dag = new DAG();
public final Map<Transform, PlannerVertex> xform2vertex = new HashMap<>(); |
codereview_java_data_1765 | scope,
includeSystemVars);
} else {
- List<List<String>> customStarExpansion;
- if ((customStarExpansion = getCustomStarExpansion(p.right)) != null) {
for (List<String> names : customStarExpansion) {
SqlIdentifier exp = new SqlIdentifier(
Lists.asList(p.left, names.toArray(new String[names.size()])),
move assignment to previous line. make final?
scope,
includeSystemVars);
} else {
+ final List<List<String>> customStarExpansion =
+ getCustomStarExpansion(p.right);
+ if (customStarExpansion != null) {
for (List<String> names : customStarExpansion) {
SqlIdentifier exp = new SqlIdentifier(
Lists.asList(p.left, names.toArray(new String[names.size()])), |
codereview_java_data_1769 | // make sure the child is big enough
cv.child.ensureSize(cv.childCount, true);
// Add each element
- for (long e = 0; e < cv.lengths[rowId]; ++e) {
- children.addValue((int) (e + cv.offsets[rowId]), (int) e, value, cv.child);
}
}
}
This doesn't make sense to me. Should `cv.lengths` be an integer array instead of longs? It looks like they should always be integers since the values are assigned from `ArrayData#numElements()`. That's very likely an int.
// make sure the child is big enough
cv.child.ensureSize(cv.childCount, true);
// Add each element
+ for (int e = 0; e < cv.lengths[rowId]; ++e) {
+ children.addValue((int) (e + cv.offsets[rowId]), e, value, cv.child);
}
}
} |
codereview_java_data_1770 | JID searchJID = new JID(originatingResource.getNode(), originatingResource.getDomain(), null);
List<JID> addresses = routingTable.getRoutes(searchJID, null);
for (JID address : addresses) {
- if (originatingResource != address) {
// Send the presence of the session whose presence has changed to
// this user's other session(s)
presence.setTo(address);
Here should use equals?
JID searchJID = new JID(originatingResource.getNode(), originatingResource.getDomain(), null);
List<JID> addresses = routingTable.getRoutes(searchJID, null);
for (JID address : addresses) {
+ if (!originatingResource.equals(address)) {
// Send the presence of the session whose presence has changed to
// this user's other session(s)
presence.setTo(address); |
codereview_java_data_1775 | *
*/
@Nonnull
- public static StreamSource<Long> longStreamSource(long itemsPerSecond, long initialDelay) {
- return longStreamSource(itemsPerSecond, initialDelay, Vertex.LOCAL_PARALLELISM_USE_DEFAULT, false);
}
/**
Wrap the params like this: ```java public static StreamSource<Long> longStreamSource( long itemsPerSecond, long initialDelay, int preferredLocalParallelism ) { ```
*
*/
@Nonnull
+ public static StreamSource<Long> streamSourceLong(long itemsPerSecond, long initialDelay) {
+ return streamSourceLong(itemsPerSecond, initialDelay, Vertex.LOCAL_PARALLELISM_USE_DEFAULT, false);
}
/** |
codereview_java_data_1776 | tabletMutator.putLocation(assignment.server, LocationType.LAST);
tabletMutator.deleteLocation(assignment.server, LocationType.FUTURE);
- //remove the old location
if (prevLastLoc != null && !prevLastLoc.equals(assignment.server)) {
tabletMutator.deleteLocation(prevLastLoc, LocationType.LAST);
}
If some of the methods in Assignment are no longer used it would be nice to remove them
tabletMutator.putLocation(assignment.server, LocationType.LAST);
tabletMutator.deleteLocation(assignment.server, LocationType.FUTURE);
+ // remove the old location
if (prevLastLoc != null && !prevLastLoc.equals(assignment.server)) {
tabletMutator.deleteLocation(prevLastLoc, LocationType.LAST);
} |
codereview_java_data_1780 | JSONObject result = new JSONObject();
// For old DNS-F client:
String dnsfVersion = "1.0.1";
- String agent = request.getHeader(HttpHeaderConsts.USER_AGENT_HEADER);
ClientInfo clientInfo = new ClientInfo(agent);
if (clientInfo.type == ClientInfo.ClientType.DNS &&
clientInfo.version.compareTo(VersionUtil.parseVersion(dnsfVersion)) <= 0) {
Or keep the original logic, is proposed, compatible with the old client
JSONObject result = new JSONObject();
// For old DNS-F client:
String dnsfVersion = "1.0.1";
+ String agent = WebUtils.getUserAgent(request);
ClientInfo clientInfo = new ClientInfo(agent);
if (clientInfo.type == ClientInfo.ClientType.DNS &&
clientInfo.version.compareTo(VersionUtil.parseVersion(dnsfVersion)) <= 0) { |
codereview_java_data_1784 | import org.gradle.util.GFileUtils;
@CacheableTask
-@SuppressWarnings("VisibilityModifier")
public class ClassUniquenessLockTask extends DefaultTask {
// not marking this as an Input, because we want to re-run if the *contents* of a configuration changes
- private final File lockFile;
public final SetProperty<String> configurations;
public ClassUniquenessLockTask() {
this.configurations = getProject().getObjects().setProperty(String.class);
this.lockFile = getProject().file("baseline-class-uniqueness.lock");
I think we may want to provide a different message if new duplicates appear vs when problems are fixed, or mention here that it's dangerous to have duplicate classes on the classpath and explain why it's worth spending time to fix. Otherwise I think folks will see "run X to update locks" and they'll `./X`.
import org.gradle.util.GFileUtils;
@CacheableTask
public class ClassUniquenessLockTask extends DefaultTask {
// not marking this as an Input, because we want to re-run if the *contents* of a configuration changes
+ @SuppressWarnings("VisibilityModifier")
public final SetProperty<String> configurations;
+ private final File lockFile;
+
public ClassUniquenessLockTask() {
this.configurations = getProject().getObjects().setProperty(String.class);
this.lockFile = getProject().file("baseline-class-uniqueness.lock"); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.