id
stringlengths
23
26
content
stringlengths
182
2.49k
codereview_java_data_10605
: config.getProfile(profileName); } if (this.statement.getNode() != null) { - this.queryPlan = new ConcurrentLinkedQueue<Node>(); - this.queryPlan.add(this.statement.getNode()); } else { this.queryPlan = Since JAVA-1883 there is a dedicated queue implementation for query plans, we can also use it here: ```java this.queryPlan = new QueryPlan(this.statement.getNode()); ``` : config.getProfile(profileName); } if (this.statement.getNode() != null) { + this.queryPlan = new QueryPlan(this.statement.getNode()); } else { this.queryPlan =
codereview_java_data_10609
* @since 5.5 */ public void setCookieMaxAge(int cookieMaxAge) { - Assert.isTrue(cookieMaxAge != 0, "cookieMaxAge is not zero"); this.cookieMaxAge = cookieMaxAge; } Can you please change this to be cookieMaxAge cannot be zero? As it is, the error the user will see if it is `0` would state it is not zero which would be confusing. ```suggestion Assert.isTrue(cookieMaxAge != 0, "cookieMaxAge cannot be zero"); ``` * @since 5.5 */ public void setCookieMaxAge(int cookieMaxAge) { + Assert.isTrue(cookieMaxAge != 0, "cookieMaxAge cannot be zero"); this.cookieMaxAge = cookieMaxAge; }
codereview_java_data_10617
@Override public double computeFor(ASTMethodOrConstructorDeclaration node, MetricVersion version) { - JavaParserVisitor visitor = (CycloVersion.IGNORE_BOOLEAN_PATHS.equals(version)) ? new CycloPathUnawareOperationVisitor() : new StandardCycloVisitor(); Since the version is a enum, we can compare here using `==` directly. @Override public double computeFor(ASTMethodOrConstructorDeclaration node, MetricVersion version) { + JavaParserVisitor visitor = (CycloVersion.IGNORE_BOOLEAN_PATHS == version) ? new CycloPathUnawareOperationVisitor() : new StandardCycloVisitor();
codereview_java_data_10623
jet.newJob(p).join(); - assertTrueEventually(() -> { - try (S3Client client = clientSupplier().get()) { long lineCount = client .listObjects(req -> req.bucket(bucketName).prefix(prefix)) .contents() do we need to recreate the client each time? jet.newJob(p).join(); + try (S3Client client = clientSupplier().get()) { + assertTrueEventually(() -> { long lineCount = client .listObjects(req -> req.bucket(bucketName).prefix(prefix)) .contents()
codereview_java_data_10625
}); } - private void setWriteMode(String tabName, String mode) { sql("ALTER TABLE %s SET TBLPROPERTIES('%s' '%s')", tabName, TableProperties.WRITE_DISTRIBUTION_MODE, mode); } I think this should be `setDistributionMode` instead because `setWriteMode` sounds more general, like "copy-on-write" or "merge-on-read". }); } + private void setDistributionMode(String tabName, String mode) { sql("ALTER TABLE %s SET TBLPROPERTIES('%s' '%s')", tabName, TableProperties.WRITE_DISTRIBUTION_MODE, mode); }
codereview_java_data_10627
); } - @GET - @Path("/agent/max-decommissioning-count") - @Operation(summary = "Retrieve the max decommissioning agent count from configuration") - public int getMaxDecommissioningAgent() { - return super.getMaxDecommissioningAgents(); - } - @POST @Path("/agent/{agentId}/freeze") @Operation(summary = "Freeze tasks on a specific agent") This isn't really agent specific, and unfortunately doesn't fit neatly with any of our other resources either. Probably worth creating a separate "config" resource class to expose this. ); } @POST @Path("/agent/{agentId}/freeze") @Operation(summary = "Freeze tasks on a specific agent")
codereview_java_data_10640
requestResource.postRequest(request.toBuilder().setInstances(Optional.of(2)).build(), singularityUser); initFirstDeploy(); - configuration.setDeltaAfterWhichTasksAreLateMillis(TimeUnit.MILLISECONDS.toMillis(10)); requestResource.scheduleImmediately( singularityUser, shouldn't need MILLISECONDS.toMillis, can just use the number. Also, why not set to `0`? Outcome otherwise may be different depending on how fast the machine running the test is requestResource.postRequest(request.toBuilder().setInstances(Optional.of(2)).build(), singularityUser); initFirstDeploy(); + configuration.setDeltaAfterWhichTasksAreLateMillis(0); requestResource.scheduleImmediately( singularityUser,
codereview_java_data_10641
final Optional<Double> minimumPriorityLevel = getMinimumPriorityLevel(); final Map<Boolean, List<SingularityPendingTaskId>> lateTasksPartitionedByOnDemand = scheduledTasksInfo.getLateTasks().stream() - .collect(Collectors.partitioningBy(lateTask -> requestManager.getRequest(lateTask.getRequestId()).get().getRequest().getRequestType().equals(RequestType.ON_DEMAND))); final List<SingularityPendingTaskId> onDemandLateTasks = lateTasksPartitionedByOnDemand.get(true); final List<SingularityPendingTaskId> lateTasks = lateTasksPartitionedByOnDemand.get(false); We'll want to handle the case where a `getRequest()` comes back as an empty Optional here final Optional<Double> minimumPriorityLevel = getMinimumPriorityLevel(); final Map<Boolean, List<SingularityPendingTaskId>> lateTasksPartitionedByOnDemand = scheduledTasksInfo.getLateTasks().stream() + .collect(Collectors.partitioningBy(lateTask -> requestTypeIsOnDemand(lateTask)); final List<SingularityPendingTaskId> onDemandLateTasks = lateTasksPartitionedByOnDemand.get(true); final List<SingularityPendingTaskId> lateTasks = lateTasksPartitionedByOnDemand.get(false);
codereview_java_data_10645
import tech.pegasys.pantheon.util.ExceptionUtils; import java.time.Duration; -import java.util.List; import java.util.concurrent.CompletableFuture; import org.apache.logging.log4j.LogManager; Does it make sense to use the more generic `Collection` here? import tech.pegasys.pantheon.util.ExceptionUtils; import java.time.Duration; +import java.util.Collection; import java.util.concurrent.CompletableFuture; import org.apache.logging.log4j.LogManager;
codereview_java_data_10646
assertEquals("00000000-0000-4000-8000-000000000000", min.getString()); // Test conversion from ValueJavaObject to ValueUuid - ValueJavaObject valObj = ValueJavaObject.getNoCopy(UUID.fromString("12345678-1234-4321-8765-123456789012"), null, null); Value valUUID = valObj.convertTo(Value.UUID); assertTrue(valUUID instanceof ValueUuid); assertTrue((valUUID.getString().equals("12345678-1234-4321-8765-123456789012"))); ValueJavaObject vo_string = ValueJavaObject.getNoCopy(new String("This is not a ValueUuid object"), null, null); assertThrows(DbException.class, vo_string).convertTo(Value.UUID); Here it would be a good idea to add assertion that `valUUID.getObject().equals(originalUUID)` assertEquals("00000000-0000-4000-8000-000000000000", min.getString()); // Test conversion from ValueJavaObject to ValueUuid + UUID origUUID = UUID.fromString("12345678-1234-4321-8765-123456789012"); + ValueJavaObject valObj = ValueJavaObject.getNoCopy(origUUID, null, null); Value valUUID = valObj.convertTo(Value.UUID); assertTrue(valUUID instanceof ValueUuid); assertTrue((valUUID.getString().equals("12345678-1234-4321-8765-123456789012"))); + assertTrue(valUUID.getObject().equals(origUUID)); ValueJavaObject vo_string = ValueJavaObject.getNoCopy(new String("This is not a ValueUuid object"), null, null); assertThrows(DbException.class, vo_string).convertTo(Value.UUID);
codereview_java_data_10649
private static final Pattern PTN_INTERVAL = Pattern.compile( "interval" + SM + "(floor\\()([\\d\\.]+)(\\))" + SM + "(second|minute|hour|day|month|year)", Pattern.CASE_INSENSITIVE); - private static final Pattern PTN_HAVING_ESCAPE_FUNCTION = Pattern.compile("\\{fn" + SM + "(EXTRACT\\(.*?\\))" + "\\}", Pattern.CASE_INSENSITIVE); private static final Pattern PIN_SUM_OF_CAST = Pattern.compile(S0 + "SUM" + S0 + "\\(" + S0 + "CAST" + S0 + "\\(" + S0 + "([^\\s,]+)" + S0 + "AS" + SM + "DOUBLE" + S0 + "\\)" + S0 + "\\)", Pattern.CASE_INSENSITIVE); private static final Pattern PIN_SUM_OF_FN_CONVERT = Pattern .compile(S0 + "SUM" + S0 + "\\(" + S0 + "\\{\\s*fn" + SM + "convert" + S0 + "\\(" + S0 + "([^\\s,]+)" + S0 + "," + S0 + "SQL_DOUBLE" + S0 + "\\)" + S0 + "\\}" + S0 + "\\)", Pattern.CASE_INSENSITIVE); - private static final Pattern PTN_HAVING_FUNCTION = Pattern.compile("\\{fn" + "(.*?)" + "\\}", - Pattern.CASE_INSENSITIVE); @Override public String transform(String sql, String project, String defaultSchema) { It's too general as it matches all functions. How about adding a CURRENT_TIMESTAMP function like PTN_MIN_1 instead? private static final Pattern PTN_INTERVAL = Pattern.compile( "interval" + SM + "(floor\\()([\\d\\.]+)(\\))" + SM + "(second|minute|hour|day|month|year)", Pattern.CASE_INSENSITIVE); + private static final Pattern PTN_HAVING_ESCAPE_FUNCTION = Pattern.compile("\\{fn" + SM + "(EXTRACT\\(.*?\\)||CURRENT_TIMESTAMP\\(.*?\\))" + "\\}", Pattern.CASE_INSENSITIVE); private static final Pattern PIN_SUM_OF_CAST = Pattern.compile(S0 + "SUM" + S0 + "\\(" + S0 + "CAST" + S0 + "\\(" + S0 + "([^\\s,]+)" + S0 + "AS" + SM + "DOUBLE" + S0 + "\\)" + S0 + "\\)", Pattern.CASE_INSENSITIVE); private static final Pattern PIN_SUM_OF_FN_CONVERT = Pattern .compile(S0 + "SUM" + S0 + "\\(" + S0 + "\\{\\s*fn" + SM + "convert" + S0 + "\\(" + S0 + "([^\\s,]+)" + S0 + "," + S0 + "SQL_DOUBLE" + S0 + "\\)" + S0 + "\\}" + S0 + "\\)", Pattern.CASE_INSENSITIVE); @Override public String transform(String sql, String project, String defaultSchema) {
codereview_java_data_10656
if (!TextSecurePreferences.isNewContactsNotificationEnabled(context)) return; for (String newUser : newUsers) { - String e164number = ""; - try { - e164number = Util.canonicalizeNumber(context, newUser); - } catch (InvalidNumberException e) { - Log.w(TAG, e); - } - - if (!SessionUtil.hasSession(context, masterSecret, newUser) && - !TextSecurePreferences.getLocalNumber(context).equals(e164number)) { IncomingJoinedMessage message = new IncomingJoinedMessage(newUser); Pair<Long, Long> smsAndThreadId = DatabaseFactory.getSmsDatabase(context).insertMessageInbox(message); too ugly, put this in a helper if you must if (!TextSecurePreferences.isNewContactsNotificationEnabled(context)) return; for (String newUser : newUsers) { + if (!SessionUtil.hasSession(context, masterSecret, newUser) && !Util.isOwnNumber(context, newUser)) { IncomingJoinedMessage message = new IncomingJoinedMessage(newUser); Pair<Long, Long> smsAndThreadId = DatabaseFactory.getSmsDatabase(context).insertMessageInbox(message);
codereview_java_data_10661
double doublePrecisionDelta = 0.0001; if (index == 0 || (Math.abs(weights[index - 1] - 1) < doublePrecisionDelta)) { - throw new IllegalStateException( - "Cumulative Weight caculate wrong , the sum of probabilities does not equals 1."); } } @Override Seems it should be ```if (!(index == 0 || (Math.abs(weights[index - 1] - 1) < doublePrecisionDelta)))``` double doublePrecisionDelta = 0.0001; if (index == 0 || (Math.abs(weights[index - 1] - 1) < doublePrecisionDelta)) { + return; } + throw new IllegalStateException("Cumulative Weight caculate wrong , the sum of probabilities does not equals 1."); } @Override
codereview_java_data_10671
Matcher m = re.matcher(page); while (m.find()) { LOGGER.debug("found subtitle " + m.group(2) + " name " + m.group(1) + " zip " + m.group(3)); - res.put(m.group(2) + ":" + FileUtil.getFileNameWithoutExtension(m.group(1)), m.group(3)); if (res.size() > PMS.getConfiguration().openSubsLimit()) { // limit the number of hits somewhat break; How does this line work? It looks like it's a loop that doesn't do anything Matcher m = re.matcher(page); while (m.find()) { LOGGER.debug("found subtitle " + m.group(2) + " name " + m.group(1) + " zip " + m.group(3)); + res.put(m.group(2) + ":" + m.group(1), m.group(3)); if (res.size() > PMS.getConfiguration().openSubsLimit()) { // limit the number of hits somewhat break;
codereview_java_data_10673
long tmpTimeStamp = mappedFile.getStoreTimestamp(); int offset = mappedFile.flush(flushLeastPages); if (mappedFile.getflushError()) { - this.flushError =true; } long where = mappedFile.getFileFromOffset() + offset; result = where == this.flushedWhere; If we got error during flush, is it better not forwarding `flushedWhere` below.? long tmpTimeStamp = mappedFile.getStoreTimestamp(); int offset = mappedFile.flush(flushLeastPages); if (mappedFile.getflushError()) { + this.flushError = true; } long where = mappedFile.getFileFromOffset() + offset; result = where == this.flushedWhere;
codereview_java_data_10675
} } - @SuppressWarnings("unchecked") @Override public List<ReadOnlyRepo<T>> getStack(long tid) { String txpath = getTXPath(tid); Empty list instead of null? } } @Override public List<ReadOnlyRepo<T>> getStack(long tid) { String txpath = getTXPath(tid);
codereview_java_data_10677
* * The lists are encoded with the elements separated by null (0x0) bytes, which null bytes appearing * in the elements escaped as two 0x1 bytes, and 0x1 bytes appearing in the elements escaped as 0x1 - * and 0x2 bytes. The list is terminated with a final delimiter, with no bytes following it. * * @since 2.0.0 * @param <E> assertions may not be enabled (they typically aren't). Should use IllegalArgumentException instead; could use Guava's `Preconditions.checkArgument()`. * * The lists are encoded with the elements separated by null (0x0) bytes, which null bytes appearing * in the elements escaped as two 0x1 bytes, and 0x1 bytes appearing in the elements escaped as 0x1 + * and 0x2 bytes. The list is terminated with a final delimiter after the last element, with no + * bytes following it. An empty list is represented as an empty byte array, with no delimiter, + * whereas a list with a single empty element is represented as a single terminating delimiter. * * @since 2.0.0 * @param <E>
codereview_java_data_10687
} @Bean - @ConditionalOnMissingBean(RedisConnectionFactory.class) RedisConnectionFactory redisConnectionFactory(Cloud cloud) { return cloud.getSingletonServiceConnector(RedisConnectionFactory.class, null); } since this is now using `@AutoConfigureBefore`, does it still need the `@ConditionalOnMissingBean` as well? } @Bean RedisConnectionFactory redisConnectionFactory(Cloud cloud) { return cloud.getSingletonServiceConnector(RedisConnectionFactory.class, null); }
codereview_java_data_10693
package org.apache.calcite.test; -import org.apache.calcite.jdbc.JavaTypeFactoryImpl; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.logical.LogicalFilter; import org.apache.calcite.rel.logical.LogicalProject; -import org.apache.calcite.rel.type.RelDataType; -import org.apache.calcite.rel.type.RelDataTypeFactory; -import org.apache.calcite.rel.type.RelDataTypeSystem; import org.apache.calcite.rex.RexNode; import org.apache.calcite.test.verifier.RexToSymbolicColumn; import org.apache.calcite.test.verifier.SymbolicColumn; Please use `RexProgramTestBase` so you could reuse all the helpers for types, etc, etc. package org.apache.calcite.test; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.logical.LogicalFilter; import org.apache.calcite.rel.logical.LogicalProject; import org.apache.calcite.rex.RexNode; +import org.apache.calcite.rex.RexProgramBuilderBase; import org.apache.calcite.test.verifier.RexToSymbolicColumn; import org.apache.calcite.test.verifier.SymbolicColumn;
codereview_java_data_10700
* to 1.4.196 because 1.4.197 broke audio metadata being * inserted/updated * - 23: Store aspect ratios as strings again - * - 24: added MusicBrainzID to audio tracks */ - private final int latestVersion = 24; // Database column sizes private final int SIZE_CODECV = 32; Do you think it would be possible to do this without bumping the database version? I am hesitant to do that since it is quite an expensive operation to happen on people's machines. Maybe you can use the existing `MusicBrainzReleases` table and add a `AudioTrackID` column? * to 1.4.196 because 1.4.197 broke audio metadata being * inserted/updated * - 23: Store aspect ratios as strings again */ + private final int latestVersion = 23; // Database column sizes private final int SIZE_CODECV = 32;
codereview_java_data_10703
snapshotContext = new SnapshotContext(nodeEngine.getLogger(SnapshotContext.class), jobNameAndExecutionId(), plan.lastSnapshotId(), jobConfig.getProcessingGuarantee()); - serializationService = new JetSerializationService( - instantiateSerializers(currentThread().getContextClassLoader(), jobConfig.getSerializerConfigs()), - (AbstractSerializationService) nodeEngine.getSerializationService() - ); metricsEnabled = jobConfig.isMetricsEnabled() && nodeEngine.getConfig().getMetricsConfig().isEnabled(); plan.initialize(nodeEngine, jobId, executionId, snapshotContext, tempDirectories, serializationService); Maybe we can avoid this if there are no serializers configured. snapshotContext = new SnapshotContext(nodeEngine.getLogger(SnapshotContext.class), jobNameAndExecutionId(), plan.lastSnapshotId(), jobConfig.getProcessingGuarantee()); + serializationService = serializationService(nodeEngine, jobConfig); metricsEnabled = jobConfig.isMetricsEnabled() && nodeEngine.getConfig().getMetricsConfig().isEnabled(); plan.initialize(nodeEngine, jobId, executionId, snapshotContext, tempDirectories, serializationService);
codereview_java_data_10705
this.ldif = ldif; } - private void checkFilePath(String ldif) { - if (!StringUtils.hasText(ldif)) { - throw new IllegalArgumentException("Unable to load LDIF " + ldif); - } - } public int getPort() { return this.port; Setting the LDIF is optional, so we shouldn't throw an exception, instead we should just avoid processing the LDIF. this.ldif = ldif; } public int getPort() { return this.port;
codereview_java_data_10715
@Override public boolean equals(Object other) { if (other instanceof ImapFolder) { - - return other.hashCode() == hashCode() ; } return super.equals(other); This is wrong. We still need to use the folder name for equality checks. @Override public boolean equals(Object other) { if (other instanceof ImapFolder) { + ImapFolder otherFolder = (ImapFolder) other; + if (otherFolder.getName().equalsIgnoreCase("INBOX")) { + return otherFolder.getName().equalsIgnoreCase(getName()); + } + return otherFolder.getName().equals(getName()); } return super.equals(other);
codereview_java_data_10722
@Override public void connectionClose(final BackendConnection conn, final String reason) { final XACommitNodesHandler thisHandler = this; - Thread newThreadFor = new Thread(new Runnable() { @Override public void run() { thisHandler.connectionCloseLocal(conn, reason); } }); - newThreadFor.start(); } use thread pool @Override public void connectionClose(final BackendConnection conn, final String reason) { final XACommitNodesHandler thisHandler = this; + DbleServer.getInstance().getBusinessExecutor().execute(new Runnable() { @Override public void run() { thisHandler.connectionCloseLocal(conn, reason); } }); }
codereview_java_data_10731
TabletIteratorEnvironment iterEnv; if (env.getIteratorScope() == IteratorScope.majc) iterEnv = new TabletIteratorEnvironment(IteratorScope.majc, !propogateDeletes, acuTableConf, - MajorCompactionReason.values()[reason]); else if (env.getIteratorScope() == IteratorScope.minc) - iterEnv = new TabletIteratorEnvironment(IteratorScope.minc, acuTableConf, - MajorCompactionReason.values()[reason]); else throw new IllegalArgumentException(); Calling `getMajorCompactionReason()` here would be a bit cleaner. TabletIteratorEnvironment iterEnv; if (env.getIteratorScope() == IteratorScope.majc) iterEnv = new TabletIteratorEnvironment(IteratorScope.majc, !propogateDeletes, acuTableConf, + getMajorCompactionReason()); else if (env.getIteratorScope() == IteratorScope.minc) + iterEnv = new TabletIteratorEnvironment(IteratorScope.minc, acuTableConf); else throw new IllegalArgumentException();
codereview_java_data_10735
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: - navigateUp = true; - prepareToFinish(); break; case R.id.send: checkToSendMessage(); These two always go together. It might be cleaner to set the field inside `prepareToFinish()`. public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: + prepareToFinish(true); break; case R.id.send: checkToSendMessage();
codereview_java_data_10737
} validateIdentityLinkArguments(identityId, type); if (restApiInterceptor != null) { - restApiInterceptor.deleteProcessInstanceIdentityLink(processInstance, identityId, type); } - getIdentityLink(identityId, type, processInstance.getId()); - runtimeService.deleteUserIdentityLink(processInstance.getId(), identityId, type); response.setStatus(HttpStatus.NO_CONTENT.value()); Same story as for deleting a case instance identity link } validateIdentityLinkArguments(identityId, type); + + IdentityLink link = getIdentityLink(identityId, type, processInstance.getId()); + if (restApiInterceptor != null) { + restApiInterceptor.deleteProcessInstanceIdentityLink(processInstance, link); } runtimeService.deleteUserIdentityLink(processInstance.getId(), identityId, type); response.setStatus(HttpStatus.NO_CONTENT.value());
codereview_java_data_10740
if (loopIfNoConnection) { try { Thread.sleep(retryWait); - } catch (Exception e) { - // Ignored, the thread was interrupted while waiting, so no need to log either } } } while (loopIfNoConnection); You're catching an InterruptedException here, which really means you should re-interrupt the thread. Something like ``` try { Thread.sleep(retryWait); } catch (InterruptedException ex) { Log.info("Interrupted whilst waiting", e); Thread.currentThread().interrupt(); } ``` if (loopIfNoConnection) { try { Thread.sleep(retryWait); + } catch (InterruptedException ex) { + String msg = "Interrupted waiting for DB connection"; + Log.info(msg,ex); + Thread.currentThread().interrupt(); + throw new SQLException(msg,ex); } } } while (loopIfNoConnection);
codereview_java_data_10742
mSendProductDao = Utils.getAppDaoSession(this).getSendProductDao(); mSharedPref = getApplicationContext().getSharedPreferences("prefs", 0); - boolean messageDismissed = mSharedPref.getBoolean("is_message_dismissed", false); if (messageDismissed) { mContainerView.setVisibility(View.GONE); } Can we be much more explicit about the name of the message var ? I expect that eventually we'll have many explainer messages at many places in the app. mSendProductDao = Utils.getAppDaoSession(this).getSendProductDao(); mSharedPref = getApplicationContext().getSharedPreferences("prefs", 0); + boolean isMsgOnlyOnePhotoNecessaryDismissed = mSharedPref.getBoolean("is_msg_only_one_photo_necessary_dismissed", false); if (messageDismissed) { mContainerView.setVisibility(View.GONE); }
codereview_java_data_10754
if (tranType == MessageSysFlag.TRANSACTION_NOT_TYPE || tranType == MessageSysFlag.TRANSACTION_COMMIT_TYPE) { // Delay Delivery - if (msg.getDelayTimeLevel() > 0 && !isDLQTopic(msg.getTopic())) { if (msg.getDelayTimeLevel() > this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel()) { msg.setDelayTimeLevel(this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel()); } We could remove the delay_level property of DLQ msg from the source if (tranType == MessageSysFlag.TRANSACTION_NOT_TYPE || tranType == MessageSysFlag.TRANSACTION_COMMIT_TYPE) { // Delay Delivery + if (msg.getDelayTimeLevel() > 0) { if (msg.getDelayTimeLevel() > this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel()) { msg.setDelayTimeLevel(this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel()); }
codereview_java_data_10762
@JsonProperty("gcsCredentials") Map<String, Object> gcsCredentials, @JsonProperty("gcsStorageClass") Optional<String> gcsStorageClass, @JsonProperty("encryptionKey") Optional<String> encryptionKey, - @JsonProperty("s3ServerSideEncryption") Optional<Boolean> s3ServerSideEncryption) { Preconditions.checkNotNull(directory); Preconditions.checkNotNull(fileGlob); Preconditions.checkNotNull(s3Bucket); Can we name this something more like `useS3ServerSideEncryption`? Makes it a bit more obvious it's a boolean and not a string to specify a type of encryption. Other than that PR looks good @JsonProperty("gcsCredentials") Map<String, Object> gcsCredentials, @JsonProperty("gcsStorageClass") Optional<String> gcsStorageClass, @JsonProperty("encryptionKey") Optional<String> encryptionKey, + @JsonProperty("useS3ServerSideEncryption") Optional<Boolean> useS3ServerSideEncryption) { Preconditions.checkNotNull(directory); Preconditions.checkNotNull(fileGlob); Preconditions.checkNotNull(s3Bucket);
codereview_java_data_10768
/** * Initialize all views. */ private void initViews() { Timber.d("initViews called"); View elements that are part of `NearbyFragment` should ideally be not accessed directly in `NearbyMapFragment`. Either try to fix it or atleast add a `TODO` to fix it in the future. /** * Initialize all views. + * TODO: View elements that are part of NearbyFragment should ideally be not accessed directly in NearbyMapFragment. */ private void initViews() { Timber.d("initViews called");
codereview_java_data_10769
} // FIXME: Make sure that the content provider is up // This is the wrong place for it, but bleh - better than not having it turned on by default for people who don't go throughl ogin - ContentResolver.setSyncAutomatically(app.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default! - EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, CommonsApplication.getInstance()) - .param("username", app.getCurrentAccount().name) .param("categories-count", categories.size()) .param("files-count", photosList.size()) .param("source", Contribution.SOURCE_EXTERNAL) Not sure if the whole application instance should be passed. } // FIXME: Make sure that the content provider is up // This is the wrong place for it, but bleh - better than not having it turned on by default for people who don't go throughl ogin + ContentResolver.setSyncAutomatically(sessionManager.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default! + EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, mwApi, prefs) + .param("username", sessionManager.getCurrentAccount().name) .param("categories-count", categories.size()) .param("files-count", photosList.size()) .param("source", Contribution.SOURCE_EXTERNAL)
codereview_java_data_10773
private void addMutations(MutationSet mutationsToSend) { Map<String,TabletServerMutations<Mutation>> binnedMutations = new HashMap<>(); - Span span = - TraceUtil.getTracer().spanBuilder("TabletServerBatchWriter::binMutations").startSpan(); try (Scope scope = span.makeCurrent()) { long t1 = System.currentTimeMillis(); binMutations(mutationsToSend, binnedMutations); It's a little annoying that constructing a new Span and adding it to the current context are two separate steps. It's probably not worth creating a wrapper around this, but if we were to do it, we could return an AutoCloseable Span type that calls `span.end()` and `scope.close()` in its own `.close()` method. private void addMutations(MutationSet mutationsToSend) { Map<String,TabletServerMutations<Mutation>> binnedMutations = new HashMap<>(); + Span span = TraceUtil.createSpan(this.getClass(), "binMutations", SpanKind.CLIENT); try (Scope scope = span.makeCurrent()) { long t1 = System.currentTimeMillis(); binMutations(mutationsToSend, binnedMutations);
codereview_java_data_10774
import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.util.*; import java.util.stream.Collectors; import org.infinispan.protostream.FileDescriptorSource; @uteegozi we should probably avoid using import * import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import org.infinispan.protostream.FileDescriptorSource;
codereview_java_data_10780
} validateIdentityLinkArguments(family, identityId, type); - if (restApiInterceptor != null) { - restApiInterceptor.accessTaskIdentityLinks(task); - } IdentityLink link = getIdentityLink(family, identityId, type, task.getId()); return restResponseFactory.createRestIdentityLink(link); } Same story as for the case isntances. } validateIdentityLinkArguments(family, identityId, type); IdentityLink link = getIdentityLink(family, identityId, type, task.getId()); + if (restApiInterceptor != null) { + restApiInterceptor.accessTaskIdentityLink(task, link); + } + return restResponseFactory.createRestIdentityLink(link); }
codereview_java_data_10786
private final Duration maxBatchOpenInMs; public SqsBatchConfiguration(BatchOverrideConfiguration overrideConfiguration) { - Optional<BatchOverrideConfiguration> configuration = Optional.ofNullable(overrideConfiguration); - this.maxBatchItems = configuration.flatMap(BatchOverrideConfiguration::maxBatchItems).orElse(DEFAULT_MAX_BATCH_ITEMS); - this.maxBatchOpenInMs = configuration.flatMap(BatchOverrideConfiguration::maxBatchOpenInMs) - .orElse(DEFAULT_MAX_BATCH_OPEN_IN_MS); } public Duration maxBatchOpenInMs() { Wrapping overrideConfiguration with optional here seems a bit overkill to me. Can we just use plain old null check? private final Duration maxBatchOpenInMs; public SqsBatchConfiguration(BatchOverrideConfiguration overrideConfiguration) { + if (overrideConfiguration == null) { + this.maxBatchItems = DEFAULT_MAX_BATCH_ITEMS; + this.maxBatchOpenInMs = DEFAULT_MAX_BATCH_OPEN_IN_MS; + } else { + this.maxBatchItems = overrideConfiguration.maxBatchItems().orElse(DEFAULT_MAX_BATCH_ITEMS); + this.maxBatchOpenInMs = overrideConfiguration.maxBatchOpenInMs().orElse(DEFAULT_MAX_BATCH_OPEN_IN_MS); + } } public Duration maxBatchOpenInMs() {
codereview_java_data_10795
public static boolean isPrime(long val) { return API.Match(val).of( Case($(2L), true), - Case($(n -> n > 2), n -> !primes().takeWhile(d -> d <= Math.sqrt(n)).exists(d -> n % d == 0)), Case($(), false) ); } - isn't `n` always bigger than 2 here? - consider extracting `Math.sqrt(n)`, as we're recalculating it every time now public static boolean isPrime(long val) { return API.Match(val).of( Case($(2L), true), + Case($(n -> n > 2), n -> { + final double upperLimitToCheck = Math.sqrt(n); + return !primes().takeWhile(d -> d <= upperLimitToCheck).exists(d -> n % d == 0); + }), Case($(), false) ); }
codereview_java_data_10798
public static void ingest(AccumuloClient c, Opts opts, BatchWriterOpts batchWriterOpts) throws MutationsRejectedException, IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException, TableExistsException { - ingest(c, FileSystem.get(new Configuration()), opts, batchWriterOpts); } } Could possibly cast the AccumloClient to a context and get the hadoopConfig public static void ingest(AccumuloClient c, Opts opts, BatchWriterOpts batchWriterOpts) throws MutationsRejectedException, IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException, TableExistsException { + ClientContext cc = (ClientContext) c; + ingest(c, FileSystem.get(cc.getHadoopConf()), opts, batchWriterOpts); } }
codereview_java_data_10802
* v5. */ void switchToV5Framing() { // We want to do this on the event loop, to make sure it doesn't race with incoming requests assert channel.eventLoop().inEventLoop(); Why remove this? * v5. */ void switchToV5Framing() { + assert factory.protocolVersion.compareTo(ProtocolVersion.V5) >= 0; // We want to do this on the event loop, to make sure it doesn't race with incoming requests assert channel.eventLoop().inEventLoop();
codereview_java_data_10804
} if(mState != null && product.getIngredientsText() != null) { - //TODO The API doesn't return ingredients text with the _ token. the replace method could be removed String txtIngredients = product.getIngredientsText().replace("_","").trim(); if(!txtIngredients.isEmpty()) { String ingredientsValue = setSpanBoldBetweenTokens(txtIngredients).toString(); It returns allergens with _ bl _ } if(mState != null && product.getIngredientsText() != null) { String txtIngredients = product.getIngredientsText().replace("_","").trim(); if(!txtIngredients.isEmpty()) { String ingredientsValue = setSpanBoldBetweenTokens(txtIngredients).toString();
codereview_java_data_10805
unique.setTableName(tableName); command.addConstraintCommand(unique); } - - NULL_CONSTRAINT nullConstraint = parseNotNullConstraint(); - switch (nullConstraint) { - case NULL_IS_NOT_ALLOWED: column.setNullable(false); - break; - default: - // do nothing } if (readIf("CHECK")) { Expression expr = readExpression(); can just use an if statement here unique.setTableName(tableName); command.addConstraintCommand(unique); } + if (NullConstraintType.NULL_IS_NOT_ALLOWED == parseNotNullConstraint()) { column.setNullable(false); } if (readIf("CHECK")) { Expression expr = readExpression();
codereview_java_data_10814
public interface LogCaptor extends SdkAutoCloseable { List<LogEvent> loggedEvents(); void clear(); Do we have unit tests that cover this class? public interface LogCaptor extends SdkAutoCloseable { + static LogCaptor create() { + return new DefaultLogCaptor(); + } + + static LogCaptor create(Level level) { + return new DefaultLogCaptor(level); + } + List<LogEvent> loggedEvents(); void clear();
codereview_java_data_10818
initDrawer(); setTitle(getString(R.string.title_activity_contributions)); - QuizChecker quizChecker = new QuizChecker(this, - sessionManager.getCurrentAccount().name, - mediaWikiApi); if(!BuildConfig.FLAVOR.equalsIgnoreCase("beta")){ setUploadCount(); } `sessionManager.getCurrentAccount()` is nullable. initDrawer(); setTitle(getString(R.string.title_activity_contributions)); + + if(checkAccount()) { + new QuizChecker(this, + sessionManager.getCurrentAccount().name, + mediaWikiApi); + } if(!BuildConfig.FLAVOR.equalsIgnoreCase("beta")){ setUploadCount(); }
codereview_java_data_10822
private DefaultBatchManagerTestBatchManager(DefaultBuilder builder) { this.client = builder.client; ScheduledExecutorService scheduledExecutor = builder.scheduledExecutor; - ThreadFactory threadFactory = new ThreadFactoryBuilder().threadNamePrefix( - "software.amazon.awssdk.services.batchmanagertest.batchmanager.internal.DefaultBatchManagerTestBatchManager") - .build(); if (builder.executor == null) { - this.executor = createDefaultExecutor(threadFactory); this.createdExecutor = true; } else { this.executor = builder.executor; Can we move the threadFactory variable to createDefaultExectutor method? For the thread name prefix, how about something shorter, like `sdk-$serviceId(eg: sqs)-batchmanager` private DefaultBatchManagerTestBatchManager(DefaultBuilder builder) { this.client = builder.client; ScheduledExecutorService scheduledExecutor = builder.scheduledExecutor; if (builder.executor == null) { + this.executor = createDefaultExecutor(); this.createdExecutor = true; } else { this.executor = builder.executor;
codereview_java_data_10823
fullBlockchain = BlockchainSetupUtil.forTesting().importAllBlocks(); } - @SuppressWarnings("unchecked") @Before public void setup() { blockchainUtil = BlockchainSetupUtil.forTesting(); I really don't like disabling the unchecked warning. Consider using <?> when you access no templated methods. fullBlockchain = BlockchainSetupUtil.forTesting().importAllBlocks(); } @Before public void setup() { blockchainUtil = BlockchainSetupUtil.forTesting();
codereview_java_data_10828
package org.apache.iceberg; -import com.google.common.collect.Sets; import java.util.Date; import java.util.List; -import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.StreamSupport; nit: Empty line. package org.apache.iceberg; import java.util.Date; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.StreamSupport;
codereview_java_data_10830
final MockEthTask task1 = new MockEthTask(1); final MockEthTask task2 = new MockEthTask(); - ethScheduler.scheduleTxWorkerTask(BoundedTimedTask.fromRunnable(task1::executeTask)); - ethScheduler.scheduleTxWorkerTask(BoundedTimedTask.fromRunnable(task2::executeTask)); ethScheduler.stop(); assertThat(txWorkerExecutor.isShutdown()).isTrue(); Why not move this wrapping into `scheduleTxWorkerTask`? final MockEthTask task1 = new MockEthTask(1); final MockEthTask task2 = new MockEthTask(); + ethScheduler.scheduleTxWorkerTask(task1::executeTask); + ethScheduler.scheduleTxWorkerTask(task2::executeTask); ethScheduler.stop(); assertThat(txWorkerExecutor.isShutdown()).isTrue();
codereview_java_data_10846
}; } else if (map instanceof ClientMapProxy) { // TODO: add strategy/unify after https://github.com/hazelcast/hazelcast/issues/13950 is fixed - addToBuffer = entry -> { - Data key = serializationService.toData(key(entry)); - Data value = serializationService.toData(value(entry)); buffer.add(new SimpleEntry<>(key, value)); }; } else { should also be called `item` }; } else if (map instanceof ClientMapProxy) { // TODO: add strategy/unify after https://github.com/hazelcast/hazelcast/issues/13950 is fixed + addToBuffer = item -> { + Data key = serializationService.toData(key(item)); + Data value = serializationService.toData(value(item)); buffer.add(new SimpleEntry<>(key, value)); }; } else {
codereview_java_data_10848
public synchronized String getPropertiesPath() { if (propsPath == null) { - URL propLocation = SiteConfiguration.getAccumuloPropsLocation(); - propsPath = propLocation.getFile(); } return propsPath; } Could this just be one line? public synchronized String getPropertiesPath() { if (propsPath == null) { + propsPath = SiteConfiguration.getAccumuloPropsLocation().getFile(); } return propsPath; }
codereview_java_data_10862
} } - protected SingularityDeleteResult delete(String path, ZkCache<?> cache) { - cache.delete(path); - return delete(path); - } - protected SingularityDeleteResult delete(String path) { final long start = System.currentTimeMillis(); Won't other nodes still have this data cached? } } protected SingularityDeleteResult delete(String path) { final long start = System.currentTimeMillis();
codereview_java_data_10863
if (tablet.needsSplit()) { tablet.getTabletServer().executeSplit(tablet); } - } catch (Exception t) { - log.error("Unknown error during minor compaction for extent: " + tablet.getExtent(), t); - throw new RuntimeException(t); } finally { tablet.minorCompactionComplete(); } This seems to be wrapping the exception with a RTE. Are there even checked exceptions that can occur here? If so, we probably should enumerate them explicitly, and only wrap checked exceptions, leaving RTEs unwrapped. if (tablet.needsSplit()) { tablet.getTabletServer().executeSplit(tablet); } + } catch (Exception e) { + log.error("Unknown error during minor compaction for extent: {}", tablet.getExtent(), e); + throw e; } finally { tablet.minorCompactionComplete(); }
codereview_java_data_10867
} // get Iceberg props that have been removed - List<String> removedProps = Collections.emptyList(); if (base != null) { removedProps = base.properties().keySet().stream() .filter(key -> !metadata.properties().containsKey(key)) - .collect(Collectors.toList()); } setHmsTableParameters(newMetadataLocation, tbl, metadata.properties(), removedProps, hiveEngineEnabled); Could this be a set? } // get Iceberg props that have been removed + Set<String> removedProps = Collections.emptySet(); if (base != null) { removedProps = base.properties().keySet().stream() .filter(key -> !metadata.properties().containsKey(key)) + .collect(Collectors.toSet()); } setHmsTableParameters(newMetadataLocation, tbl, metadata.properties(), removedProps, hiveEngineEnabled);
codereview_java_data_10869
@EnableConfigurationProperties(SelfTracingProperties.class) @ConditionalOnSelfTracing public class TracingConfiguration { - static volatile Thread reporterThread; - - public static boolean isSpanReporterThread() { - return Thread.currentThread() == reporterThread; - } - /** Configuration for how to buffer spans into messages for Zipkin */ @Bean Reporter<Span> reporter(BeanFactory factory, SelfTracingProperties config) { return AsyncReporter.builder(new LocalSender(factory)) - .threadFactory(r -> reporterThread = new Thread(r)) .messageTimeout(config.getMessageTimeout().toNanos(), TimeUnit.NANOSECONDS) .metrics(new ReporterMetricsAdapter(factory)) .build(); While bean's are generally singleton, it seems highly unusual to save into a static variable from a bean constructor. I think I'd at least go ahead and make another bean holder, something like ```java static class ReporterThreadFactory implements ThreadFactory { volatile Thread reporterThread; public Thread newThread(Runnable r) { if (reporterThread != null) throw? return reporterThread = new Thread(r); } public boolean isSpanReporterThread() { return Thread.currentThread() == reporterThread; } } ``` Then areas that want to know if it's a span reporter thread can inject this bean and call the method. @EnableConfigurationProperties(SelfTracingProperties.class) @ConditionalOnSelfTracing public class TracingConfiguration { /** Configuration for how to buffer spans into messages for Zipkin */ @Bean Reporter<Span> reporter(BeanFactory factory, SelfTracingProperties config) { return AsyncReporter.builder(new LocalSender(factory)) .messageTimeout(config.getMessageTimeout().toNanos(), TimeUnit.NANOSECONDS) .metrics(new ReporterMetricsAdapter(factory)) .build();
codereview_java_data_10873
import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; Put in a 2 second delay because the reloading thread kept starting before the CuratorFrameworkImpl started import java.util.Collection; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function;
codereview_java_data_10874
*/ public abstract class SingleKeyAction extends KeysRelatedAction { protected final Keys key; - private static final Keys[] MODIFIER_KEYS = {Keys.SHIFT, Keys.CONTROL, Keys.ALT, Keys.META, Keys.COMMAND, Keys.LEFT_ALT, Keys.LEFT_CONTROL, Keys.LEFT_SHIFT}; protected SingleKeyAction(Keyboard keyboard, Mouse mouse, Keys key) { this(keyboard, mouse, null, key); LEFT_ALT, LEFT_CONTROL, and LEFT_SHIFT should already be aliases. META could be an alias for ALT but probably isn't yet. */ public abstract class SingleKeyAction extends KeysRelatedAction { protected final Keys key; + private static final Keys[] MODIFIER_KEYS = {Keys.SHIFT, Keys.CONTROL, Keys.ALT, Keys.META}; protected SingleKeyAction(Keyboard keyboard, Mouse mouse, Keys key) { this(keyboard, mouse, null, key);
codereview_java_data_10877
import static tech.pegasys.pantheon.tests.acceptance.dsl.node.PantheonNodeConfig.pantheonCliqueMinerNode; import tech.pegasys.pantheon.tests.acceptance.dsl.AcceptanceTestBase; -import tech.pegasys.pantheon.tests.acceptance.dsl.clique.CliqueConditions; import tech.pegasys.pantheon.tests.acceptance.dsl.node.PantheonNode; import java.io.IOException; This isn't really asserting anything because the validators are always the same. The test would pass even if we always returned the validators from genesis. Would also be good to remove the direct call to web3 here with something like `cliqueConditions.validatorsAtLatestBlockEquals` so the DSL does the work instead of the test. import static tech.pegasys.pantheon.tests.acceptance.dsl.node.PantheonNodeConfig.pantheonCliqueMinerNode; import tech.pegasys.pantheon.tests.acceptance.dsl.AcceptanceTestBase; import tech.pegasys.pantheon.tests.acceptance.dsl.node.PantheonNode; import java.io.IOException;
codereview_java_data_10879
@Override public SnapshotTable.Result execute() { - JobGroupInfo info = newJobGroupInfo("SNAPSHOT-TABLE", - String.format("Snapshotting table %s as %s", sourceTableIdent().toString(), destTableIdent.toString())); return withJobGroupInfo(info, this::doExecute); } Do we need to call toString explicitly? Can we also put the description into a separate var so that this fits on one line? ``` String desc = String.format("Snapshotting table %s as %s", sourceTableIdent(), destTableIdent); ``` @Override public SnapshotTable.Result execute() { + String desc = String.format("Snapshotting table %s as %s", sourceTableIdent(), destTableIdent); + JobGroupInfo info = newJobGroupInfo("SNAPSHOT-TABLE", desc); return withJobGroupInfo(info, this::doExecute); }
codereview_java_data_10883
public Writer(BlockFileWriter bfw, int blockSize) throws IOException { this(bfw, blockSize, (int) DefaultConfiguration.getInstance().getAsBytes(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE_INDEX), null, null); - long indexBlockSize = DefaultConfiguration.getInstance().getAsBytes(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE_INDEX); - if (indexBlockSize > Integer.MAX_VALUE || indexBlockSize < 0) { - throw new IllegalArgumentException("table.file.compress.blocksize.index must be greater than 0 and no more than " + Integer.MAX_VALUE); - } } public Writer(BlockFileWriter bfw, int blockSize, int indexBlockSize, SamplerConfigurationImpl samplerConfig, Sampler sampler) throws IOException { This appears to only be checking the default value... which is hard-coded. A check in the unit test for Property could ensure we don't make a stupid mistake for the default. I think we may have a validate method in Property.java, also, which might be used to do a quick verification that a value is good when a user sets it or when the process starts up and reads the config for the first time. public Writer(BlockFileWriter bfw, int blockSize) throws IOException { this(bfw, blockSize, (int) DefaultConfiguration.getInstance().getAsBytes(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE_INDEX), null, null); } public Writer(BlockFileWriter bfw, int blockSize, int indexBlockSize, SamplerConfigurationImpl samplerConfig, Sampler sampler) throws IOException {
codereview_java_data_10898
AppDefinition revisedDefinition = mergeAndExpandAppProperties(currentApp, metadataResource, appDeployTimeProperties); AppDeploymentRequest request = new AppDeploymentRequest(revisedDefinition, appResource, deployerDeploymentProperties); try { - String loggingString = String.format("Deploying the app '%s.%s'", currentApp.getStreamName(), - request.getDefinition().getName()); - if (request.getResource().getFilename() != null) { - loggingString = String.format(loggingString + " using the resource '%s'", request.getResource().getFilename()); } logger.info(loggingString); String id = this.deployer.deploy(request); I would change the format to not be <streamName>.<appLabel> and be explicit in terms of the components. ``` Deploying application named [log] as part of stream named [ticktock] using the resource [maven://blahblah]. ``` Will modify on merge I was thinking if we could get finer grained in terms of the download request, that would live in the deployer and the call to `getInputStream`.... AppDefinition revisedDefinition = mergeAndExpandAppProperties(currentApp, metadataResource, appDeployTimeProperties); AppDeploymentRequest request = new AppDeploymentRequest(revisedDefinition, appResource, deployerDeploymentProperties); try { + String loggingString = String.format("Deploying application named [%s] as part of stream named [%s]", + request.getDefinition().getName(), currentApp.getStreamName()); + if (registration.getUri() != null) { + loggingString = String.format(loggingString + " using the resource '%s'", registration.getUri()); } logger.info(loggingString); String id = this.deployer.deploy(request);
codereview_java_data_10902
import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.Callable; -import java.util.concurrent.Executors; import org.apache.accumulo.master.TimeoutTaskExecutor.SuccessCallback; import org.apache.accumulo.master.TimeoutTaskExecutor.TimeoutCallback; try changing this code to ```java public String call() throws Exception { try { Thread.sleep(timeout); } catch (InterruptedException e) { Thread.sleep(timeout); } return result; } ``` This simulates badly behaved code (some hadoop code used to swallow thread interrupts and keep going, not sure if it still does). This will cause a test to fail because a non-slow task is canceled. import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.Callable; import org.apache.accumulo.master.TimeoutTaskExecutor.SuccessCallback; import org.apache.accumulo.master.TimeoutTaskExecutor.TimeoutCallback;
codereview_java_data_10907
justification = "all updates to ongoingSnapshotId are synchronized") public void startNewSnapshot(String exportedSnapshotMapName) { ongoingSnapshotId++; - ongoingSnapshotStartTime = System.nanoTime(); this.exportedSnapshotMapName = exportedSnapshotMapName; } is this value used by Management Center? since it would make the timestamps useless. justification = "all updates to ongoingSnapshotId are synchronized") public void startNewSnapshot(String exportedSnapshotMapName) { ongoingSnapshotId++; + ongoingSnapshotStartTime = Clock.currentTimeMillis(); this.exportedSnapshotMapName = exportedSnapshotMapName; }
codereview_java_data_10912
import tech.pegasys.pantheon.tests.acceptance.dsl.node.Cluster; import tech.pegasys.pantheon.tests.acceptance.dsl.node.PantheonNode; -import javax.annotation.concurrent.Immutable; - -@Immutable public class JsonRpc { private final Cluster nodes; I'll review this properly tomorrow but, why the @Immutable annotations? import tech.pegasys.pantheon.tests.acceptance.dsl.node.Cluster; import tech.pegasys.pantheon.tests.acceptance.dsl.node.PantheonNode; public class JsonRpc { private final Cluster nodes;
codereview_java_data_10917
"difficulty_total", "Total difficulty of the chainhead", () -> - new BigInteger(this.getChainHead().getTotalDifficulty().getBytes().getArrayUnsafe()) .doubleValue()); } There's a utility for transforming `BytesValues` to `BigInteger`'s: `BytesValues.asUnsignedBigInteger(this.getChainHead().getTotalDifficulty().getBytes()).doubleValue()` "difficulty_total", "Total difficulty of the chainhead", () -> + BytesValues.asUnsignedBigInteger(this.getChainHead().getTotalDifficulty().getBytes()) .doubleValue()); }
codereview_java_data_10920
try { if (f.getType() == GeneratedFile.Type.RESOURCE) { writeGeneratedFile(f, resourcePath); - } else if (isCustomizable(f)) { writeGeneratedFile(f, restResourcePath); } else { writeGeneratedFile(f, sourcePath); this is still using a "naming convention," and I feel it's going to be quite fragile try { if (f.getType() == GeneratedFile.Type.RESOURCE) { writeGeneratedFile(f, resourcePath); + } else if (f.getType().isCustomizable()) { writeGeneratedFile(f, restResourcePath); } else { writeGeneratedFile(f, sourcePath);
codereview_java_data_10934
} public int getRequestTimeoutMillis() { - return ibftConfigRoot.getInteger("requesttimeoutseconds", DEFAULT_ROUND_EXPIRY_MILLISECONDS); } } shouldn't this be requesttimeoutmilliseconds the default value and method suggests it is meant to represents millis } public int getRequestTimeoutMillis() { + return ibftConfigRoot.getInteger("requesttimeout", DEFAULT_ROUND_EXPIRY_MILLISECONDS); } }
codereview_java_data_10940
@JsonProperty @NotNull - private boolean switchUser = true; public List<SingularityExecutorShellCommandOptionDescriptor> getOptions() { return options; can we make this more descriptive? (i.e. `runAsTaskUser`) @JsonProperty @NotNull + private boolean runAsTaskUser = true; public List<SingularityExecutorShellCommandOptionDescriptor> getOptions() { return options;
codereview_java_data_10945
CompactableImpl.CompactionInfo cInfo, CompactionEnv cenv, Map<StoredTabletFile,DataFileValue> compactFiles, TabletFile tmpFileName) throws IOException, CompactionCanceledException { - boolean propagateDeletes = cInfo.propagateDeletes; AccumuloConfiguration compactionConfig = getCompactionConfig(tablet.getTableConfiguration(), getOverrides(job.getKind(), tablet, cInfo.localHelper, job.getFiles())); FileCompactor compactor = new FileCompactor(tablet.getContext(), tablet.getExtent(), - compactFiles, tmpFileName, propagateDeletes, cenv, cInfo.iters, compactionConfig); return compactor.call(); } Could this be inlined? CompactableImpl.CompactionInfo cInfo, CompactionEnv cenv, Map<StoredTabletFile,DataFileValue> compactFiles, TabletFile tmpFileName) throws IOException, CompactionCanceledException { AccumuloConfiguration compactionConfig = getCompactionConfig(tablet.getTableConfiguration(), getOverrides(job.getKind(), tablet, cInfo.localHelper, job.getFiles())); FileCompactor compactor = new FileCompactor(tablet.getContext(), tablet.getExtent(), + compactFiles, tmpFileName, cInfo.propagateDeletes, cenv, cInfo.iters, compactionConfig); return compactor.call(); }
codereview_java_data_10946
try { double progress = entries.getValue().getBytesCopied() / walBlockSize; // to be sure progress does not exceed 100% - status.progress = Math.max(progress, 99.0); } catch (IOException ex) { log.warn("Error getting bytes read"); } I think this keeps the status permanently at 99%. I think we want something like `Math.min(progress, 99.9)` try { double progress = entries.getValue().getBytesCopied() / walBlockSize; // to be sure progress does not exceed 100% + status.progress = Math.min(progress, 99.0); } catch (IOException ex) { log.warn("Error getting bytes read"); }
codereview_java_data_10954
).collect(joining("\n"))); } - private static boolean isSplitLocalForMember(InputSplit split, Address memberAddr) { try { final InetAddress inetAddr = memberAddr.getInetAddress(); return Arrays.stream(split.getLocations()) We should log this at warning level if it happens. ).collect(joining("\n"))); } + private boolean isSplitLocalForMember(InputSplit split, Address memberAddr) { try { final InetAddress inetAddr = memberAddr.getInetAddress(); return Arrays.stream(split.getLocations())
codereview_java_data_10956
@Experimental public final class ASTGuardedPattern extends AbstractJavaNode implements ASTPattern { ASTGuardedPattern(int id) { super(id); } ```suggestion * GuardedPattern ::= {@linkplain ASTPattern Pattern} "&amp;&amp;" {@linkplain ASTConditionalAndExpression ConditionalAndExpression} ``` @Experimental public final class ASTGuardedPattern extends AbstractJavaNode implements ASTPattern { + private int parenDepth; + ASTGuardedPattern(int id) { super(id); }
codereview_java_data_10964
} /** - * Upgrades the settings from version 75 to 76. * * <p> - * Change default value of {@code registeredNameColor} from {@code 0xFF00008F} to {@code -638932 )} (#F6402C). * </p> */ private static class SettingsUpgraderV79 implements SettingsUpgrader { The actual colors are probably not important. The reason why the colors were changed are probably more interesting to a reader in the future. ```suggestion * Change default value of {@code registeredNameColor} to have enough contrast in both the light and dark theme. ``` } /** + * Upgrades the settings from version 78 to 79. * * <p> + * Change default value of {@code registeredNameColor} to have enough contrast in both the light and dark theme. * </p> */ private static class SettingsUpgraderV79 implements SettingsUpgrader {
codereview_java_data_10965
} } - @Override - public void onAttach(Context context) { - super.onAttach(context); - } - @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { Unnecessary empty method. } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) {
codereview_java_data_10970
bolusMessage.setDuration(0); bolusMessage.setExtendedAmount(0); bolusMessage.setImmediateAmount(insulin); - bolusMessage.setVibration(sp.getBoolean("insight_disable_vibration",false)); bolusID = connectionService.requestMessage(bolusMessage).await().getBolusId(); bolusCancelled = false; } You may also want to add another setting for automated treatments to differentiate between manual boluses and SMBs (use `detailedBolusInfo.isSMB`) bolusMessage.setDuration(0); bolusMessage.setExtendedAmount(0); bolusMessage.setImmediateAmount(insulin); + bolusMessage.setVibration(sp.getBoolean(detailedBolusInfo.isSMB ? R.string.key_disable_vibration_auto : R.string.key_disable_vibration ,false)); bolusID = connectionService.requestMessage(bolusMessage).await().getBolusId(); bolusCancelled = false; }
codereview_java_data_10972
public static final String CATALOG = "iceberg.mr.catalog"; public static final String HADOOP_CATALOG_WAREHOUSE_LOCATION = "iceberg.mr.catalog.hadoop.warehouse.location"; public static final String CATALOG_LOADER_CLASS = "iceberg.mr.catalog.loader.class"; - public static final String COLUMN_PROJECTIONS = "iceberg.mr.column.projections"; public static final String CATALOG_NAME = "iceberg.catalog"; public static final String HADOOP_CATALOG = "hadoop.catalog"; The wording we've generally settled on is that `project` is used to set a requested schema and `select` is used to select columns like a `SELECT` statement in SQL. Following that convention, when we pass a schema we call it a "projection" and when we pass columns we call them "selected columns". I think it would be good to make this more clear, since this is passing columns to project and not a schema. How about `SELECTED_COLUMNS = "iceberg.mr.selected.columns"`? public static final String CATALOG = "iceberg.mr.catalog"; public static final String HADOOP_CATALOG_WAREHOUSE_LOCATION = "iceberg.mr.catalog.hadoop.warehouse.location"; public static final String CATALOG_LOADER_CLASS = "iceberg.mr.catalog.loader.class"; + public static final String SELECTED_COLUMNS = "iceberg.mr.selected.columns"; public static final String CATALOG_NAME = "iceberg.catalog"; public static final String HADOOP_CATALOG = "hadoop.catalog";
codereview_java_data_10975
return; } // Check if the subscriber is an anonymous user - if (!UserManager.getInstance().isRegisteredUser(subscriberJID) && !isComponent(subscriberJID)) { // Anonymous users cannot subscribe to the node. Return forbidden error sendErrorPacket(iq, PacketError.Condition.forbidden, null); return; Assuming Java does shortcuts, you'll want this as the first condition: if (!isComponent(subscriberJID) && ...) isRegisteredUser() will do a disco#info query (rather surprisingly) in order to find out whether a remote user is anonymous or not. Not sure this is right, but it's what's done. return; } // Check if the subscriber is an anonymous user + if (!isComponent(subscriberJID) && !UserManager.getInstance().isRegisteredUser(subscriberJID)) { // Anonymous users cannot subscribe to the node. Return forbidden error sendErrorPacket(iq, PacketError.Condition.forbidden, null); return;
codereview_java_data_10976
// Http code 200 if (result.ok()) { - return JSONUtils.deserializeObject(result.getData(), new TypeReference<SampleResult>() { - }); } else { LogUtil.DEFAULT_LOG.info("Can not get clientInfo from {} with {}", ip, result.getData()); Can unified json utils to Jackson util? // Http code 200 if (result.ok()) { + return JacksonUtils.toObj(result.getData(), SampleResult.class); } else { LogUtil.DEFAULT_LOG.info("Can not get clientInfo from {} with {}", ip, result.getData());
codereview_java_data_10977
Timestamp currentTimestamp = Timestamp.from(Instant.ofEpochMilli(System.currentTimeMillis())); List<Object[]> output = sql( - "CALL %s.system.expire_snapshots('%s', '%s', TIMESTAMP '%s', 1)", - catalogName, tableIdent.namespace(), tableIdent.name(), currentTimestamp); assertEquals("Procedure output must match", ImmutableList.of(row(0L, 0L, 1L)), output); Not sure we need some of the more generic checks here, like testing if named and pos args cannot be mixed Timestamp currentTimestamp = Timestamp.from(Instant.ofEpochMilli(System.currentTimeMillis())); List<Object[]> output = sql( + "CALL %s.system.expire_snapshots(" + + "older_than => TIMESTAMP '%s'," + + "namespace => '%s'," + + "table => '%s'," + + "retain_last => 1)", + catalogName, currentTimestamp, tableIdent.namespace(), tableIdent.name()); assertEquals("Procedure output must match", ImmutableList.of(row(0L, 0L, 1L)), output);
codereview_java_data_10994
protected static class LocalConfig { @Bean - public ModuleDeployer longRunningModuleDeployer(ModuleLauncher moduleLauncher) { return new LocalModuleDeployer(moduleLauncher); } Since we are creating two same beans with different names for the purpose of using them in qualifiers, can we do this way: ``` @Bean(name={"longRunningModuleDeployer","taskModuleDeployer"}) ``` protected static class LocalConfig { @Bean + public ModuleDeployer processModuleDeployer(ModuleLauncher moduleLauncher) { return new LocalModuleDeployer(moduleLauncher); }
codereview_java_data_10996
if (this.runtimeApps.getPlatformType().equalsIgnoreCase(RuntimeApplicationHelper.KUBERNETES_PLATFORM_TYPE)) { propertiesBuilder.put("app.*.server.port", "80"); - propertiesBuilder.put("deployer.*.kubernetes.createLoadBalancer", "true"); // requires metallb } return propertiesBuilder.build(); id recommend `// requires metallb` to be something say like `// requires LoadBalancer support on the platform` if (this.runtimeApps.getPlatformType().equalsIgnoreCase(RuntimeApplicationHelper.KUBERNETES_PLATFORM_TYPE)) { propertiesBuilder.put("app.*.server.port", "80"); + propertiesBuilder.put("deployer.*.kubernetes.createLoadBalancer", "true"); // requires LoadBalancer support on the platform } return propertiesBuilder.build();
codereview_java_data_11017
Symbol varSymbol, Symbol.MethodSymbol methodSymbol, List<TreePath> usagePaths, VisitorState state) { boolean isPrivateMethod = methodSymbol.getModifiers().contains(Modifier.PRIVATE); int index = methodSymbol.params.indexOf(varSymbol); - Preconditions.checkState(index != -1, "symbol must be a parameter to the owning method"); SuggestedFix.Builder fix = SuggestedFix.builder(); for (TreePath path : usagePaths) { fix.delete(path.getLeaf()); might be nice to log the symbol and the method if we're gonna throw? :) Symbol varSymbol, Symbol.MethodSymbol methodSymbol, List<TreePath> usagePaths, VisitorState state) { boolean isPrivateMethod = methodSymbol.getModifiers().contains(Modifier.PRIVATE); int index = methodSymbol.params.indexOf(varSymbol); + Preconditions.checkState(index != -1, "symbol {} must be a parameter to the owning method", varSymbol); SuggestedFix.Builder fix = SuggestedFix.builder(); for (TreePath path : usagePaths) { fix.delete(path.getLeaf());
codereview_java_data_11018
this.keyMetadata = toCopy.keyMetadata() == null ? null : ByteBuffers.copy(toCopy.keyMetadata()); this.splitOffsets = toCopy.splitOffsets() == null ? null : copyList(toCopy.splitOffsets()); - this.sortOrderId = toCopy.sortOrderId() == null ? SortOrder.unsorted().orderId() : toCopy.sortOrderId(); return this; } If the copied `DataFile` returns null, shouldn't the copy also return null? Why not make the builder use `Integer` instead of a primitive here? this.keyMetadata = toCopy.keyMetadata() == null ? null : ByteBuffers.copy(toCopy.keyMetadata()); this.splitOffsets = toCopy.splitOffsets() == null ? null : copyList(toCopy.splitOffsets()); + this.sortOrderId = toCopy.sortOrderId(); return this; }
codereview_java_data_11025
Collectors.toList(), StringUtils.joiningWithLastDelimiter(", ", " and "))); if (!affectedOptions.isEmpty()) { - logger.warn("{} require {} option to be true.", affectedOptions, mainOptionName); } } } I think the verbiage could be better. Perhaps Madeline or Jake could weigh in. ```suggestion logger.warn("{} will have no effect unless {} is in the command line.", affectedOptions, mainOptionName); ``` Collectors.toList(), StringUtils.joiningWithLastDelimiter(", ", " and "))); if (!affectedOptions.isEmpty()) { + logger.warn("{} will have no effect unless {} is in the command line.", affectedOptions, mainOptionName); } } }
codereview_java_data_11028
} static void init(TestHiveShell shell, TestTables testTables, TemporaryFolder temp, String engine) { - init(shell, testTables, temp, engine, "false"); } - static void init(TestHiveShell shell, TestTables testTables, TemporaryFolder temp, String engine, String cboEnable) { shell.openSession(); for (Map.Entry<String, String> property : testTables.properties().entrySet()) { Could we use a boolean instead of the string? } static void init(TestHiveShell shell, TestTables testTables, TemporaryFolder temp, String engine) { + init(shell, testTables, temp, engine, false); } + static void init(TestHiveShell shell, TestTables testTables, TemporaryFolder temp, String engine, boolean cboEnable) { shell.openSession(); for (Map.Entry<String, String> property : testTables.properties().entrySet()) {
codereview_java_data_11039
public static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids,boolean anonymize) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); Eek, anonymize scattered all over this file makes it hard to track what should and should not be anonymized. I'd create a Set of anonymous fields and let writeElement() figure out if it should anonymize or not. ``` java private static final Set<String> privateFields = ImmutableSet<String>.of(HOST_ELEMENT, POST_ELEMENT, etc); // In writeElement() if(privateFields.contains(elementName)) { value = ANNON_STRING; } ``` public static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids,boolean anonymize) throws SettingsImportExportException { + if(anonymize) { + // pass the hidden fields to startElements with this static memeber + privateFields = new HashSet<String>(Arrays.asList(USERNAME_ELEMENT, PASSWORD_ELEMENT, + NAME_ELEMENT, EMAIL_ELEMENT, HOST_ELEMENT, PORT_ELEMENT)); + } else { + privateFields = new HashSet<String>(); + } try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8");
codereview_java_data_11042
TableUtils.createTableIfNotExists(connectionSource, TDD.class); // soft migration without changing DB version - createRowIfNotExists(getDaoBgReadings(), DatabaseHelper.DATABASE_BGREADINGS, "isFiltered", "integer"); - createRowIfNotExists(getDaoBgReadings(), DatabaseHelper.DATABASE_BGREADINGS, "sourcePlugin", "text"); } catch (SQLException e) { I guess you've meant `createColumnIfNotExists`, as you are actually adding a *column*, not a *row*. ;-) TableUtils.createTableIfNotExists(connectionSource, TDD.class); // soft migration without changing DB version + createColumnIfNotExists(getDaoBgReadings(), DatabaseHelper.DATABASE_BGREADINGS, "isFiltered", "integer"); + createColumnIfNotExists(getDaoBgReadings(), DatabaseHelper.DATABASE_BGREADINGS, "sourcePlugin", "text"); } catch (SQLException e) {
codereview_java_data_11046
*/ package tech.pegasys.pantheon.chainexport; -import tech.pegasys.pantheon.ethereum.ProtocolContext; import tech.pegasys.pantheon.ethereum.core.Block; import tech.pegasys.pantheon.ethereum.rlp.RLP; import tech.pegasys.pantheon.util.bytes.BytesValue; Question: Are you writing binary data in the file ? Is it what we want ? */ package tech.pegasys.pantheon.chainexport; +import tech.pegasys.pantheon.ethereum.chain.Blockchain; import tech.pegasys.pantheon.ethereum.core.Block; import tech.pegasys.pantheon.ethereum.rlp.RLP; import tech.pegasys.pantheon.util.bytes.BytesValue;
codereview_java_data_11047
t2 = System.currentTimeMillis(); - out.printf("existent lookup rate %6.2f%n", 500 / ((t2 - t1) / 1000.0)); out.println("expected hits 500. Receive hits: " + count); bmfr.close(); } Maybe this should be existing? ``` suggest out.printf("existing lookup rate %6.2f%n", 500 / ((t2 - t1) / 1000.0)); ``` t2 = System.currentTimeMillis(); + out.printf("existing lookup rate %6.2f%n", 500 / ((t2 - t1) / 1000.0)); out.println("expected hits 500. Receive hits: " + count); bmfr.close(); }
codereview_java_data_11050
import com.hazelcast.jet.pipeline.BatchSource; import com.hazelcast.jet.pipeline.SourceBuilder; import com.hazelcast.jet.pipeline.SourceBuilder.SourceBuffer; import javax.annotation.Nonnull; import javax.annotation.Nullable; any open readers (if there was some exception, or job is cancelled) should also be closed here import com.hazelcast.jet.pipeline.BatchSource; import com.hazelcast.jet.pipeline.SourceBuilder; import com.hazelcast.jet.pipeline.SourceBuilder.SourceBuffer; +import com.hazelcast.nio.IOUtil; import javax.annotation.Nonnull; import javax.annotation.Nullable;
codereview_java_data_11056
Suppliers.memoize(() -> CliqueBlockHashing.recoverProposerAddress(header, this)); } - public static BytesValue createUnsignedData( final BytesValue vanityData, final List<Address> validators) { return new CliqueExtraData(vanityData, null, validators, null).encode(); } is this a warning? Or is it expected that someone MUST call decodeRaw quite early in the reception (why not force the call during blockimporter?) Suppliers.memoize(() -> CliqueBlockHashing.recoverProposerAddress(header, this)); } + public static BytesValue createWithoutProposerSeal( final BytesValue vanityData, final List<Address> validators) { return new CliqueExtraData(vanityData, null, validators, null).encode(); }
codereview_java_data_11057
@Override public String toString() { - byte[] binary = new byte[value().remaining()]; - value().duplicate().get(binary); - return "0x" + BaseEncoding.base16().encode(binary); } } There's an existing ByteBuffers utility class, org.apache.iceberg.util.ByteBuffers, which you can use here. Can you please use that for consistency? It's also more efficient in some cases (doesn't always necessarily allocate, handles offsets more thoroughly, etc). @Override public String toString() { + return "0x" + ByteBuffers.encodeHexString(value()); } }
codereview_java_data_11064
public static void updateExtendedBolusInDB() { TreatmentsInterface treatmentsInterface = new TreatmentsPlugin(); - if ( TreatmentsPlugin.getPlugin() != null) { - treatmentsInterface = TreatmentsPlugin.getPlugin(); - } - DanaRPump pump = DanaRPump.getInstance(); long now = System.currentTimeMillis(); this is wrong, it creates another instance of singleton. keep it as it was public static void updateExtendedBolusInDB() { TreatmentsInterface treatmentsInterface = new TreatmentsPlugin(); DanaRPump pump = DanaRPump.getInstance(); long now = System.currentTimeMillis();
codereview_java_data_11065
//snippet-service:[elastictranscoder] //snippet-sourcetype:[snippet] //snippet-sourcedate:[] -//snippet-sourceauthor:[] /* * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * i don't think this is a snippet for java. is it supposed to be part of a different language PR? //snippet-service:[elastictranscoder] //snippet-sourcetype:[snippet] //snippet-sourcedate:[] +//snippet-sourceauthor:[AWS] /* * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. *
codereview_java_data_11095
import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.refEq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import tech.pegasys.pantheon.ethereum.core.BlockHeader; Should you verify `checkCompletion` wasn't called? import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.refEq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import tech.pegasys.pantheon.ethereum.core.BlockHeader;
codereview_java_data_11097
import java.util.Collection; import java.util.Collections; -import java.util.Iterator; import java.util.List; import java.util.Map; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.Singleton; remove `limitCount` and `limitStart`, and just use `getFromZk()` instead import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.Singleton;
codereview_java_data_11098
service.shutdown(); try { - service.awaitTermination( 500, TimeUnit.MILLISECONDS ); Log.debug( "Successfully notified all {} local users about the imminent destruction of chat service '{}'", users.size(), chatServiceName ); } catch ( InterruptedException e ) Should this value be configurable? service.shutdown(); try { + service.awaitTermination( JiveGlobals.getIntProperty( "xmpp.muc.await-termination-millis", 500 ), TimeUnit.MILLISECONDS ); Log.debug( "Successfully notified all {} local users about the imminent destruction of chat service '{}'", users.size(), chatServiceName ); } catch ( InterruptedException e )
codereview_java_data_11101
import org.flowable.bpmn.converter.export.FieldExtensionExport; import org.flowable.bpmn.converter.export.MapExceptionExport; import org.flowable.bpmn.converter.util.BpmnXMLUtil; -import org.flowable.bpmn.model.*; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; Please note the project does not use wildcard imports but explicitly lists each import. Thanks. import org.flowable.bpmn.converter.export.FieldExtensionExport; import org.flowable.bpmn.converter.export.MapExceptionExport; import org.flowable.bpmn.converter.util.BpmnXMLUtil; +import org.flowable.bpmn.model.AbstractFlowableHttpHandler; +import org.flowable.bpmn.model.BaseElement; +import org.flowable.bpmn.model.BpmnModel; +import org.flowable.bpmn.model.CaseServiceTask; +import org.flowable.bpmn.model.CustomProperty; +import org.flowable.bpmn.model.HttpServiceTask; +import org.flowable.bpmn.model.ImplementationType; +import org.flowable.bpmn.model.ServiceTask; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter;
codereview_java_data_11105
* When there is no file matching the glob specified by * {@link #glob(String)} (or the default glob) Jet throws an exception by * default. This might be problematic in some cases, where the directory - * is empty. To override this behaviour set this to true. The source * <p> * If set to true and there are no files in the directory the source will * produce 0 items. `The source` at the end of the line, a leftover ? * When there is no file matching the glob specified by * {@link #glob(String)} (or the default glob) Jet throws an exception by * default. This might be problematic in some cases, where the directory + * is empty. To override this behaviour set this to true. * <p> * If set to true and there are no files in the directory the source will * produce 0 items.
codereview_java_data_11108
TSERV_COMPACTION_SERVICE_ROOT_PLANNER("tserver.compaction.major.service.root.planner", DefaultCompactionPlanner.class.getName(), PropertyType.CLASSNAME, "Compaction planner for root tablet service"), - TSERV_COMPACTION_SERVICE_ROOT_THROUGHPUT("tserver.compaction.major.service.root.throughput", "0B", PropertyType.BYTES, "Maximum number of bytes to read or write per second over all major" + " compactions in this compaction service, or 0B for unlimited."), I think a property that is easier to spell is more user friendly. The last part of the property could be "limit" or "rate.limit". As a bad speller, I know a word like "throughput" would trip me up. TSERV_COMPACTION_SERVICE_ROOT_PLANNER("tserver.compaction.major.service.root.planner", DefaultCompactionPlanner.class.getName(), PropertyType.CLASSNAME, "Compaction planner for root tablet service"), + TSERV_COMPACTION_SERVICE_ROOT_RATE_LIMIT("tserver.compaction.major.service.root.rate.limit", "0B", PropertyType.BYTES, "Maximum number of bytes to read or write per second over all major" + " compactions in this compaction service, or 0B for unlimited."),
codereview_java_data_11127
* * @param member {@link Member} */ - public static void onSuccess(Member member) { final NodeState old = member.getState(); manager.getMemberAddressInfos().add(member.getAddress()); member.setState(NodeState.UP); Only add but no remove after change. * * @param member {@link Member} */ + public static void onSuccess(final ServerMemberManager manager, final Member member) { final NodeState old = member.getState(); manager.getMemberAddressInfos().add(member.getAddress()); member.setState(NodeState.UP);