comment stringlengths 22 3.02k | method_body stringlengths 46 368k | target_code stringlengths 0 181 | method_body_after stringlengths 12 368k | context_before stringlengths 11 634k | context_after stringlengths 11 632k |
|---|---|---|---|---|---|
Do we need this short timeout? We already have a TIMEOUT constant defined that can be reused. You can bump the seconds up if you need. https://github.com/Azure/azure-sdk-for-java/blob/0902c492de42ed25164e22fc55ec388041ca12df/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceB... | void singleUnnamedSessionCleanupAfterTimeout() {
Duration shortTimeout = Duration.ofSeconds(15);
ReceiverOptions receiverOptions = new ReceiverOptions(ServiceBusReceiveMode.PEEK_LOCK, 1, MAX_LOCK_RENEWAL, false, null,
2);
sessionManager = new ServiceBusSessionManager(ENTITY... | Duration shortTimeout = Duration.ofSeconds(15); | void singleUnnamedSessionCleanupAfterTimeout() {
ReceiverOptions receiverOptions = new ReceiverOptions(ServiceBusReceiveMode.PEEK_LOCK, 1, MAX_LOCK_RENEWAL, false, null,
2);
sessionManager = new ServiceBusSessionManager(ENTITY_PATH, ENTITY_TYPE, connectionProcessor,
trac... | class ServiceBusSessionManagerTest {
private static final ClientOptions CLIENT_OPTIONS = new ClientOptions();
private static final Duration TIMEOUT = Duration.ofSeconds(10);
private static final Duration MAX_LOCK_RENEWAL = Duration.ofSeconds(5);
private static final String NAMESPACE = "my-namespace-foo... | class ServiceBusSessionManagerTest {
private static final ClientOptions CLIENT_OPTIONS = new ClientOptions();
private static final Duration TIMEOUT = Duration.ofSeconds(10);
private static final Duration MAX_LOCK_RENEWAL = Duration.ofSeconds(5);
private static final String NAMESPACE = "my-namespace-foo... |
Yeah, exactly! It's meant to be used by Quarkus developers (as it's part of the runtime package, so not meant to be part of the public API) | public QuarkusBindException(List<Integer> ports) {
if (ports.isEmpty()) {
throw new IllegalStateException("ports must not be empty");
}
this.ports = ports;
} | throw new IllegalStateException("ports must not be empty"); | public QuarkusBindException(List<Integer> ports) {
if (ports.isEmpty()) {
throw new IllegalStateException("ports must not be empty");
}
this.ports = ports;
} | class QuarkusBindException extends BindException {
private final List<Integer> ports;
public QuarkusBindException(int port) {
this(Collections.singletonList(port));
}
public List<Integer> getPorts() {
return ports;
}
} | class QuarkusBindException extends BindException {
private final List<Integer> ports;
public QuarkusBindException(int port) {
this(Collections.singletonList(port));
}
public List<Integer> getPorts() {
return ports;
}
} |
Maybe we could always `pin` as before, but migrate the checking logic from `ResultPartitionManger` to `ResultPartition` as I mentioned before. I mean `ResultPartitionManager` is not aware of the external issue, the tag in `ResultPartitionManager#isReleaseExternallyManagedPartitionsOnConsumption` could be merged with `R... | void onConsumedSubpartition(int subpartitionIndex) {
if (isReleased.get()) {
return;
}
if (isManagedExternally) {
partitionManager.onConsumedPartition(this);
} else {
int refCnt = pendingReferences.decrementAndGet();
if (refCnt == 0) {
partitionManager.onConsumedPartition(this);
} else if ... | partitionManager.onConsumedPartition(this); | void onConsumedSubpartition(int subpartitionIndex) {
if (isReleased.get()) {
return;
}
LOG.debug("{}: Received release notification for subpartition {}.",
this, subpartitionIndex);
} | class ResultPartition implements ResultPartitionWriter, BufferPoolOwner {
private static final Logger LOG = LoggerFactory.getLogger(ResultPartition.class);
private final String owningTaskName;
private final ResultPartitionID partitionId;
/** Type of this partition. Defines the concrete subpartition implementati... | class ResultPartition implements ResultPartitionWriter, BufferPoolOwner {
protected static final Logger LOG = LoggerFactory.getLogger(ResultPartition.class);
private final String owningTaskName;
protected final ResultPartitionID partitionId;
/** Type of this partition. Defines the concrete subpartition implemen... |
we need to validate whether there are any whitespaces/trivia between the tokens. Can log an error and continue. | private STNode parseTrippleGTToken() {
STNode openGTToken = parseGTToken();
STNode middleLGToken = parseGTToken();
STNode endLGToken = parseGTToken();
return STNodeFactory.createTrippleGTTokenNode(openGTToken, middleLGToken, endLGToken);
} | STNode endLGToken = parseGTToken(); | private STNode parseTrippleGTToken() {
STNode openGTToken = parseGTToken();
reportInvalidShiftOperator(openGTToken);
STNode middleGTToken = parseGTToken();
reportInvalidShiftOperator(middleGTToken);
STNode endLGToken = parseGTToken();
return STNodeFactory.createTrippleG... | class BallerinaParser extends AbstractParser {
private static final OperatorPrecedence DEFAULT_OP_PRECEDENCE = OperatorPrecedence.ACTION;
protected BallerinaParser(AbstractTokenReader tokenReader) {
super(tokenReader, new BallerinaParserErrorHandler(tokenReader));
}
/**
* Start parsing t... | class BallerinaParser extends AbstractParser {
private static final OperatorPrecedence DEFAULT_OP_PRECEDENCE = OperatorPrecedence.ACTION;
protected BallerinaParser(AbstractTokenReader tokenReader) {
super(tokenReader, new BallerinaParserErrorHandler(tokenReader));
}
/**
* Start parsing t... |
Moreover, if the credential is required, we can move the validation up to buildClient() | public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) {
this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null.");
return this;
} | this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null."); | public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) {
this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null.");
return this;
} | class FormRecognizerClientBuilder {
private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id";
private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON;
private static final String ACCEPT_HEADER = "Accept";
private static final String FORM_RECOGNIZ... | class FormRecognizerClientBuilder {
private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id";
private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON;
private static final String ACCEPT_HEADER = "Accept";
private static final String FORM_RECOGNIZ... |
`baseMessage` could be returned here instead of retrieving it from the super class again. | public String getMessage() {
String baseMessage = super.getMessage();
if (this.errorCodeValue == null) {
return super.getMessage();
} else {
baseMessage = String.format(Locale.ROOT, "%s %s: {%s}", baseMessage, "ErrorCodeValue",
errorCodeValue);
}
... | return super.getMessage(); | public String getMessage() {
StringBuilder baseMessage = new StringBuilder().append(super.getMessage()).append(" ").append(ERROR_CODE)
.append(": {").append(errorCodeValue).append("}");
if (this.target == null) {
return baseMessage.toString();
} else {
return... | class TextAnalyticsException extends AzureException {
private static final long serialVersionUID = 21436310107606058L;
private final String errorCodeValue;
private final String target;
/**
* Initializes a new instance of the TextAnalyticsException class.
* @param message Text containing any ... | class TextAnalyticsException extends AzureException {
private static final long serialVersionUID = 21436310107606058L;
private static final String ERROR_CODE = "ErrorCodeValue";
private static final String TARGET = "target";
private final String errorCodeValue;
private final String target;
/**... |
duplicated code could probably be moved to a method | String bindUpdate(Class<?> clazz, String query, Map<String, Object> params) {
String bindUpdate = bindQuery(clazz, query, params);
boolean containsOperator = false;
for (String operator : UPDATE_OPERATORS) {
if (bindUpdate.contains(operator)) {
containsOperator = true... | boolean containsOperator = false; | String bindUpdate(Class<?> clazz, String query, Map<String, Object> params) {
String bindUpdate = bindQuery(clazz, query, params);
if (!containsUpdateOperator(query)) {
bindUpdate = "{'$set':" + bindUpdate + "}";
}
LOGGER.debug(bindUpdate);
return bindUpdate;
} | class ReactiveMongoOperations<QueryType, UpdateType> {
public final String ID = "_id";
private static final Logger LOGGER = Logger.getLogger(ReactiveMongoOperations.class);
private static final List<String> UPDATE_OPERATORS = Arrays.asList(
"$currentDate", "$inc", "$min", "$max", "$mul", "... | class ReactiveMongoOperations<QueryType, UpdateType> {
public final String ID = "_id";
private static final Logger LOGGER = Logger.getLogger(ReactiveMongoOperations.class);
private static final List<String> UPDATE_OPERATORS = Arrays.asList(
"$currentDate", "$inc", "$min", "$max", "$mul", "... |
Can join the apostrophe to the string itself. | public static void pushPackages(String packageName, String sourceRoot, String installToRepo, boolean noBuild) {
Path prjDirPath = LauncherUtils.getSourceRootPath(sourceRoot);
if (Files.notExists(prjDirPath.resolve(ProjectDirConstants.MANIFEST_FILE_NAME))) {
throw createLauncherExcep... | throw createLauncherException("invalid organization name provided " + "'" + orgName + "'." + " Only " + | public static void pushPackages(String packageName, String sourceRoot, String installToRepo, boolean noBuild) {
Path prjDirPath = LauncherUtils.getSourceRootPath(sourceRoot);
if (Files.notExists(prjDirPath.resolve(ProjectDirConstants.MANIFEST_FILE_NAME))) {
throw createLauncherExcep... | class PushUtils {
private static final String BALLERINA_CENTRAL_CLI_TOKEN = "https:
private static final PrintStream SYS_ERR = System.err;
private static final Path BALLERINA_HOME_PATH = RepoUtils.createAndGetHomeReposPath();
private static final Path SETTINGS_TOML_FILE_PATH = BALLERINA_HOME_PATH.resol... | class PushUtils {
private static final String BALLERINA_CENTRAL_CLI_TOKEN = "https:
private static final PrintStream SYS_ERR = System.err;
private static final Path BALLERINA_HOME_PATH = RepoUtils.createAndGetHomeReposPath();
private static final Path SETTINGS_TOML_FILE_PATH = BALLERINA_HOME_PATH.resol... |
We can use `internalKeyName` in L213, L216, and L219, right? | private static Object getStructData(BMap data, BField[] structFields, int index, BString key) {
if (structFields == null) {
ArrayValue jsonArray = new ArrayValueImpl(new BArrayType(PredefinedTypes.TYPE_JSON));
if (data != null) {
BArray dataArray = data.getArrayValue(key)... | jsonData.put(StringUtils.fromString(internalStructFields[i].getFieldName()), value); | private static Object getStructData(BMap data, BField[] structFields, int index, BString key) {
if (structFields == null) {
ArrayValue jsonArray = new ArrayValueImpl(new BArrayType(PredefinedTypes.TYPE_JSON));
if (data != null) {
BArray dataArray = data.getArrayValue(key)... | class DefaultJSONObjectGenerator implements JSONObjectGenerator {
@Override
public Object transform(MapValueImpl record) {
MapValue<BString, Object> objNode = new MapValueImpl<>(new BMapType(PredefinedTypes.TYPE_JSON));
BStructureType structType = (BStructureType) record.getType... | class DefaultJSONObjectGenerator implements JSONObjectGenerator {
@Override
public Object transform(MapValueImpl record) {
MapValue<BString, Object> objNode = new MapValueImpl<>(new BMapType(PredefinedTypes.TYPE_JSON));
BStructureType structType = (BStructureType) record.getType... |
can be shortened to `notNumberGauges.forEach(gauges::remove);` | public void report() {
DatadogHttpRequest request = new DatadogHttpRequest();
List<Gauge> notNumberGauges = new ArrayList<>();
for (Map.Entry<Gauge, DGauge> entry : gauges.entrySet()) {
DGauge g = entry.getValue();
try {
g.getMetricValue();
request.addGauge(g);
} catch (Exception e) {
... | notNumberGauges.stream().forEach(g -> gauges.remove(g)); | public void report() {
DatadogHttpRequest request = new DatadogHttpRequest();
List<Gauge> gaugesToRemove = new ArrayList<>();
for (Map.Entry<Gauge, DGauge> entry : gauges.entrySet()) {
DGauge g = entry.getValue();
try {
g.getMetricValue();
request.addGauge(g);
} catch (ClassCastExcepti... | class DatadogHttpReporter implements MetricReporter, Scheduled {
private static final Logger LOGGER = LoggerFactory.getLogger(DatadogHttpReporter.class);
private static final String HOST_VARIABLE = "<host>";
private final Map<Gauge, DGauge> gauges = new ConcurrentHashMap<>();
private final Map<Counter, DCounter>... | class DatadogHttpReporter implements MetricReporter, Scheduled {
private static final Logger LOGGER = LoggerFactory.getLogger(DatadogHttpReporter.class);
private static final String HOST_VARIABLE = "<host>";
private final Map<Gauge, DGauge> gauges = new ConcurrentHashMap<>();
private final Map<Counter, DCounter>... |
Your idea is good and easy to implement. I've created the PR#22 (https://github.com/dataArtisans/flink-benchmarks/pull/22) for benchmarks. | public boolean processInput() throws Exception {
if (!initialized) {
initialize();
}
int readingInputIndex = inputSelection.fairSelectNextIndexOutOf2(availableInputsMask, lastReadInputIndex);
if (readingInputIndex == -1) {
return waitForAvailableInput(inputSelection);
}
lastReadInputIndex = readingIn... | checkAndSetAvailable(1 - readingInputIndex); | public boolean processInput() throws Exception {
if (!isPrepared) {
prepareForProcessing();
}
int readingInputIndex = selectNextReadingInputIndex();
if (readingInputIndex == -1) {
return false;
}
lastReadInputIndex = readingInputIndex;
StreamElement recordOrMark;
if (readingInputIndex ==... | class StreamTwoInputSelectableProcessor<IN1, IN2> {
private static final Logger LOG = LoggerFactory.getLogger(StreamTwoInputSelectableProcessor.class);
private static final CompletableFuture<?> UNAVAILABLE = new CompletableFuture<>();
private final TwoInputStreamOperator<IN1, IN2, ?> streamOperator;
private fina... | class StreamTwoInputSelectableProcessor<IN1, IN2> {
private static final Logger LOG = LoggerFactory.getLogger(StreamTwoInputSelectableProcessor.class);
private static final CompletableFuture<?> UNAVAILABLE = new CompletableFuture<>();
private final TwoInputStreamOperator<IN1, IN2, ?> streamOperator;
private fina... |
Actually, why isn't this in the format string? | public String getMessage() {
String baseMessage = super.getMessage();
if (this.errorCodeValue == null) {
return super.getMessage();
} else {
baseMessage = String.format(Locale.ROOT, "%s %s: {%s}", baseMessage, "ErrorCodeValue",
errorCodeValue);
}
... | baseMessage = String.format(Locale.ROOT, "%s %s: {%s}", baseMessage, "ErrorCodeValue", | public String getMessage() {
StringBuilder baseMessage = new StringBuilder().append(super.getMessage()).append(" ").append(ERROR_CODE)
.append(": {").append(errorCodeValue).append("}");
if (this.target == null) {
return baseMessage.toString();
} else {
return... | class TextAnalyticsException extends AzureException {
private static final long serialVersionUID = 21436310107606058L;
private final String errorCodeValue;
private final String target;
/**
* Initializes a new instance of the TextAnalyticsException class.
* @param message Text containing any ... | class TextAnalyticsException extends AzureException {
private static final long serialVersionUID = 21436310107606058L;
private static final String ERROR_CODE = "ErrorCodeValue";
private static final String TARGET = "target";
private final String errorCodeValue;
private final String target;
/**... |
The most risky bug in this code is: A potential resource leak due to the improper handling of `client` when exceptions other than `NoSuchMethodException` are thrown. You can modify the code like this: ```java public Table getTable(String dbName, String tableName) { try (Timer ignored = Tracers.watchScope(EXTERNAL,... | public Table getTable(String dbName, String tableName) {
try (Timer ignored = Tracers.watchScope(EXTERNAL, "HMS.getTable")) {
RecyclableClient client = null;
StarRocksConnectorException connectionException = null;
Object[] args = {dbName, tableName};
String messag... | public Table getTable(String dbName, String tableName) {
try (Timer ignored = Tracers.watchScope(EXTERNAL, "HMS.getTable")) {
return callRPC("getTable", String.format("Failed to get table [%s.%s]", dbName, tableName),
dbName, tableName);
}
} | class relies on opening
if (Thread.currentThread().getContextClassLoader() == null) {
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
} | class relies on opening
if (Thread.currentThread().getContextClassLoader() == null) {
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
} | |
i think make this comment as a method function should be better | public void analyze(Analyzer analyzer) throws UserException {
Analyzer dummyRootAnalyzer = new Analyzer(analyzer.getCatalog(), analyzer.getContext());
QueryStmt tmpStmt = queryStmt.clone();
tmpStmt.analyze(dummyRootAnalyzer);
this.queryStmt = tmpStmt;
A... | public void analyze(Analyzer analyzer) throws UserException {
Analyzer dummyRootAnalyzer = new Analyzer(analyzer.getCatalog(), analyzer.getContext());
QueryStmt tmpStmt = queryStmt.clone();
tmpStmt.analyze(dummyRootAnalyzer);
this.queryStmt = tmpStmt;
A... | class CreateTableAsSelectStmt extends DdlStmt {
@Getter
private final CreateTableStmt createTableStmt;
@Getter
private final List<String> columnNames;
@Getter
private QueryStmt queryStmt;
@Getter
private final InsertStmt insertStmt;
public CreateTableAsSelect... | class CreateTableAsSelectStmt extends DdlStmt {
@Getter
private final CreateTableStmt createTableStmt;
@Getter
private final List<String> columnNames;
@Getter
private QueryStmt queryStmt;
@Getter
private final InsertStmt insertStmt;
protected CreateTableAsSelectStmt(CreateTableS... | |
Since the recommended line length is 120, this line can be merged with the line above. | public void visit(BLangRecordLiteral recordLiteral) {
List<BLangRecordLiteral.BLangRecordKeyValue> keyValuePairs = recordLiteral.keyValuePairs;
keyValuePairs.forEach(kv -> {
analyzeExpr(kv.valueExpr);
});
Set<Object> names = new TreeSet<>((l, r) -> l.equals(r) ? 0 : 1);
... | assigneeType, keyRef); | public void visit(BLangRecordLiteral recordLiteral) {
List<BLangRecordLiteral.BLangRecordKeyValue> keyValuePairs = recordLiteral.keyValuePairs;
keyValuePairs.forEach(kv -> {
analyzeExpr(kv.valueExpr);
});
Set<Object> names = new TreeSet<>((l, r) -> l.equals(r) ? 0 : 1);
... | class CodeAnalyzer extends BLangNodeVisitor {
private static final CompilerContext.Key<CodeAnalyzer> CODE_ANALYZER_KEY =
new CompilerContext.Key<>();
private int loopCount;
private int transactionCount;
private boolean statementReturns;
private boolean lastStatement;
private boolea... | class CodeAnalyzer extends BLangNodeVisitor {
private static final CompilerContext.Key<CodeAnalyzer> CODE_ANALYZER_KEY =
new CompilerContext.Key<>();
private int loopCount;
private int transactionCount;
private boolean statementReturns;
private boolean lastStatement;
private boolea... |
I thought that when the ContextManager is not empty, the stateContext will definitely not be empty. According to ProxyContext to obtain the internal logic of stateContext, judgment should be added. | public List<MetricFamilySamples> collect() {
if (!MetricsUtil.isClassExisted(PROXY_CLASS)) {
return Collections.emptyList();
}
Optional<GaugeMetricFamily> proxyInfo = FACTORY.createGaugeMetricFamily(MetricIds.PROXY_INFO);
if (null == ProxyContext.getInstance().getContextManag... | if (null == ProxyContext.getInstance().getContextManager() || !proxyInfo.isPresent()) { | public List<MetricFamilySamples> collect() {
if (!MetricsUtil.isClassExisted(PROXY_CLASS) || null == ProxyContext.getInstance().getContextManager()) {
return Collections.emptyList();
}
Optional<GaugeMetricFamily> proxyInfo = FACTORY.createGaugeMetricFamily(MetricIds.PROXY_INFO);
... | class ProxyInfoCollector extends Collector {
private static final String PROXY_STATE = "state";
private static final String PROXY_CLASS = "org.apache.shardingsphere.proxy.backend.context.ProxyContext";
private static final PrometheusWrapperFactory FACTORY = new PrometheusWrapperFactory();
... | class ProxyInfoCollector extends Collector {
private static final String PROXY_STATE = "state";
private static final String PROXY_CLASS = "org.apache.shardingsphere.proxy.backend.context.ProxyContext";
private static final PrometheusWrapperFactory FACTORY = new PrometheusWrapperFactory();
... |
Probably don't need the `isLhsAService` here also? | public boolean checkObjectEquivalency(BObjectType rhsType, BObjectType lhsType, Set<TypePair> unresolvedTypes) {
if (Symbols.isFlagOn(lhsType.flags, Flags.ISOLATED) && !Symbols.isFlagOn(rhsType.flags, Flags.ISOLATED)) {
return false;
}
BObjectTypeSymbol lhsStructSymbol = (BObjectTyp... | if (isLhsAService && Symbols.isResource(lhsFunc.symbol)) { | public boolean checkObjectEquivalency(BObjectType rhsType, BObjectType lhsType, Set<TypePair> unresolvedTypes) {
if (Symbols.isFlagOn(lhsType.flags, Flags.ISOLATED) && !Symbols.isFlagOn(rhsType.flags, Flags.ISOLATED)) {
return false;
}
BObjectTypeSymbol lhsStructSymbol = (BObjectTyp... | class Types {
private static final CompilerContext.Key<Types> TYPES_KEY =
new CompilerContext.Key<>();
private final ResolvedTypeBuilder typeBuilder;
private SymbolTable symTable;
private SymbolResolver symResolver;
private BLangDiagnosticLog dlog;
private Names names;
private ... | class Types {
private static final CompilerContext.Key<Types> TYPES_KEY =
new CompilerContext.Key<>();
private final ResolvedTypeBuilder typeBuilder;
private SymbolTable symTable;
private SymbolResolver symResolver;
private BLangDiagnosticLog dlog;
private Names names;
private ... |
Add a method, e.g. getJobID to reuse these codes. | public void testStopJob() throws Exception {
final MockExecutor mockExecutor = new MockExecutor();
mockExecutor.isSync = false;
String sessionId = mockExecutor.openSession("test-session");
OutputStream outputStream = new ByteArrayOutputStream(256);
try (CliClient client =
... | String jobId = matcher.group(1); | public void testStopJob() throws Exception {
final MockExecutor mockExecutor = new MockExecutor();
mockExecutor.isSync = false;
String sessionId = mockExecutor.openSession("test-session");
OutputStream outputStream = new ByteArrayOutputStream(256);
try (CliClient client =
... | class CliClientTest extends TestLogger {
private static final String INSERT_INTO_STATEMENT =
"INSERT INTO MyTable SELECT * FROM MyOtherTable";
private static final String INSERT_OVERWRITE_STATEMENT =
"INSERT OVERWRITE MyTable SELECT * FROM MyOtherTable";
@Test
public void testU... | class CliClientTest extends TestLogger {
private static final String INSERT_INTO_STATEMENT =
"INSERT INTO MyTable SELECT * FROM MyOtherTable";
private static final String INSERT_OVERWRITE_STATEMENT =
"INSERT OVERWRITE MyTable SELECT * FROM MyOtherTable";
private static final String ... |
Ah, I missed it! Will fix now | public Charset convert(String value) {
try {
return Charset.forName(value);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
} | throw new IllegalArgumentException(e); | public Charset convert(String value) {
try {
return Charset.forName(value);
} catch (Exception e) {
throw new IllegalArgumentException("Unable to create Charset from: '" + value + "'", e);
}
} | class CharsetConverter implements Converter<Charset>, Serializable {
private static final long serialVersionUID = 2320905063828247874L;
@Override
} | class CharsetConverter implements Converter<Charset>, Serializable {
private static final long serialVersionUID = 2320905063828247874L;
@Override
} |
Perhaps it's this file that should be deleted? | public void require_that_valid_tar_application_can_be_unpacked() throws IOException {
File outFile = createTarFile();
try (CompressedApplicationInputStream unpacked = streamFromTarGz(outFile)) {
File outApp = unpacked.decompress();
assertTestApp(outApp);
}
} | File outFile = createTarFile(); | public void require_that_valid_tar_application_can_be_unpacked() throws IOException {
File outFile = createTarFile();
try (CompressedApplicationInputStream unpacked = streamFromTarGz(outFile)) {
File outApp = unpacked.decompress();
assertTestApp(outApp);
}
} | class CompressedApplicationInputStreamTest {
private static void writeFileToTar(ArchiveOutputStream taos, File file) throws IOException {
taos.putArchiveEntry(taos.createArchiveEntry(file, file.getName()));
ByteStreams.copy(new FileInputStream(file), taos);
taos.closeArchiveEntry();
}
... | class CompressedApplicationInputStreamTest {
private static void writeFileToTar(ArchiveOutputStream taos, File file) throws IOException {
taos.putArchiveEntry(taos.createArchiveEntry(file, file.getName()));
ByteStreams.copy(new FileInputStream(file), taos);
taos.closeArchiveEntry();
}
... |
It seems that it is not necessary to be that complicated, I use a easier realization. | public void analyze(Analyzer analyzer) throws AnalysisException, UserException {
if (type == null) {
type = SetType.DEFAULT;
}
if (Strings.isNullOrEmpty(variable)) {
throw new AnalysisException("No variable name in set statement.");
}
if (type == SetType... | if (variable.equalsIgnoreCase(GlobalVariable.HEARTBEAT_FLAGS)) { | public void analyze(Analyzer analyzer) throws AnalysisException, UserException {
if (type == null) {
type = SetType.DEFAULT;
}
if (Strings.isNullOrEmpty(variable)) {
throw new AnalysisException("No variable name in set statement.");
}
if (type == SetType... | class SetVar {
private String variable;
private Expr value;
private SetType type;
private LiteralExpr result;
public SetVar() {
}
public SetVar(SetType type, String variable, Expr value) {
this.type = type;
this.variable = variable;
this.value = value;
if (... | class SetVar {
private String variable;
private Expr value;
private SetType type;
private LiteralExpr result;
public SetVar() {
}
public SetVar(SetType type, String variable, Expr value) {
this.type = type;
this.variable = variable;
this.value = value;
if (... |
I'll probably replace the job error with a job status some time soon, and then this won't be an issue :) | public boolean isOutOfCapacity() {
return jobError.filter(error -> error == DeploymentJobs.JobError.outOfCapacity).isPresent();
} | return jobError.filter(error -> error == DeploymentJobs.JobError.outOfCapacity).isPresent(); | public boolean isOutOfCapacity() {
return jobError.filter(error -> error == DeploymentJobs.JobError.outOfCapacity).isPresent();
} | class JobStatus {
private final DeploymentJobs.JobType type;
private final Optional<JobRun> lastTriggered;
private final Optional<JobRun> lastCompleted;
private final Optional<JobRun> firstFailing;
private final Optional<JobRun> lastSuccess;
private final Optional<DeploymentJobs.JobError> job... | class JobStatus {
private final DeploymentJobs.JobType type;
private final Optional<JobRun> lastTriggered;
private final Optional<JobRun> lastCompleted;
private final Optional<JobRun> firstFailing;
private final Optional<JobRun> lastSuccess;
private final Optional<DeploymentJobs.JobError> job... |
Currently, the method of geting the mapping is compatible. Alias and index can be queried. Therefore, the mapping relationship is not maintained. | public List<String> listTableNames(SessionContext ctx, String dbName) {
List<String> indexes = esRestClient.getIndexes().stream().distinct().collect(Collectors.toList());
esRestClient.getAliases().entrySet().stream().filter(e -> indexes.contains(e.getKey()))
.flatMap(e -> e.getValue().st... | esRestClient.getAliases().entrySet().stream().filter(e -> indexes.contains(e.getKey())) | public List<String> listTableNames(SessionContext ctx, String dbName) {
return esRestClient.listTable();
} | class EsExternalDataSource extends ExternalDataSource {
public static final String DEFAULT_DB = "default_es_db";
private static final Logger LOG = LogManager.getLogger(EsExternalDataSource.class);
private static final String PROP_HOSTS = "elasticsearch.hosts";
private static final String PROP_USERNAME ... | class EsExternalDataSource extends ExternalDataSource {
public static final String DEFAULT_DB = "default_db";
private static final Logger LOG = LogManager.getLogger(EsExternalDataSource.class);
private static final String PROP_HOSTS = "elasticsearch.hosts";
private static final String PROP_USERNAME = "... |
why here need to disable decimal256 explicitly? add some comment? | public static void initBuiltins(FunctionSet functionSet) {
for (int i = 0; i < Type.getNumericTypes().size(); i++) {
Type t1 = Type.getNumericTypes().get(i);
for (int j = 0; j < Type.getNumericTypes().size(); j++) {
Type t2 = Type.getNumericTypes().get(j);
... | functionSet.addBuiltin(ScalarFunction.createBuiltinOperator( | public static void initBuiltins(FunctionSet functionSet) {
for (int i = 0; i < Type.getNumericTypes().size(); i++) {
Type t1 = Type.getNumericTypes().get(i);
for (int j = 0; j < Type.getNumericTypes().size(); j++) {
Type t2 = Type.getNumericTypes().get(j);
... | class ArithmeticExpr extends Expr {
enum OperatorPosition {
BINARY_INFIX,
UNARY_PREFIX,
UNARY_POSTFIX,
}
public enum Operator {
MULTIPLY("*", "multiply", OperatorPosition.BINARY_INFIX, TExprOpcode.MULTIPLY),
DIVIDE("/", "divide", OperatorPosition.BINARY_INFIX, TExpr... | class ArithmeticExpr extends Expr {
enum OperatorPosition {
BINARY_INFIX,
UNARY_PREFIX,
UNARY_POSTFIX,
}
public enum Operator {
MULTIPLY("*", "multiply", OperatorPosition.BINARY_INFIX, TExprOpcode.MULTIPLY),
DIVIDE("/", "divide", OperatorPosition.BINARY_INFIX, TExpr... |
Can't we check for a flag instead? ENUM_MEMBER for example. | public void visit(BLangFiniteTypeNode finiteTypeNode, AnalyzerData data) {
boolean foundUnaryExpr = false;
boolean isErroredExprInFiniteType = false;
NodeKind valueKind;
BLangExpression value;
for (int i = 0; i < finiteTypeNode.valueSpace.size(); i++) {
value = finit... | public void visit(BLangFiniteTypeNode finiteTypeNode, AnalyzerData data) {
boolean foundUnaryExpr = false;
boolean isErroredExprInFiniteType = false;
NodeKind valueKind;
BLangExpression value;
for (int i = 0; i < finiteTypeNode.valueSpace.size(); i++) {
value = finit... | class representing a service-decl or object-ctor with service prefix
AttachPoint.Point attachedPoint;
Set<Flag> flagSet = classDefinition.flagSet;
if (flagSet.contains(Flag.OBJECT_CTOR) && flagSet.contains(Flag.SERVICE)) {
attachedPoint = AttachPoint.Point.SERVICE;
} | class representing a service-decl or object-ctor with service prefix
AttachPoint.Point attachedPoint;
Set<Flag> flagSet = classDefinition.flagSet;
if (flagSet.contains(Flag.OBJECT_CTOR) && flagSet.contains(Flag.SERVICE)) {
attachedPoint = AttachPoint.Point.SERVICE;
} | |
Or you could just use a if statement, and then you would not be using any metaspace or incurring a runtime cost. | public Object getReference(Bean<?> bean, Type beanType, CreationalContext<?> ctx) {
Objects.requireNonNull(bean, () -> "Managed Bean [" + beanType + "] is null");
Objects.requireNonNull(ctx, "CreationalContext is null");
if (bean instanceof InjectableBean && ctx instanceof CreationalContextImpl)... | Objects.requireNonNull(bean, () -> "Managed Bean [" + beanType + "] is null"); | public Object getReference(Bean<?> bean, Type beanType, CreationalContext<?> ctx) {
if (bean == null) {
throw new NullPointerException("Managed Bean [" + beanType + "] is null");
}
Objects.requireNonNull(ctx, "CreationalContext is null");
if (bean instanceof InjectableBean &&... | class BeanManagerImpl implements BeanManager {
static final LazyValue<BeanManagerImpl> INSTANCE = new LazyValue<>(BeanManagerImpl::new);
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
@Override
public Object getInjectableReference(InjectionPoint ij, CreationalContext<?> ctx) {
... | class BeanManagerImpl implements BeanManager {
static final LazyValue<BeanManagerImpl> INSTANCE = new LazyValue<>(BeanManagerImpl::new);
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
@Override
public Object getInjectableReference(InjectionPoint ij, CreationalContext<?> ctx) {
... |
I followed the same pattern used for other test cases in this specific test | public void testInferredArrayInitWithInGrpExpr() {
Object[] args = {};
Object returns = BRunUtil.invoke(compileResult, "testInferredArrayInitWithInGrpExpr", args);
Assert.assertTrue(returns instanceof BArray);
BArray arrayValue = (BArray) returns;
Assert.assertEquals(arrayValue... | Assert.assertEquals(arrayValue.getBString(2).getValue(), "a"); | public void testInferredArrayInitWithInGrpExpr() {
BRunUtil.invoke(compileResult, "testInferredArrayInitWithInGrpExpr");
} | class ArrayInitializerExprTest {
private CompileResult compileResult;
@BeforeClass
public void setup() {
compileResult = BCompileUtil.compile("test-src/statements/arrays/array-initializer-expr.bal");
}
@Test(description = "Test arrays initializer expression")
public void testArrayInit... | class ArrayInitializerExprTest {
private CompileResult compileResult;
@BeforeClass
public void setup() {
compileResult = BCompileUtil.compile("test-src/statements/arrays/array-initializer-expr.bal");
}
@Test(description = "Test arrays initializer expression")
public void testArrayInit... |
"Result". But this message is in itself quite fishy. Could we make the error conditions here more crisp? | static boolean warmup(Linguistics linguistics) {
Query query = new Query("search/?yql=select%20*%20from%20sources%20where%20title%20contains%20'xyz';");
Result result = insertQuery(query, new ParserEnvironment().setLinguistics(linguistics));
if (result != null) {
log.warning("Somethi... | log.warning("Something fishy. Reult = " + result.toString()); | static boolean warmup(Linguistics linguistics) {
Query query = new Query("search/?yql=select%20*%20from%20sources%20where%20title%20contains%20'xyz';");
Result result = insertQuery(query, new ParserEnvironment().setLinguistics(linguistics));
if (result != null) {
log.warning("Warmup ... | class MinimalQueryInserter extends Searcher {
public static final String EXTERNAL_YQL = "ExternalYql";
public static final CompoundName YQL = new CompoundName("yql");
private static final CompoundName MAX_HITS = new CompoundName("maxHits");
private static final CompoundName MAX_OFFSET = new CompoundN... | class MinimalQueryInserter extends Searcher {
public static final String EXTERNAL_YQL = "ExternalYql";
public static final CompoundName YQL = new CompoundName("yql");
private static final CompoundName MAX_HITS = new CompoundName("maxHits");
private static final CompoundName MAX_OFFSET = new CompoundN... |
Yes, `hasEntity` is returning `true` because the is an entityStream | public void handle(ResteasyReactiveRequestContext requestContext) throws Exception {
Object result = requestContext.getResult();
if (result instanceof Response) {
boolean mediaTypeAlreadyExists = false;
ResponseBuilderImpl responseBuilder;
Re... | if (existing.hasEntity() && (existing.getEntity() != null)) | public void handle(ResteasyReactiveRequestContext requestContext) throws Exception {
Object result = requestContext.getResult();
if (result instanceof Response) {
boolean mediaTypeAlreadyExists = false;
ResponseBuilderImpl responseBuilder;
Re... | class ResponseHandler implements ServerRestHandler {
@Override
private ResponseBuilderImpl fromResponse(Response response) {
Response.ResponseBuilder b = new ResponseBuilderImpl().status(response.getStatus());
if (response.hasEntity()) {
b.entity(response.getEntity());
... | class ResponseHandler implements ServerRestHandler {
@Override
private ResponseBuilderImpl fromResponse(Response response) {
Response.ResponseBuilder b = new ResponseBuilderImpl().status(response.getStatus());
if (response.hasEntity()) {
b.entity(response.getEntity());
... |
```suggestion return (int) nodes.stream().filter(node -> node.isWorking()).count(); ``` | public int workingNodes() {
return (int) nodes.stream().filter(node -> node.isWorking() == Boolean.TRUE).count();
} | return (int) nodes.stream().filter(node -> node.isWorking() == Boolean.TRUE).count(); | public int workingNodes() {
return (int) nodes.stream().filter(node -> node.isWorking() == Boolean.TRUE).count();
} | class Group {
private final int id;
private final ImmutableList<Node> nodes;
private final AtomicBoolean hasSufficientCoverage = new AtomicBoolean(true);
private final AtomicBoolean hasFullCoverage = new AtomicBoolean(true);
private final AtomicLong activeDocuments = new AtomicLong(0);
private... | class Group {
private final int id;
private final ImmutableList<Node> nodes;
private final AtomicBoolean hasSufficientCoverage = new AtomicBoolean(true);
private final AtomicBoolean hasFullCoverage = new AtomicBoolean(true);
private final AtomicLong activeDocuments = new AtomicLong(0);
private... |
Yes. Thing is that we would need to know if a refresh happened before to make the second point work. I think is easier to just let them refresh and get a new set of tokens. | public void accept(UniEmitter<? super SecurityIdentity> emitter) {
OAuth2TokenImpl token = new OAuth2TokenImpl(configContext.auth, new JsonObject());
token.principal().put("refresh_token", entry.getToken());
... | context)); | public void accept(UniEmitter<? super SecurityIdentity> emitter) {
OAuth2TokenImpl token = new OAuth2TokenImpl(configContext.auth, new JsonObject());
token.principal().put("refresh_token", refreshToken);
token.refresh(new Handler<AsyncResult<Void>>() {
... | class CodeAuthenticationMechanism extends AbstractOidcAuthenticationMechanism {
private static final Logger LOG = Logger.getLogger(CodeAuthenticationMechanism.class);
private static final String STATE_COOKIE_NAME = "q_auth";
private static final String SESSION_COOKIE_NAME = "q_session";
private static... | class CodeAuthenticationMechanism extends AbstractOidcAuthenticationMechanism {
private static final Logger LOG = Logger.getLogger(CodeAuthenticationMechanism.class);
private static final String STATE_COOKIE_NAME = "q_auth";
private static final String SESSION_COOKIE_NAME = "q_session";
private static... |
How about describing the root cause here? something like: > sort state handles by offsets to avoid building `SnappyFramedInputStream` with EOF stream. And IIUC, we only need to sort the state handles when compression is enabled? | public Void restore() throws Exception {
if (stateHandles.isEmpty()) {
return null;
}
for (OperatorStateHandle stateHandle : stateHandles) {
if (stateHandle == null) {
continue;
}
FSDataInputStream in = stateHandle.openInputStrea... | List<Map.Entry<String, OperatorStateHandle.StateMetaInfo>> entries = | public Void restore() throws Exception {
if (stateHandles.isEmpty()) {
return null;
}
for (OperatorStateHandle stateHandle : stateHandles) {
if (stateHandle == null) {
continue;
}
FSDataInputStream in = stateHandle.openInputStrea... | class OperatorStateRestoreOperation implements RestoreOperation<Void> {
private final CloseableRegistry closeStreamOnCancelRegistry;
private final ClassLoader userClassloader;
private final Map<String, PartitionableListState<?>> registeredOperatorStates;
private final Map<String, BackendWritableBroadcas... | class OperatorStateRestoreOperation implements RestoreOperation<Void> {
private final CloseableRegistry closeStreamOnCancelRegistry;
private final ClassLoader userClassloader;
private final Map<String, PartitionableListState<?>> registeredOperatorStates;
private final Map<String, BackendWritableBroadcas... |
I think this is completely wonderful. I believe then the code for `completeRequest()` should be: ``` private void completeRequest(List<RequestEntryT> failedRequestEntries, long requestStartTime) { // do completeRequest stuff including reducing the inFlightRequestsCount, etc. mailboxExecutor.tryYiel... | private void flush() {
while (inFlightRequestsCount >= maxInFlightRequests) {
try {
mailboxExecutor.yield();
} catch (InterruptedException e) {
getFatalExceptionCons()
.accept(
new InterruptedExceptio... | failedRequestEntries -> | private void flush() throws InterruptedException {
while (isInFlightRequestOrMessageLimitExceeded()) {
mailboxExecutor.yield();
}
List<RequestEntryT> batch = createNextAvailableBatch();
int batchSize = batch.size();
if (batch.size() == 0) {
return;
... | class AsyncSinkWriter<InputT, RequestEntryT extends Serializable>
implements StatefulSink.StatefulSinkWriter<InputT, BufferedRequestState<RequestEntryT>> {
private final MailboxExecutor mailboxExecutor;
private final ProcessingTimeService timeService;
/* The timestamp of the previous batch of reco... | class AsyncSinkWriter<InputT, RequestEntryT extends Serializable>
implements StatefulSink.StatefulSinkWriter<InputT, BufferedRequestState<RequestEntryT>> {
private static final int INFLIGHT_MESSAGES_LIMIT_INCREASE_RATE = 10;
private static final double INFLIGHT_MESSAGES_LIMIT_DECREASE_FACTOR = 0.5;
... |
maybe use `assertThat` instead for `assertEquals` | private void testPartitionReleaseAfterFinished(Consumer<Execution> postFinishedExecutionAction) throws Exception {
final Tuple2<JobID, Collection<ResultPartitionID>> releasedPartitions = Tuple2.of(null, null);
final SimpleAckingTaskManagerGateway taskManagerGateway = new SimpleAckingTaskManagerGateway();
taskMana... | assertEquals(executionGraph.getJobID(), releasedPartitions.f0); | private void testPartitionReleaseAfterFinished(Consumer<Execution> postFinishedExecutionAction) throws Exception {
final Tuple2<JobID, Collection<ResultPartitionID>> releasedPartitions = Tuple2.of(null, null);
final SimpleAckingTaskManagerGateway taskManagerGateway = new SimpleAckingTaskManagerGateway();
taskMana... | class ExecutionTest extends TestLogger {
@ClassRule
public static final TestingComponentMainThreadExecutor.Resource EXECUTOR_RESOURCE =
new TestingComponentMainThreadExecutor.Resource();
private final TestingComponentMainThreadExecutor testMainThreadUtil =
EXECUTOR_RESOURCE.getComponentMainThreadTestExecutor()... | class ExecutionTest extends TestLogger {
@ClassRule
public static final TestingComponentMainThreadExecutor.Resource EXECUTOR_RESOURCE =
new TestingComponentMainThreadExecutor.Resource();
private final TestingComponentMainThreadExecutor testMainThreadUtil =
EXECUTOR_RESOURCE.getComponentMainThreadTestExecutor()... |
@manuranga Do we have other construct to create StringValue or is it ok to use this directly? | public static Object bindDataToIntendedType(byte[] data, BType intendedType) {
int dataParamTypeTag = intendedType.getTag();
Object dispatchedData;
switch (dataParamTypeTag) {
case TypeTags.STRING_TAG:
dispatchedData = new BmpStringValue(new String(data, StandardChars... | dispatchedData = new BmpStringValue(new String(data, StandardCharsets.UTF_8)); | public static Object bindDataToIntendedType(byte[] data, BType intendedType) {
int dataParamTypeTag = intendedType.getTag();
Object dispatchedData;
switch (dataParamTypeTag) {
case TypeTags.STRING_TAG:
dispatchedData = StringUtils.fromString(new String(data, StandardC... | class Utils {
public static ErrorValue createNatsError(String nuid, String detailedErrorMessage) {
MapValue<String, Object> errorDetailRecord = BallerinaValues
.createRecordValue(Constants.NATS_PACKAGE_ID, Constants.NATS_ERROR_DETAIL_RECORD);
MapValue<String, Object> populatedDetail... | class Utils {
public static ErrorValue createNatsError(String nuid, String detailedErrorMessage) {
MapValue<String, Object> errorDetailRecord = BallerinaValues
.createRecordValue(Constants.NATS_PACKAGE_ID, Constants.NATS_ERROR_DETAIL_RECORD);
MapValue<String, Object> populatedDetail... |
@michalvavrik Sure, the question is, is this extra check done inside Permission related to the authorization ? | public boolean implies(Permission permission) {
if (permission instanceof WorkdayPermission) {
WorkdayPermission that = (WorkdayPermission) permission;
if (that.getName().equals("worker") && that.getActions().contains("adult")) {
final Work... | if (that.getName().equals("worker") && that.getActions().contains("adult")) { | public boolean implies(Permission permission) {
if (permission instanceof WorkdayPermission) {
WorkdayPermission that = (WorkdayPermission) permission;
if (that.getName().equals("worker") && that.getActions().contains("adult")) {
final Work... | class must have a formal parameter {@link String} | class must have a formal parameter {@link String} |
Yes, that's a good point. However, it is currently used by production code and a lot of testing code paths. I would move this issue out of the scope of this PR. WDYT? | public ExecutionAttemptID() {
this(new ExecutionVertexID(), 0);
} | this(new ExecutionVertexID(), 0); | public ExecutionAttemptID() {
this(new ExecutionVertexID(new JobVertexID(), 0), 0);
} | class ExecutionAttemptID implements java.io.Serializable {
private static final long serialVersionUID = -1169683445778281344L;
private final ExecutionVertexID executionVertexID;
private final int attemptNumber;
/**
* Get a random execution attempt id.
*/
public ExecutionAttemptID(ExecutionVertexID execut... | class ExecutionAttemptID implements java.io.Serializable {
private static final long serialVersionUID = -1169683445778281344L;
private final ExecutionVertexID executionVertexId;
private final int attemptNumber;
/**
* Get a random execution attempt id.
*/
public ExecutionAttemptID(ExecutionVertexID execut... |
Then we have to do in L5127 ``` arrayLiteral.exprs.add(addConversionExprIfRequired(restArg, elemType)); ``` I'd rather complete the list and then set it. | public void visit(BLangFunction funcNode) {
SymbolEnv funcEnv = SymbolEnv.createFunctionEnv(funcNode, funcNode.symbol.scope, env);
if (!funcNode.interfaceFunction) {
addReturnIfNotPresent(funcNode);
}
funcNode.originalFuncSymbol = funcNode.symbol;
funcNode.s... | List<BLangExpression> exprs = new ArrayList<>(); | public void visit(BLangFunction funcNode) {
SymbolEnv funcEnv = SymbolEnv.createFunctionEnv(funcNode, funcNode.symbol.scope, env);
if (!funcNode.interfaceFunction) {
addReturnIfNotPresent(funcNode);
}
funcNode.originalFuncSymbol = funcNode.symbol;
funcNode.s... | class Desugar extends BLangNodeVisitor {
private static final CompilerContext.Key<Desugar> DESUGAR_KEY =
new CompilerContext.Key<>();
private static final String QUERY_TABLE_WITH_JOIN_CLAUSE = "queryTableWithJoinClause";
private static final String QUERY_TABLE_WITHOUT_JOIN_CLAUSE = "queryTableW... | class Desugar extends BLangNodeVisitor {
private static final CompilerContext.Key<Desugar> DESUGAR_KEY =
new CompilerContext.Key<>();
private static final String QUERY_TABLE_WITH_JOIN_CLAUSE = "queryTableWithJoinClause";
private static final String QUERY_TABLE_WITHOUT_JOIN_CLAUSE = "queryTableW... |
Yeah I wasn't sure how this architecture was intended to work. I feel like we should have a consistent way to set up the configuration but we do not yet. So again I opted to preserve the existing behavior as much as possible. | public void stop() {
if (oldSystemProps != null) {
for (Map.Entry<String, String> e : oldSystemProps.entrySet()) {
if (e.getValue() == null) {
System.clearProperty(e.getKey());
} else {
System.setProperty(e.getKey(), e.getValue(... | cpr.releaseConfig(cpr.getConfig()); | public void stop() {
if (oldSystemProps != null) {
for (Map.Entry<String, String> e : oldSystemProps.entrySet()) {
if (e.getValue() == null) {
System.clearProperty(e.getKey());
} else {
System.setProperty(e.getKey(), e.getValue(... | class TestResourceManager {
private final List<QuarkusTestResourceLifecycleManager> testResources;
private Map<String, String> oldSystemProps;
public TestResourceManager(Class<?> testClass) {
testResources = getTestResources(testClass);
}
public Map<String, String> start() {
Map<S... | class TestResourceManager {
private final List<QuarkusTestResourceLifecycleManager> testResources;
private Map<String, String> oldSystemProps;
public TestResourceManager(Class<?> testClass) {
testResources = getTestResources(testClass);
}
public Map<String, String> start() {
Map<S... |
Just curious, was there a case when it actually was a `String`? Which option was that? | public String[] getOptionValues(String name) {
final Object o = options.get(name);
return o == null ? null : o instanceof String ? new String[] { o.toString() } : (String[]) o;
} | return o == null ? null : o instanceof String ? new String[] { o.toString() } : (String[]) o; | public String[] getOptionValues(String name) {
final Object o = options.get(name);
return o == null ? null : o instanceof String ? new String[] { o.toString() } : (String[]) o;
} | class BootstrapMavenOptions {
public static Map<String, Object> parse(String cmdLine) {
if (cmdLine == null) {
return Collections.emptyMap();
}
final String[] args = cmdLine.split("\\s+");
if (args.length == 0) {
return Collections.emptyMap();
}
... | class BootstrapMavenOptions {
public static Map<String, Object> parse(String cmdLine) {
if (cmdLine == null) {
return Collections.emptyMap();
}
final String[] args = cmdLine.split("\\s+");
if (args.length == 0) {
return Collections.emptyMap();
}
... |
We should use logger here and at other places in this class. It is available from TestSuiteBase, which gets it from DocumentClientTest | public void beforeClass() throws Exception {
System.out.println("OrderbyDocumentQueryTest.beforeClass");
client = clientBuilder().build();
createdDatabase = getSharedCosmosDatabase(client);
createdCollection = getSharedMultiPartitionCosmosContainer(client);
System.out.println("be... | System.out.println("OrderbyDocumentQueryTest.beforeClass"); | public void beforeClass() throws Exception {
client = clientBuilder().build();
createdDatabase = getSharedCosmosDatabase(client);
createdCollection = getSharedMultiPartitionCosmosContainer(client);
truncateCollection(createdCollection);
List<Map<String, Object>> keyValuePropsLis... | class OrderbyDocumentQueryTest extends TestSuiteBase {
private final double minQueryRequestChargePerPartition = 2.0;
private CosmosClient client;
private CosmosContainer createdCollection;
private CosmosDatabase createdDatabase;
private List<CosmosItemProperties> createdDocuments = new ArrayList<>(... | class OrderbyDocumentQueryTest extends TestSuiteBase {
private final double minQueryRequestChargePerPartition = 2.0;
private CosmosClient client;
private CosmosContainer createdCollection;
private CosmosDatabase createdDatabase;
private List<CosmosItemProperties> createdDocuments = new ArrayList<>(... |
Please use `Entry` instead of `Map.Entry` | public void init(final ShardingSphereMetaData metaData, final SQLStatement sqlStatement) {
resource = metaData.getResource();
dataSourcePropsMap = new LinkedHashMap<>(metaData.getResource().getDataSources().size(), 1);
for (Map.Entry<String, DataSource> entry : metaData.getResource().getDataSour... | for (Map.Entry<String, DataSource> entry : metaData.getResource().getDataSources().entrySet()) { | public void init(final ShardingSphereMetaData metaData, final SQLStatement sqlStatement) {
resource = metaData.getResource();
dataSourcePropsMap = new LinkedHashMap<>(metaData.getResource().getDataSources().size(), 1);
for (Entry<String, DataSource> entry : metaData.getResource().getDataSources(... | class DataSourceQueryResultSet implements DistSQLResultSet {
private static final String CONNECTION_TIMEOUT_MILLISECONDS = "connectionTimeoutMilliseconds";
private static final String IDLE_TIMEOUT_MILLISECONDS = "idleTimeoutMilliseconds";
private static final String MAX_LIFETIME_MILLISECONDS ... | class DataSourceQueryResultSet implements DistSQLResultSet {
private static final String CONNECTION_TIMEOUT_MILLISECONDS = "connectionTimeoutMilliseconds";
private static final String IDLE_TIMEOUT_MILLISECONDS = "idleTimeoutMilliseconds";
private static final String MAX_LIFETIME_MILLISECONDS ... |
I would add a comment here to explain what we're doing. | public void startDev() {
Project project = getProject();
QuarkusPluginExtension extension = (QuarkusPluginExtension) project.getExtensions().findByName("quarkus");
if (!getSourceDir().isDirectory()) {
throw new GradleException("The `src/main/java` directory is required, please crea... | args.add(extension.outputDirectory().getAbsolutePath() + "," + extension.outputConfigDirectory().getAbsolutePath()); | public void startDev() {
Project project = getProject();
QuarkusPluginExtension extension = (QuarkusPluginExtension) project.getExtensions().findByName("quarkus");
if (!getSourceDir().isDirectory()) {
throw new GradleException("The `src/main/java` directory is required, please crea... | class QuarkusDev extends QuarkusTask {
private Set<File> filesIncludedInClasspath = new HashSet<>();
private String debug;
private File buildDir;
private String sourceDir;
private String jvmArgs;
private boolean preventnoverify = false;
public QuarkusDev() {
super("Development... | class QuarkusDev extends QuarkusTask {
private Set<File> filesIncludedInClasspath = new HashSet<>();
private String debug;
private File buildDir;
private String sourceDir;
private String jvmArgs;
private boolean preventnoverify = false;
public QuarkusDev() {
super("Development... |
It's required, I have analyzed [here](https://github.com/apache/flink/pull/19993#discussion_r901261999). > For old code, the unit-test gets stuck in the second dataFuture.get(). After the change, the unit-test worked fine. | public void testCanBeClosed() throws Exception {
long checkpointId = 1L;
ChannelStateWriteRequestDispatcher processor =
new ChannelStateWriteRequestDispatcherImpl(
"dummy task",
0,
getStreamFactoryFactory(),
... | new CompletableFuture<>())); | public void testCanBeClosed() throws Exception {
long checkpointId = 1L;
ChannelStateWriteRequestDispatcher processor =
new ChannelStateWriteRequestDispatcherImpl(
"dummy task",
0,
getStreamFactoryFactory(),
... | class ChannelStateWriteRequestExecutorImplTest {
private static final String TASK_NAME = "test task";
@Test(expected = IllegalStateException.class)
public void testCloseAfterSubmit() throws Exception {
testCloseAfterSubmit(ChannelStateWriteRequestExecutor::submit);
}
@Test(expected = Ille... | class ChannelStateWriteRequestExecutorImplTest {
private static final String TASK_NAME = "test task";
@Test(expected = IllegalStateException.class)
public void testCloseAfterSubmit() throws Exception {
testCloseAfterSubmit(ChannelStateWriteRequestExecutor::submit);
}
@Test(expected = Ille... |
loadAzureVmMetaData is part of init and not meant to call multiple times , why we used AtomicReference here ? | private void loadAzureVmMetaData() {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null) {
this.populateAzureVmMetaData(metadataSnapshot);
return;
}
URI targetEndpoint = null;
try {
targetEndpoint ... | AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get(); | private void loadAzureVmMetaData() {
AzureVMMetadata metadataSnapshot = azureVmMetaDataSingleton.get();
if (metadataSnapshot != null) {
this.populateAzureVmMetaData(metadataSnapshot);
return;
}
URI targetEndpoint = null;
try {
targetEndpoint ... | class ClientTelemetry {
public final static int ONE_KB_TO_BYTES = 1024;
public final static int REQUEST_LATENCY_MAX_MILLI_SEC = 300000;
public final static int REQUEST_LATENCY_SUCCESS_PRECISION = 4;
public final static int REQUEST_LATENCY_FAILURE_PRECISION = 2;
public final static String REQUEST_LAT... | class ClientTelemetry {
public final static int ONE_KB_TO_BYTES = 1024;
public final static int REQUEST_LATENCY_MAX_MILLI_SEC = 300000;
public final static int REQUEST_LATENCY_SUCCESS_PRECISION = 4;
public final static int REQUEST_LATENCY_FAILURE_PRECISION = 2;
public final static String REQUEST_LAT... |
> the only reason for collecting the retrieved Gauge instances to a Set is to validate that none of them are null Here, we are not checking for null; rather, we are examining whether there are duplicates among the five `Gauge`s to ensure that no metric has been registered multiple times. | void testWatermarkMetrics() throws Exception {
final OneInputStreamTaskTestHarness<String, String> testHarness =
new OneInputStreamTaskTestHarness<>(
OneInputStreamTask::new,
BasicTypeInfo.STRING_TYPE_INFO,
BasicTypeInfo.STR... | assertThat( | void testWatermarkMetrics() throws Exception {
final OneInputStreamTaskTestHarness<String, String> testHarness =
new OneInputStreamTaskTestHarness<>(
OneInputStreamTask::new,
BasicTypeInfo.STRING_TYPE_INFO,
BasicTypeInfo.STR... | class DuplicatingOperator extends AbstractStreamOperator<String>
implements OneInputStreamOperator<String, String> {
@Override
public void processElement(StreamRecord<String> element) {
output.collect(element);
output.collect(element);
}
} | class DuplicatingOperator extends AbstractStreamOperator<String>
implements OneInputStreamOperator<String, String> {
@Override
public void processElement(StreamRecord<String> element) {
output.collect(element);
output.collect(element);
}
} |
add comment to explain why must replace here | private static List<RewriteJob> buildAnalyzeJobs(Optional<CustomTableResolver> customTableResolver) {
return jobs(
topDown(new AnalyzeCTE()),
topDown(new EliminateLogicalSelectHint()),
bottomUp(
new BindRelation(customTableResolver),
... | bottomUp(new SemiJoinCommute()), | private static List<RewriteJob> buildAnalyzeJobs(Optional<CustomTableResolver> customTableResolver) {
return jobs(
topDown(new AnalyzeCTE()),
topDown(new EliminateLogicalSelectHint()),
bottomUp(
new BindRelation(customTableResolver),
... | class Analyzer extends AbstractBatchJobExecutor {
public static final List<RewriteJob> DEFAULT_ANALYZE_JOBS = buildAnalyzeJobs(Optional.empty());
public static final List<RewriteJob> DEFAULT_ANALYZE_VIEW_JOBS = buildAnalyzeViewJobs(Optional.empty());
private final List<RewriteJob> jobs;
/**
* Ex... | class Analyzer extends AbstractBatchJobExecutor {
public static final List<RewriteJob> DEFAULT_ANALYZE_JOBS = buildAnalyzeJobs(Optional.empty());
public static final List<RewriteJob> DEFAULT_ANALYZE_VIEW_JOBS = buildAnalyzeViewJobs(Optional.empty());
private final List<RewriteJob> jobs;
/**
* Ex... |
Yes, but afaik, it would require quite a bit of refactoring, which I'd do in another PR. | public void testClosingWithBlockedEmitter() throws Exception {
final Object lock = new Object();
ArgumentCaptor<Throwable> failureReason = ArgumentCaptor.forClass(Throwable.class);
MockEnvironment environment = createMockEnvironment();
StreamTask<?, ?> containingTask = mock(StreamTask.class);
TaskMailboxIm... | when(containingTask.getTaskMailboxExecutor(any())).thenReturn(new MailboxExecutorImpl(mailbox)); | public void testClosingWithBlockedEmitter() throws Exception {
JobVertex chainedVertex = createChainedVertex(new MyAsyncFunction(), new EmitterBlockingFunction());
final OneInputStreamTaskTestHarness<Integer, Integer> testHarness = new OneInputStreamTaskTestHarness<>(
OneInputStreamTask::new,
1, 1,
Ba... | class StreamRecordComparator implements Comparator<Object> {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Watermark || o2 instanceof Watermark) {
return 0;
} else {
StreamRecord<Integer> sr0 = (StreamRecord<Integer>) o1;
StreamRecord<Integer> sr1 = (StreamRecord<Integer>)... | class StreamRecordComparator implements Comparator<Object> {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Watermark || o2 instanceof Watermark) {
return 0;
} else {
StreamRecord<Integer> sr0 = (StreamRecord<Integer>) o1;
StreamRecord<Integer> sr1 = (StreamRecord<Integer>)... |
Lets rename exprs to indexExprs for readability | private void assignValueToArrayMapAccessExpr(BValue rValue, ArrayMapAccessExpr lExpr) {
ArrayMapAccessExpr accessExpr = lExpr;
if (!(accessExpr.getType() == BTypes.typeMap)) {
BArray arrayVal = (BArray) accessExpr.getRExpr().execute(this);
Expression[] exprs = accessExpr.getInde... | Expression[] exprs = accessExpr.getIndexExprs(); | private void assignValueToArrayMapAccessExpr(BValue rValue, ArrayMapAccessExpr lExpr) {
ArrayMapAccessExpr accessExpr = lExpr;
if (!(accessExpr.getType() == BTypes.typeMap)) {
BArray arrayVal = (BArray) accessExpr.getRExpr().execute(this);
Expression[] indexExprs = accessExpr.ge... | class since Unary does not need BiFunction
return unaryExpr.getEvalFunc().apply(null, rValue);
}
@Override
public BValue visit(BinaryExpression binaryExpr) {
Expression rExpr = binaryExpr.getRExpr();
BValueType rValue = (BValueType) rExpr.execute(this);
Expression lExpr = b... | class since Unary does not need BiFunction
return unaryExpr.getEvalFunc().apply(null, rValue);
}
@Override
public BValue visit(BinaryExpression binaryExpr) {
Expression rExpr = binaryExpr.getRExpr();
BValueType rValue = (BValueType) rExpr.execute(this);
Expression lExpr = b... |
That sounds good. Maybe add a comment on the bug or here with a comment on what are the limitations. Previously we had a conversation about not receiving progress updates as an indicator of sdk harness failure. We could consider that as an option. | public void unregisterWorkerClient(FnApiControlClient controlClient) {
WorkCountingSdkWorkerHarness worker = workerMap.remove(controlClient);
if (worker != null) {
worker.closed.set(true);
workers.remove(worker);
}
LOG.info("Unregistered Control client {}", worker != null... | sdkHarnessesAreHealthy.set(false); | public void unregisterWorkerClient(FnApiControlClient controlClient) {
WorkCountingSdkWorkerHarness worker = workerMap.remove(controlClient);
if (worker != null) {
worker.closed.set(true);
workers.remove(worker);
}
LOG.info("Unregistered Control client {}", worker != null... | class WorkBalancingSdkHarnessRegistry implements SdkHarnessRegistry {
private static final Logger LOG =
LoggerFactory.getLogger(WorkBalancingSdkHarnessRegistry.class);
private final ApiServiceDescriptor stateApiServiceDescriptor;
private final GrpcStateService beamFnStateService;
private final B... | class WorkBalancingSdkHarnessRegistry implements SdkHarnessRegistry {
private static final Logger LOG =
LoggerFactory.getLogger(WorkBalancingSdkHarnessRegistry.class);
private final ApiServiceDescriptor stateApiServiceDescriptor;
private final GrpcStateService beamFnStateService;
private final B... |
Even if there is no clustering shouldn't we still set the event bus options? | private static VertxOptions convertToVertxOptions(VertxConfiguration conf, boolean allowClustering) {
VertxOptions options = new VertxOptions();
if (allowClustering) {
setEventBusOptions(conf, options);
initializeClusterOptions(conf, options);
}
Str... | setEventBusOptions(conf, options); | private static VertxOptions convertToVertxOptions(VertxConfiguration conf, boolean allowClustering) {
VertxOptions options = new VertxOptions();
if (allowClustering) {
setEventBusOptions(conf, options);
initializeClusterOptions(conf, options);
}
Str... | class VertxCoreRecorder {
private static final Pattern COMMA_PATTERN = Pattern.compile(",");
static volatile VertxSupplier vertx;
static volatile Vertx webVertx;
public Supplier<Vertx> configureVertx(BeanContainer container, VertxConfiguration config,
LaunchMode launchMode, ShutdownC... | class VertxCoreRecorder {
private static final Pattern COMMA_PATTERN = Pattern.compile(",");
static volatile VertxSupplier vertx;
static volatile Vertx webVertx;
public Supplier<Vertx> configureVertx(BeanContainer container, VertxConfiguration config,
LaunchMode launchMode, ShutdownC... |
+1 changed it to emit results in processElement as well. Could not measure a noticeable difference in my test though. | public void finishBundle() {
try {
remoteBundle.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
KV<String, OutputT> result;
while ((result = outputQueue.poll()) != null) {
outputManager.output(outputMap.get(result.getKey()), (Wind... | public void finishBundle() {
try {
remoteBundle.close();
emitResults();
} catch (Exception e) {
throw new RuntimeException("Failed to finish remote bundle", e);
}
} | class SdkHarnessDoFnRunner implements DoFnRunner<InputT, OutputT> {
@Override
public void startBundle() {
checkState(
stageBundleFactory != null, "%s not yet prepared", StageBundleFactory.class.getName());
checkState(
stateRequestHandler != null, "%s not yet prepared", StateReque... | class SdkHarnessDoFnRunner implements DoFnRunner<InputT, OutputT> {
@Override
public void startBundle() {
checkState(
stageBundleFactory != null, "%s not yet prepared", StageBundleFactory.class.getName());
checkState(
stateRequestHandler != null, "%s not yet prepared", StateReque... | |
Can't we return here? Or we have to unnecessarily check the tag in L3701 and return? | private void addAsRecordTypeDefinition(BType type, Location pos) {
if (type.tag == TypeTags.UNION) {
for (BType memberType : ((BUnionType) type).getMemberTypes()) {
addAsRecordTypeDefinition(memberType, pos);
}
}
if (type.tag != TypeTags.RECORD) {
... | BRecordType recordType = (BRecordType) type; | private void addAsRecordTypeDefinition(BType type, Location pos) {
if (type.tag == TypeTags.UNION) {
for (BType memberType : ((BUnionType) type).getMemberTypes()) {
addAsRecordTypeDefinition(memberType, pos);
}
return;
}
if (type.tag != TypeTag... | class definition node for which the initializer is created
* @param env The env for the type node
* @return The generated initializer method
*/
private BLangFunction createGeneratedInitializerFunction(BLangClassDefinition classDefinition, SymbolEnv env) {
BLangFunction generatedIni... | class definition node for which the initializer is created
* @param env The env for the type node
* @return The generated initializer method
*/
private BLangFunction createGeneratedInitializerFunction(BLangClassDefinition classDefinition, SymbolEnv env) {
BLangFunction generatedIni... |
This anonymous class is used twice, can you extract it as a private static class and remove the duplication? | public void testWriteQueue() throws Exception {
final int maxNumRecords = 1000;
List<RabbitMqMessage> data =
IntStream.range(0, maxNumRecords)
.mapToObj(i -> new RabbitMqMessage(("Test " + i).getBytes(StandardCharsets.UTF_8)))
.collect(Collectors.toList());
p.apply(Create.of(... | new DefaultConsumer(channel) { | public void testWriteQueue() throws Exception {
final int maxNumRecords = 1000;
List<RabbitMqMessage> data =
generateRecords(maxNumRecords)
.stream()
.map(bytes -> new RabbitMqMessage(bytes))
.collect(Collectors.toList());
p.apply(Create.of(data))
.apply(
... | class RabbitMqIOTest implements Serializable {
private static final Logger LOG = LoggerFactory.getLogger(RabbitMqIOTest.class);
private static int port;
@ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule public transient TestPipeline p = TestPipeline.create();
private s... | class RabbitMqIOTest implements Serializable {
private static final Logger LOG = LoggerFactory.getLogger(RabbitMqIOTest.class);
private static int port;
@ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule public transient TestPipeline p = TestPipeline.create();
private s... |
run `./gradlew spotlessApply` to fix style issues. | public void testAnyValueFunction() throws Exception {
pipeline.enableAbandonedNodeEnforcement(false);
Schema schema =
Schema.builder().addInt32Field("key").addInt32Field("col").build();
PCollection<Row> inputRows =
pipeline
.apply(
Cr... | TestUtils.rowsBuilderOf(schema) | public void testAnyValueFunction() throws Exception {
pipeline.enableAbandonedNodeEnforcement(false);
Schema schema = Schema.builder().addInt32Field("key").addInt32Field("col").build();
PCollection<Row> inputRows =
pipeline
.apply(
Create.of(
TestUti... | class BeamSqlDslAggregationTest extends BeamSqlDslBase {
public PCollection<Row> boundedInput3;
@Before
public void setUp() {
Schema schemaInTableB =
Schema.builder()
.addInt32Field("f_int")
.addDoubleField("f_double")
.addInt32Field("f_int2")
.addDecim... | class BeamSqlDslAggregationTest extends BeamSqlDslBase {
public PCollection<Row> boundedInput3;
@Before
public void setUp() {
Schema schemaInTableB =
Schema.builder()
.addInt32Field("f_int")
.addDoubleField("f_double")
.addInt32Field("f_int2")
.addDecim... |
Aren't these all `validateTransform()` calls? | public void testReadValidationFailsMissingConfiguration() {
HadoopInputFormatIO.Read<String, String> read = HadoopInputFormatIO.<String, String>read();
thrown.expect(NullPointerException.class);
read.validate(PipelineOptionsFactory.create());
} | read.validate(PipelineOptionsFactory.create()); | public void testReadValidationFailsMissingConfiguration() {
HadoopInputFormatIO.Read<String, String> read = HadoopInputFormatIO.<String, String>read();
thrown.expect(NullPointerException.class);
read.validateTransform();
} | class HadoopInputFormatIOTest {
static SerializableConfiguration serConf;
static SimpleFunction<Text, String> myKeyTranslate;
static SimpleFunction<Employee, String> myValueTranslate;
@Rule public final transient TestPipeline p = TestPipeline.create();
@Rule public ExpectedException thrown = ExpectedExceptio... | class HadoopInputFormatIOTest {
static SerializableConfiguration serConf;
static SimpleFunction<Text, String> myKeyTranslate;
static SimpleFunction<Employee, String> myValueTranslate;
@Rule public final transient TestPipeline p = TestPipeline.create();
@Rule public ExpectedException thrown = ExpectedExceptio... |
I assume what you are saying if on the ServiceEndpoint we had successful requests very recently let's throw away the failed channel rather faster because chances are good that other channels are healthy? | private String transitTimeoutValidation(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) {
String transitTimeoutValidationMessage = StringUtils.EMPTY;
if (this.timeoutDetectionEnabled && timestamps.transitTimeoutCount() > 0) {
final Optional<R... | private String transitTimeoutValidation(Timestamps timestamps, Instant currentTime, RntbdRequestManager requestManager, Channel channel) {
String transitTimeoutValidationMessage = StringUtils.EMPTY;
if (this.timeoutDetectionEnabled && timestamps.transitTimeoutCount() > 0) {
... | class RntbdClientChannelHealthChecker implements ChannelHealthChecker {
private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class);
private static final long recentReadWindowInNanos = 1_000_000_000L;
private static fin... | class RntbdClientChannelHealthChecker implements ChannelHealthChecker {
private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class);
private static final long recentReadWindowInNanos = 1_000_000_000L;
private static fin... | |
What happens service side if it receives an empty `clientFilters` list? The other option would be to defer this instantiation and only perform it when `addFilter` is called and `clientFilters == null` | public FeatureFlagConfigurationSetting(String featureId, boolean isEnabled) {
this.featureId = featureId;
this.isEnabled = isEnabled;
super.setKey(KEY_PREFIX + featureId);
super.setContentType(FEATURE_FLAG_CONTENT_TYPE);
clientFilters = new ArrayList<>();
} | clientFilters = new ArrayList<>(); | public FeatureFlagConfigurationSetting(String featureId, boolean isEnabled) {
this.featureId = featureId;
this.isEnabled = isEnabled;
super.setKey(KEY_PREFIX + featureId);
super.setContentType(FEATURE_FLAG_CONTENT_TYPE);
} | class FeatureFlagConfigurationSetting extends ConfigurationSetting {
private static final ClientLogger LOGGER = new ClientLogger(FeatureFlagConfigurationSetting.class);
private static final String FEATURE_FLAG_CONTENT_TYPE = "application/vnd.microsoft.appconfig.ff+json;charset=utf-8";
private String featur... | class FeatureFlagConfigurationSetting extends ConfigurationSetting {
private static final ClientLogger LOGGER = new ClientLogger(FeatureFlagConfigurationSetting.class);
private static final String FEATURE_FLAG_CONTENT_TYPE = "application/vnd.microsoft.appconfig.ff+json;charset=utf-8";
private String featur... |
By defining two functions like this, we can remove the last parameter. ```ballerina private void addTypeCastForBinaryExprA(BLangBinaryExpr binaryExpr, BType targetType, BType sourceType, boolean isRhsExpr) { if (sourceType.tag == TypeTags.UNION && sourceType.isNull... | private BLangBlockStmt desugarForeachToWhile(BLangForeach foreach, BLangSimpleVariableDef varDef) {
... | private void addTypeCastForBinaryExpr(BLangBinaryExpr binaryExpr, BType targetType, BType sourceType, | private BLangBlockStmt desugarForeachToWhile(BLangForeach foreach, BLangSimpleVariableDef varDef) {
... | class definition node for which the initializer is created
* @param env The env for the type node
* @return The generated initializer method
*/
private BLangFunction createGeneratedInitializerFunction(BLangClassDefinition classDefinition, SymbolEnv env) {
BLangFunction generatedIni... | class definition node for which the initializer is created
* @param env The env for the type node
* @return The generated initializer method
*/
private BLangFunction createGeneratedInitializerFunction(BLangClassDefinition classDefinition, SymbolEnv env) {
BLangFunction generatedIni... |
```suggestion errStream.println("Warning: Cache generation skipped for platform dependencies with 'provided' scope"); ``` | static boolean pullDependencyPackages(String orgName, String packageName, String version) {
Path ballerinaUserHomeDirPath = ProjectUtils.createAndGetHomeReposPath();
Path centralRepositoryDirPath = ballerinaUserHomeDirPath.resolve(ProjectConstants.REPOSITORIES_DIR)
.resolve(ProjectConsta... | errStream.println("Warning: Cache generation skipped due to platform dependencies with 'provided' scope"); | static boolean pullDependencyPackages(String orgName, String packageName, String version) {
Path ballerinaUserHomeDirPath = ProjectUtils.createAndGetHomeReposPath();
Path centralRepositoryDirPath = ballerinaUserHomeDirPath.resolve(ProjectConstants.REPOSITORIES_DIR)
.resolve(ProjectConsta... | class CommandUtil {
public static final String ORG_NAME = "ORG_NAME";
public static final String PKG_NAME = "PKG_NAME";
public static final String DIST_VERSION = "DIST_VERSION";
public static final String TOOL_ID = "TOOL_ID";
public static final String USER_HOME = "user.home";
public static fina... | class CommandUtil {
public static final String ORG_NAME = "ORG_NAME";
public static final String PKG_NAME = "PKG_NAME";
public static final String DIST_VERSION = "DIST_VERSION";
public static final String TOOL_ID = "TOOL_ID";
public static final String USER_HOME = "user.home";
public static fina... |
It might also be better for the new constructor to just take a long and we calculate the share usage in bytes in the constructor. | private Response<ShareStatistics> mapGetStatisticsResponse(SharesGetStatisticsResponse response) {
ShareStatistics shareStatistics =
new ShareStatistics((int) (response.getValue().getShareUsageBytes() / (Constants.GB)),
response.getValue().getShareUsageBytes());
return new S... | new ShareStatistics((int) (response.getValue().getShareUsageBytes() / (Constants.GB)), | private Response<ShareStatistics> mapGetStatisticsResponse(SharesGetStatisticsResponse response) {
ShareStatistics shareStatistics =
new ShareStatistics(response.getValue().getShareUsageBytes());
return new SimpleResponse<>(response, shareStatistics);
} | class ShareAsyncClient {
private final ClientLogger logger = new ClientLogger(ShareAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String snapshot;
private final String accountName;
private final ShareServiceVersion se... | class ShareAsyncClient {
private final ClientLogger logger = new ClientLogger(ShareAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String snapshot;
private final String accountName;
private final ShareServiceVersion se... |
> `#maybeCreate` already handles potential existing one. That's the "maybe" part. This code path is hit multiple times but if this code is allowed to run multiple times it will create duplicate sets of metadata. > TBH, I'm not sure why these get registered instead of created anyway. register and create do the same t... | private void setUpDeploymentConfiguration() {
if (project.getConfigurations().findByName(this.deploymentConfigurationName) == null) {
project.getConfigurations().register(this.deploymentConfigurationName, configuration -> {
Configuration enforcedPlatforms = this.getPlatformConfigurat... | project.getConfigurations().register(this.deploymentConfigurationName, configuration -> { | private void setUpDeploymentConfiguration() {
if (project.getConfigurations().findByName(this.deploymentConfigurationName) == null) {
project.getConfigurations().create(this.deploymentConfigurationName, configuration -> {
Configuration enforcedPlatforms = this.getPlatformConfiguratio... | class ApplicationDeploymentClasspathBuilder {
private static String getRuntimeConfigName(LaunchMode mode, boolean base) {
final StringBuilder sb = new StringBuilder();
sb.append("quarkus");
if (mode == LaunchMode.DEVELOPMENT) {
sb.append("Dev");
} else if (mode == Launch... | class ApplicationDeploymentClasspathBuilder {
private static String getRuntimeConfigName(LaunchMode mode, boolean base) {
final StringBuilder sb = new StringBuilder();
sb.append("quarkus");
if (mode == LaunchMode.DEVELOPMENT) {
sb.append("Dev");
} else if (mode == Launch... |
Why do we need to get it again? We are still inside the lock | private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetir... | Optional<Node> reservedNewNode = nodeRepository().getNode(expectedNewNode.get().hostname(), Node.State.reserved); | private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetir... | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
... | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
... |
This is because `getKeyColumns` is not stable. I've fixed this by using `fullSchema`, PTAL. ``` /** * NOTE: The result key columns are not in the creating order because `nameToColumn` * uses unordered hashmap to keeps name to column's mapping. */ public List<Column> getKeyColumns() { retu... | public void testCreateMaterializedViewWithoutSortKeys_Partitioned_1() {
String sql = "create materialized view test_mv_sort_key1 " +
"partition by c_1_3 " +
"distributed by hash(c_1_3, c_1_0) buckets 10 " +
"PROPERTIES (\n" +
"\"replicatio... | Assert.assertTrue(keyColumns.get(0).getName().equals("c_1_0")); | public void testCreateMaterializedViewWithoutSortKeys_Partitioned_1() {
String sql = "create materialized view test_mv_sort_key1 " +
"partition by c_1_3 " +
"distributed by hash(c_1_3, c_1_0) buckets 10 " +
"PROPERTIES (\n" +
"\"replicatio... | class CreateMaterializedViewTest {
private static final Logger LOG = LogManager.getLogger(CreateMaterializedViewTest.class);
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Rule
public TestName name = new TestName();
@ClassRule
public static TemporaryFolder t... | class CreateMaterializedViewTest {
private static final Logger LOG = LogManager.getLogger(CreateMaterializedViewTest.class);
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Rule
public TestName name = new TestName();
@ClassRule
public static TemporaryFolder t... |
This is easy to obtain a unstandard format content. For example: ``` BEGIN def a(b): retrun b END ``` Should we check it here? | public ParseNode visitCreateFunctionStatement(StarRocksParser.CreateFunctionStatementContext context) {
String functionType = "SCALAR";
boolean isGlobal = context.GLOBAL() != null;
if (context.functionType != null) {
functionType = context.functionType.getText();
}
Q... | inlineContent = text.substring(5, text.length() - 3); | public ParseNode visitCreateFunctionStatement(StarRocksParser.CreateFunctionStatementContext context) {
String functionType = "SCALAR";
boolean isGlobal = context.GLOBAL() != null;
if (context.functionType != null) {
functionType = context.functionType.getText();
}
Q... | class AstBuilderFactory {
protected AstBuilderFactory() {
}
public AstBuilder create(long sqlMode) {
return new AstBuilder(sqlMode, new IdentityHashMap<>());
}
public AstBuilder create(long sqlMode, IdentityHashMap<ParserRuleContext, List<HintNode>> hintMap) {
... | class AstBuilderFactory {
protected AstBuilderFactory() {
}
public AstBuilder create(long sqlMode) {
return new AstBuilder(sqlMode, new IdentityHashMap<>());
}
public AstBuilder create(long sqlMode, IdentityHashMap<ParserRuleContext, List<HintNode>> hintMap) {
... |
Yes, the APIS should be changed, here are the final discussion result: ``` post: job/start/ job/stop/ get: job/progress/${id} ``` | protected void channelRead0(final ChannelHandlerContext channelHandlerContext, final FullHttpRequest request) {
String requestPath = request.uri();
String requestBody = request.content().toString(CharsetUtil.UTF_8);
HttpMethod method = request.method();
if (!URL_PATTERN.matcher(requestPa... | if (requestPath.contains("/shardingscaling/stop/") && method.equals(HttpMethod.DELETE)) { | protected void channelRead0(final ChannelHandlerContext channelHandlerContext, final FullHttpRequest request) {
String requestPath = request.uri();
String requestBody = request.content().toString(CharsetUtil.UTF_8);
HttpMethod method = request.method();
if (!URL_PATTERN.matcher(requestPa... | class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
private static final Pattern URL_PATTERN = Pattern.compile("(^/shardingscaling/start)|(^/shardingscaling/(progress|stop)/\\d+)",
Pattern.CASE_INSENSITIVE);
private static final Gson GSON = new Gson();
private stati... | class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
private static final Pattern URL_PATTERN = Pattern.compile("(^/shardingscaling/job/(start|stop))|(^/shardingscaling/job/progress/\\d+)",
Pattern.CASE_INSENSITIVE);
private static final Gson GSON = new Gson();
priva... |
as above, moved refcounting into SpannerAccessor. | public void setup() {
spannerAccessor = spannerAccessors.get(spannerConfig);
if (spannerAccessor == null) {
synchronized (spannerAccessors) {
spannerAccessor = spannerAccessors.get(spannerConfig);
if (spannerAccessor == null) {
LOG.info("Connec... | synchronized (spannerAccessors) { | public void setup() {
spannerAccessor = SpannerAccessor.getOrCreate(spannerConfig);
bundleWriteBackoff =
FluentBackoff.DEFAULT
.withMaxCumulativeBackoff(spannerConfig.getMaxCumulativeBackoff().get())
.withInitialBackoff(spannerConfig.getMaxCumulativeBackoff().get().divi... | class WriteToSpannerFn extends DoFn<Iterable<MutationGroup>, Void> {
private final SpannerConfig spannerConfig;
private final FailureMode failureMode;
private static final ConcurrentHashMap<SpannerConfig, SpannerAccessor> spannerAccessors =
new ConcurrentHashMap<>();
private st... | class WriteToSpannerFn extends DoFn<Iterable<MutationGroup>, Void> {
private final SpannerConfig spannerConfig;
private final FailureMode failureMode;
private transient SpannerAccessor spannerAccessor;
/* Number of times an aborted write to spanner could be retried */
private static final in... |
Nice , thanks for introducing fault tolerance. | private void validateDataCreation(int expectedSize) {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CosmosAsyncContainer container = database.getContainer(containerName);
LOGG... | if (resultCount < (expectedSize * 0.90)) { | private void validateDataCreation(int expectedSize) {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CosmosAsyncContainer container = database.getContainer(containerName);
LOGG... | class DataLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(DataLoader.class);
private static final int MAX_BATCH_SIZE = 10000;
private static final int BULK_OPERATION_CONCURRENCY = 5;
private static final Duration BULK_LOAD_WAIT_DURATION = Duration.ofSeconds(120);
private stati... | class DataLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(DataLoader.class);
private static final int MAX_BATCH_SIZE = 10000;
private static final int BULK_OPERATION_CONCURRENCY = 5;
private static final Duration BULK_LOAD_WAIT_DURATION = Duration.ofSeconds(120);
private stati... |
We should not rely on "the last one is running", better filter it by state. So that we can unify the logic just same as batch cancel. | public boolean cancelLoadJob(CancelLoadStmt stmt, boolean isAccurateMatch) throws DdlException {
String dbName = stmt.getDbName();
String label = stmt.getLabel();
Database db = Catalog.getCurrentCatalog().getDb(dbName);
if (db == null) {
throw new DdlExcept... | public boolean cancelLoadJob(CancelLoadStmt stmt, boolean isAccurateMatch) throws DdlException {
String dbName = stmt.getDbName();
String label = stmt.getLabel();
Database db = Catalog.getCurrentCatalog().getDb(dbName);
if (db == null) {
throw new DdlExcept... | class Load {
private static final Logger LOG = LogManager.getLogger(Load.class);
public static final String VERSION = "v1";
private static final Map<JobState, Set<JobState>> STATE_CHANGE_MAP = Maps.newHashMap();
public static DppConfig dppDefaultConfig = null;
public static Map<String, D... | class Load {
private static final Logger LOG = LogManager.getLogger(Load.class);
public static final String VERSION = "v1";
private static final Map<JobState, Set<JobState>> STATE_CHANGE_MAP = Maps.newHashMap();
public static DppConfig dppDefaultConfig = null;
public static Map<String, D... | |
Do we need to new up `DataLakeFileInputStreamOptions` here? If it's null shouldn't `options.isUpn()` be null? Could we just make the if check below `if (options != null && options.isUpn() != null) {` | public DataLakeFileOpenInputStreamResult openInputStream(DataLakeFileInputStreamOptions options, Context context) {
Context newContext;
options = options == null ? new DataLakeFileInputStreamOptions() : options;
if (options.isUpn() != null) {
HttpHeaders headers = new HttpHeaders();
... | options = options == null ? new DataLakeFileInputStreamOptions() : options; | public DataLakeFileOpenInputStreamResult openInputStream(DataLakeFileInputStreamOptions options, Context context) {
context = BuilderHelper.addUpnHeader(() -> (options == null) ? null : options.isUpn(), context);
BlobInputStreamOptions convertedOptions = Transforms.toBlobInputStreamOptions(options);
... | class DataLakeFileClient extends DataLakePathClient {
/**
* Indicates the maximum number of bytes that can be sent in a call to upload.
*/
private static final long MAX_APPEND_FILE_BYTES = DataLakeFileAsyncClient.MAX_APPEND_FILE_BYTES;
private static final ClientLogger LOGGER = new ClientLogger(... | class DataLakeFileClient extends DataLakePathClient {
/**
* Indicates the maximum number of bytes that can be sent in a call to upload.
*/
private static final long MAX_APPEND_FILE_BYTES = DataLakeFileAsyncClient.MAX_APPEND_FILE_BYTES;
private static final ClientLogger LOGGER = new ClientLogger(... |
```suggestion service = new ScheduledThreadPoolExecutor(1, r -> new Thread(r, name() + "-worker")); ``` | public Maintainer(Controller controller, Duration interval, JobControl jobControl, String name, Set<SystemName> activeSystems) {
if (interval.isNegative() || interval.isZero())
throw new IllegalArgumentException("Interval must be positive, but was " + interval);
this.controller = controller... | service = new ScheduledThreadPoolExecutor(1, r -> new Thread(r, getClass().getSimpleName() + "-worker")); | public Maintainer(Controller controller, Duration interval, JobControl jobControl, String name, Set<SystemName> activeSystems) {
if (interval.isNegative() || interval.isZero())
throw new IllegalArgumentException("Interval must be positive, but was " + interval);
this.controller = controller... | class Maintainer extends AbstractComponent implements Runnable {
protected static final Logger log = Logger.getLogger(Maintainer.class.getName());
private final Controller controller;
private final Duration maintenanceInterval;
private final JobControl jobControl;
private final ScheduledExecutorSe... | class Maintainer extends AbstractComponent implements Runnable {
protected static final Logger log = Logger.getLogger(Maintainer.class.getName());
private final Controller controller;
private final Duration maintenanceInterval;
private final JobControl jobControl;
private final ScheduledExecutorSe... |
Does it make sense to have this.retryPolicy set to new Retrypolicy() in the constructor of the class. And in the method `public ChatClientBuilder retryPolicy(RetryPolicy retryPolicy)`, it just reset the retryPolicy attribute This way, we can avoid the null checks in the code. | private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) {
policies.add(getUserAgentPolicy());
policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policies.add(new CookiePolicy());
policies.add(new HttpLoggingPolicy(logOptions));
} | policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy); | private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) {
policies.add(getUserAgentPolicy());
policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policies.add(new CookiePolicy());
policies.add(new HttpLoggingPolicy(logOptions));
} | class ChatClientBuilder {
private String endpoint;
private HttpClient httpClient;
private CommunicationTokenCredential communicationTokenCredential;
private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>();
private HttpLogOptions logOptions = new HttpLogOptions();... | class ChatClientBuilder {
private String endpoint;
private HttpClient httpClient;
private CommunicationTokenCredential communicationTokenCredential;
private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>();
private HttpLogOptions logOptions = new HttpLogOptions();... |
I don't think we need this line, since already checked in the `while`. | public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getTypeName());
sb.append(getSizeString());
BType element = elementType;
while (element instanceof BArrayType) {
sb.append(((BArrayType) element).getSizeString());
if (!(((BArrayT... | if (!(((BArrayType) element).elementType instanceof BArrayType)) { | public String toString() {
StringBuilder sb = new StringBuilder();
BType tempElementType = elementType;
sb.append(getSizeString());
while (tempElementType.getTag() == TypeTags.ARRAY_TAG) {
BArrayType arrayElement = (BArrayType) tempElementType;
sb.append(arrayElem... | class BArrayType extends BType {
private BType elementType;
private int dimensions = 1;
private int size = -1;
private boolean hasFillerValue;
private ArrayState state = ArrayState.UNSEALED;
public BArrayType(BType elementType) {
super(null, null, ArrayValue.class);
this.element... | class BArrayType extends BType {
private BType elementType;
private int dimensions = 1;
private int size = -1;
private boolean hasFillerValue;
private ArrayState state = ArrayState.UNSEALED;
public BArrayType(BType elementType) {
super(null, null, ArrayValue.class);
this.element... |
@FroMage you could also check that the bean has all the expected types, see [`ResourceBeanTypeTest`](https://github.com/quarkusio/quarkus/blob/main/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/beanTypes/ResourceBeanTypeTest.java#L39-L45) as an example. But I... | void shouldDeployWithoutIssues() {
} | void shouldDeployWithoutIssues() {
} | class BeanParamTest {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.setArchiveProducer(() -> {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(MyBeanParamWithFieldsAndProperties.class, Top.class);
});
@T... | class BeanParamTest {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.setArchiveProducer(() -> {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(MyBeanParamWithFieldsAndProperties.class, Top.class);
});
@T... | |
Currently they do not have a shared parent to put the constant, and it seems not worthwhile to make a new class for constant, as currently here is only 1 "kubernetes" duplicated in 2 places. | private static boolean isWebApp(SiteInner inner) {
boolean ret = false;
if (inner.kind() == null) {
ret = true;
} else {
List<String> kinds = Arrays.asList(inner.kind().split(Pattern.quote(",")));
if ((kinds.contains("app") || kinds.contains("api")) && !kinds.... | if ((kinds.contains("app") || kinds.contains("api")) && !kinds.contains("kubernetes")) { | private static boolean isWebApp(SiteInner inner) {
boolean ret = false;
if (inner.kind() == null) {
ret = true;
} else {
List<String> kinds = Arrays.asList(inner.kind().split(Pattern.quote(",")));
if ((kinds.contains("app") || kinds.contains("api")) && !kinds.... | class WebAppsImpl
extends GroupableResourcesImpl<WebApp, WebAppImpl, SiteInner, WebAppsClient, AppServiceManager>
implements WebApps, SupportsBatchDeletion {
public WebAppsImpl(final AppServiceManager manager) {
super(manager.serviceClient().getWebApps(), manager);
}
@Override
public M... | class WebAppsImpl
extends GroupableResourcesImpl<WebApp, WebAppImpl, SiteInner, WebAppsClient, AppServiceManager>
implements WebApps, SupportsBatchDeletion {
public WebAppsImpl(final AppServiceManager manager) {
super(manager.serviceClient().getWebApps(), manager);
}
@Override
public M... |
```suggestion try { lowerBound = elementTimestampOrTimerHoldTimestamp.minus(doFn.getAllowedTimestampSkew()); } catch (ArithmeticException e) { lowerBound = BoundedWindow.TIMESTAMP_MIN_VALUE; } if (outputTimestamp.isBefore(lowerBound) || outputTimestamp.isAfter(Bounded... | private Timer<K> getTimerForTime(Instant scheduledTime) {
if (outputTimestamp != null) {
Instant lowerBound;
Instant upperBound = BoundedWindow.TIMESTAMP_MAX_VALUE;
try {
lowerBound = elementTimestampOrTimerHoldTimestamp.minus(doFn.getAllowedTimestampSkew());
} catch (Ari... | if (outputTimestamp.isBefore(lowerBound) || outputTimestamp.isAfter(upperBound)) { | private Timer<K> getTimerForTime(Instant scheduledTime) {
if (outputTimestamp != null) {
Instant lowerBound;
try {
lowerBound = elementTimestampOrTimerHoldTimestamp.minus(doFn.getAllowedTimestampSkew());
} catch (ArithmeticException e) {
lowerBound = BoundedWindow.TIMES... | class FnApiTimer<K> implements org.apache.beam.sdk.state.Timer {
private final String timerIdOrFamily;
private final K userKey;
private final String dynamicTimerTag;
private final TimeDomain timeDomain;
private final Duration allowedLateness;
private final Instant fireTimestamp;
private fina... | class FnApiTimer<K> implements org.apache.beam.sdk.state.Timer {
private final String timerIdOrFamily;
private final K userKey;
private final String dynamicTimerTag;
private final TimeDomain timeDomain;
private final Duration allowedLateness;
private final Instant fireTimestamp;
private fina... |
You are right in theory but the practice is that we are doing the propagation and we are responsible for cleaning up afterwards (deactivate context). Following that principle, there cannot really be an active req. context on the "new" thread. Hence we have this `NOOP` snapshot here. | public ThreadContextSnapshot currentContext(Map<String, String> map) {
ArcContainer arc = Arc.container();
if (arc == null || !arc.isRunning()) {
return null;
}
if (!isContextActiveOnThisThread(arc)) {
return NOOP_SNAPSHOT;
}
... | return NOOP_SNAPSHOT; | public ThreadContextSnapshot currentContext(Map<String, String> map) {
ArcContainer arc = Arc.container();
if (arc == null || !arc.isRunning()) {
return null;
}
InjectableContext.ContextState state = isContextActiveOnThisThread(arc) ? arc.requestContext... | class ArcContextProvider implements ThreadContextProvider {
private static ThreadContextSnapshot NOOP_SNAPSHOT = () -> () -> {
};
@Override
@Override
public ThreadContextSnapshot clearedContext(Map<String, String> map) {
ArcContainer arc = Arc.container();
if (arc ==... | class ArcContextProvider implements ThreadContextProvider {
@Override
@Override
public ThreadContextSnapshot clearedContext(Map<String, String> map) {
ArcContainer arc = Arc.container();
if (arc == null || !arc.isRunning()) {
return null;
}
... |
What I meant was something like ```java Map<Name, BPackageSymbol> modules = new HashMap<>(); modules.put(Names.ERROR, this.langErrorModuleSymbol); modules.put(Names.OBJECT, this.langObjectModuleSymbol); modules.put(Names.XML, this.langXmlModuleSymbol); this.predeclaredModules = Collections.unmodifiableMap(modules); ``... | public void loadPredeclaredModules() {
this.predeclaredModules.put(Names.ERROR, this.langErrorModuleSymbol);
this.predeclaredModules.put(Names.OBJECT, this.langObjectModuleSymbol);
this.predeclaredModules.put(Names.XML, this.langXmlModuleSymbol);
this.predeclaredModules = Collections.un... | this.predeclaredModules = Collections.unmodifiableMap(this.predeclaredModules); | public void loadPredeclaredModules() {
Map<Name, BPackageSymbol> modules = new HashMap<>();
modules.put(Names.ERROR, this.langErrorModuleSymbol);
modules.put(Names.OBJECT, this.langObjectModuleSymbol);
modules.put(Names.XML, this.langXmlModuleSymbol);
this.predeclaredModules = C... | class SymbolTable {
private static final CompilerContext.Key<SymbolTable> SYM_TABLE_KEY =
new CompilerContext.Key<>();
public static final PackageID TRANSACTION = new PackageID(Names.BUILTIN_ORG, Names.TRANSACTION_PACKAGE,
Names.EMPTY);
public static final Integer BBYTE_MIN_VALUE ... | class SymbolTable {
private static final CompilerContext.Key<SymbolTable> SYM_TABLE_KEY =
new CompilerContext.Key<>();
public static final PackageID TRANSACTION = new PackageID(Names.BUILTIN_ORG, Names.TRANSACTION_PACKAGE,
Names.EMPTY);
public static final Integer BBYTE_MIN_VALUE ... |
New issue https://github.com/ballerina-platform/ballerina-lang/issues/36069 | public Boolean visit(BRecordType t, BType s) {
if (t == s) {
return true;
}
if (s.tag != TypeTags.RECORD || !hasSameReadonlyFlag(s, t)) {
return false;
}
BRecordType source = (BRecordType) s;
if (source.fields.siz... | if (isSameType(sourceField.type, targetField.type, new HashSet<>(this.unresolvedTypes)) && | public Boolean visit(BRecordType t, BType s) {
if (t == s) {
return true;
}
if (s.tag != TypeTags.RECORD || !hasSameReadonlyFlag(s, t)) {
return false;
}
BRecordType source = (BRecordType) s;
if (source.fields.siz... | class BSameTypeVisitor implements BTypeVisitor<BType, Boolean> {
Set<TypePair> unresolvedTypes;
BSameTypeVisitor(Set<TypePair> unresolvedTypes) {
this.unresolvedTypes = unresolvedTypes;
}
@Override
public Boolean visit(BType target, BType source) {
BTyp... | class BSameTypeVisitor implements BTypeVisitor<BType, Boolean> {
Set<TypePair> unresolvedTypes;
BSameTypeVisitor(Set<TypePair> unresolvedTypes) {
this.unresolvedTypes = unresolvedTypes;
}
@Override
public Boolean visit(BType target, BType source) {
BTyp... |
> projects @tristaZero It can be seen from the source code that when the original projects and the optimized projects are the same, projectInts will return null. Maybe the `0 == projects.length` condition is redundant. ```java private static TableScanNode createProjectableFilterable(Compiler compiler, TableSc... | public String generate(final String table) {
String project = null == projects || 0 == projects.length ? "*" : Arrays.stream(projects).mapToObj(each -> fields.get(each).getName()).collect(Collectors.joining(", "));
return String.format("SELECT %s FROM %s", project, table);
} | String project = null == projects || 0 == projects.length ? "*" : Arrays.stream(projects).mapToObj(each -> fields.get(each).getName()).collect(Collectors.joining(", ")); | public String generate(final String table) {
Collection<String> actualColumnNames = null == projects ? columnNames : Arrays.stream(projects).mapToObj(columnNames::get).collect(Collectors.toList());
return String.format("SELECT %s FROM %s", Joiner.on(", ").join(actualColumnNames), table);
} | class FederateExecutionSQLGenerator {
private final DataContext root;
private final List<RexNode> filters;
private final int[] projects;
private final List<RelDataTypeField> fields;
/**
* Generate sql.
*
* @param table table
* @return sql
*/
} | class FederateExecutionSQLGenerator {
private final DataContext root;
private final List<RexNode> filters;
private final int[] projects;
private final List<String> columnNames;
/**
* Generate sql.
*
* @param table table
* @return sql
*/
} |
Super minor nitpick -> this is redundant. Feel free to ignore if you don't feel like removing it :) | public void createZip() throws IOException {
final File file = new File("target/zip");
delete(file);
file.mkdirs();
File zipFile = new File(file, "project.zip");
try (FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(f... | zis.close(); | public void createZip() throws IOException {
final File file = new File("target/zip");
delete(file);
file.mkdirs();
File zipFile = new File(file, "project.zip");
try (FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(f... | class CreateProjectTest {
@Test
public void create() throws IOException {
final File file = new File("target/basic-rest");
delete(file);
final CreateProject createProject = new CreateProject(new FileProjectWriter(file)).groupId("io.quarkus")
.artifactId("basic-rest")
... | class CreateProjectTest {
@Test
public void create() throws IOException {
final File file = new File("target/basic-rest");
delete(file);
final CreateProject createProject = new CreateProject(new FileProjectWriter(file)).groupId("io.quarkus")
.artifactId("basic-rest")
... |
Shall we use `fail.expr.Stmt.getKind()` instead of `instanceOf` check? | private BLangBlockStmt rewriteNestedOnFail(BLangOnFailClause onFailClause, BLangFail fail) {
BLangOnFailClause currentOnFail = this.onFailClause;
BLangBlockStmt onFailBody = blockStmtByFailNode.get(fail);
if (onFailBody == null) {
onFailBody = ASTBuilderUtil.createBlockStmt(onFailCla... | if (fail.exprStmt instanceof BLangPanic) { | private BLangBlockStmt rewriteNestedOnFail(BLangOnFailClause onFailClause, BLangFail fail) {
BLangOnFailClause currentOnFail = this.onFailClause;
BLangBlockStmt onFailBody = blockStmtByFailNode.get(fail);
if (onFailBody == null) {
onFailBody = ASTBuilderUtil.createB... | class definition node for which the initializer is created
* @param env The env for the type node
* @return The generated initializer method
*/
private BLangFunction createGeneratedInitializerFunction(BLangClassDefinition classDefinition, SymbolEnv env) {
BLangFunction generatedIni... | class definition node for which the initializer is created
* @param env The env for the type node
* @return The generated initializer method
*/
private BLangFunction createGeneratedInitializerFunction(BLangClassDefinition classDefinition, SymbolEnv env) {
BLangFunction generatedIni... |
it may or may not be the CPU history logged in the diagnostics, but since it is close enough, so should be fine? | public String toJson() {
String snapshot = this.cachedRequestDiagnostics;
if (snapshot != null) {
return snapshot;
}
synchronized (this.spanName) {
snapshot = this.cachedRequestDiagnostics;
if (snapshot != null) {
return snapshot;
... | this.systemUsage = ClientSideRequestStatistics.fetchSystemInformation(); | public String toJson() {
String snapshot = this.cachedRequestDiagnostics;
if (snapshot != null) {
return snapshot;
}
synchronized (this.spanName) {
snapshot = this.cachedRequestDiagnostics;
if (snapshot != null) {
return snapshot;
... | class CosmosDiagnosticsContext {
private final static ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagAccessor =
ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor();
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper()... | class CosmosDiagnosticsContext {
private final static ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagAccessor =
ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor();
private final static ObjectMapper mapper = Utils.getSimpleObjectMapper()... |
It's already exposed ~~for the other classes~~ but yes, it's better not to use it. I'll change it to a private logger. | private void cleanup() throws Exception {
StreamTask.LOG.debug(
"Cleanup AsyncCheckpointRunnable for checkpoint {} of {}.",
checkpointMetaData.getCheckpointId(),
taskName);
Exception exception = null;
for (OperatorSnapshotFutures operatorSnapshotResult : operatorSnapshotsInProgress.values()) {
if... | StreamTask.LOG.debug( | private void cleanup() throws Exception {
LOG.debug(
"Cleanup AsyncCheckpointRunnable for checkpoint {} of {}.",
checkpointMetaData.getCheckpointId(),
taskName);
Exception exception = null;
for (OperatorSnapshotFutures operatorSnapshotResult : operatorSnapshotsInProgress.values()) {
if (operatorS... | class AsyncCheckpointRunnable implements Runnable, Closeable {
private final String taskName;
private final CloseableRegistry closeableRegistry;
private final Environment taskEnvironment;
private enum AsyncCheckpointState {
RUNNING,
DISCARDED,
COMPLETED
}
private final AsyncExceptionHandler asyncExceptio... | class AsyncCheckpointRunnable implements Runnable, Closeable {
public static final Logger LOG = LoggerFactory.getLogger(AsyncCheckpointRunnable.class);
private final String taskName;
private final CloseableRegistry closeableRegistry;
private final Environment taskEnvironment;
private enum AsyncCheckpointState {
... |
I'd modify these to return a collection instead and make them static. | private void initRegionExecutionViewByVertex(final Set<PipelinedRegion> pipelinedRegions) {
for (PipelinedRegion pipelinedRegion : pipelinedRegions) {
final PipelinedRegionExecutionView regionExecutionView = new PipelinedRegionExecutionView(pipelinedRegion);
for (ExecutionVertexID executionVertexId : pipelinedR... | for (ExecutionVertexID executionVertexId : pipelinedRegion) { | private void initRegionExecutionViewByVertex(final Set<PipelinedRegion> pipelinedRegions) {
for (PipelinedRegion pipelinedRegion : pipelinedRegions) {
final PipelinedRegionExecutionView regionExecutionView = new PipelinedRegionExecutionView(pipelinedRegion);
for (ExecutionVertexID executionVertexId : pipelinedR... | class RegionPartitionReleaseStrategy implements PartitionReleaseStrategy {
private final SchedulingTopology schedulingTopology;
private final Map<PipelinedRegion, PipelinedRegionConsumedBlockingPartitions> consumedBlockingPartitionsByRegion = new IdentityHashMap<>();
private final Map<ExecutionVertexID, Pipelined... | class RegionPartitionReleaseStrategy implements PartitionReleaseStrategy {
private final SchedulingTopology schedulingTopology;
private final Map<PipelinedRegion, PipelinedRegionConsumedBlockingPartitions> consumedBlockingPartitionsByRegion = new IdentityHashMap<>();
private final Map<ExecutionVertexID, Pipelined... |
Actually `srcRel.getTable().getQualifiedName()` returns a `List`, in Calcite there's a concept of `database` which we don't touch so far. | private BeamSqlSeekableTable getSeekableTableFromRelNode(BeamRelNode relNode, BeamSqlEnv sqlEnv) {
BeamIOSourceRel srcRel = (BeamIOSourceRel) relNode;
String tableName = Joiner.on('.').join(srcRel.getTable().getQualifiedName());
BeamSqlTable sourceTable = sqlEnv.findTable(tableName);
return (BeamSqlSeek... | String tableName = Joiner.on('.').join(srcRel.getTable().getQualifiedName()); | private BeamSqlSeekableTable getSeekableTableFromRelNode(BeamRelNode relNode, BeamSqlEnv sqlEnv) {
BeamIOSourceRel srcRel = (BeamIOSourceRel) relNode;
String tableName = Joiner.on('.').join(srcRel.getTable().getQualifiedName());
BeamSqlTable sourceTable = sqlEnv.findTable(tableName);
return (BeamSqlSeek... | class BeamJoinRel extends Join implements BeamRelNode {
public BeamJoinRel(RelOptCluster cluster, RelTraitSet traits, RelNode left, RelNode right,
RexNode condition, Set<CorrelationId> variablesSet, JoinRelType joinType) {
super(cluster, traits, left, right, condition, variablesSet, joinType);
}
@Overr... | class BeamJoinRel extends Join implements BeamRelNode {
public BeamJoinRel(RelOptCluster cluster, RelTraitSet traits, RelNode left, RelNode right,
RexNode condition, Set<CorrelationId> variablesSet, JoinRelType joinType) {
super(cluster, traits, left, right, condition, variablesSet, joinType);
}
@Overr... |
I am wondering whether it wouldn't be simpler to change `result.handleAsync` to `result.whenAsync` and then to add the result of this operation to the `incompleteFuturesTracker`? That way we are sure that we will have handled the result before doing any other operations (e.g. failing/completing checkpoints). | public CompletableFuture<Acknowledge> sendEvent(OperatorEvent evt) {
if (!isReady()) {
throw new FlinkRuntimeException("SubtaskGateway is not ready, task not yet running.");
}
final SerializedValue<OperatorEvent> serializedEvent;
try {
serializedEvent = new Seria... | nonSuccessFuturesTrack.removeFailedFuture(result); | public CompletableFuture<Acknowledge> sendEvent(OperatorEvent evt) {
if (!isReady()) {
throw new FlinkRuntimeException("SubtaskGateway is not ready, task not yet running.");
}
final SerializedValue<OperatorEvent> serializedEvent;
try {
serializedEvent = new Seria... | class SubtaskGatewayImpl implements OperatorCoordinator.SubtaskGateway {
private static final String EVENT_LOSS_ERROR_MESSAGE =
"An OperatorEvent from an OperatorCoordinator to a task was lost. "
+ "Triggering task failover to ensure consistency. Event: '%s', targetTask: %s";
p... | class SubtaskGatewayImpl implements OperatorCoordinator.SubtaskGateway {
private static final String EVENT_LOSS_ERROR_MESSAGE =
"An OperatorEvent from an OperatorCoordinator to a task was lost. "
+ "Triggering task failover to ensure consistency. Event: '%s', targetTask: %s";
p... |
This isn't quite right - we're now invalidating all of the StreamWriters when any one of them fails. I think instead you want to just null out the one that failed and allow it to be recreated the next get. | void invalidateWriteStream() {
if (streamAppendClient != null) {
synchronized (APPEND_CLIENTS) {
runAsyncIgnoreFailure(closeWriterExecutor, streamAppendClient::unpin);
@Nulla... | == System.identityHashCode(streamAppendClient)) { | void invalidateWriteStream() {
if (streamAppendClient != null) {
synchronized (APPEND_CLIENTS) {
runAsyncIgnoreFailure(closeWriterExecutor, streamAppendClient::unpin);
String... | class DestinationState {
private final String tableUrn;
private final MessageConverter<ElementT> messageConverter;
private String streamName = "";
private @Nullable StreamAppendClient streamAppendClient = null;
private long currentOffset = 0;
private List<ByteString> pendingMessages;... | class DestinationState {
private final String tableUrn;
private final MessageConverter<ElementT> messageConverter;
private String streamName = "";
private @Nullable StreamAppendClient streamAppendClient = null;
private long currentOffset = 0;
private List<ByteString> pendingMessages;... |
This change is caused by code formatting, and have nothing to do with the business logic of this PR. I have rolled it back to make this PR more focused. | public String getErrorRespWhenUnauthorized(AccessDeniedException accessDeniedException) {
if (Strings.isNullOrEmpty(accessDeniedException.getMessage())) {
ConnectContext context = ConnectContext.get();
if (context != null) {
AuthorizationMgr authorizationMgr = GlobalState... | return "Access denied for user " + userIdentity + ". " + | public String getErrorRespWhenUnauthorized(AccessDeniedException accessDeniedException) {
if (Strings.isNullOrEmpty(accessDeniedException.getMessage())) {
ConnectContext context = ConnectContext.get();
if (context != null) {
AuthorizationMgr authorizationMgr = GlobalState... | class RestBaseAction extends BaseAction {
private static final Logger LOG = LogManager.getLogger(RestBaseAction.class);
protected static final String CATALOG_KEY = "catalog";
protected static final String DB_KEY = "db";
protected static final String TABLE_KEY = "table";
protected static final Stri... | class RestBaseAction extends BaseAction {
private static final Logger LOG = LogManager.getLogger(RestBaseAction.class);
protected static final String CATALOG_KEY = "catalog";
protected static final String DB_KEY = "db";
protected static final String TABLE_KEY = "table";
protected static final Stri... |
the path could still refer to an object instead of a directory | private void deleteRecursively(Path path) throws IOException {
final FileStatus[] containingFiles =
Preconditions.checkNotNull(
listStatus(path),
"Hadoop FileSystem.listStatus should never return null based on its contract.");
if (containi... | IOException exception = null; | private void deleteRecursively(Path path) throws IOException {
final FileStatus[] containingFiles =
Preconditions.checkNotNull(
listStatus(path),
"Hadoop FileSystem.listStatus should never return null based on its contract.");
if (containi... | class FlinkS3PrestoFileSystem extends FlinkS3FileSystem {
public FlinkS3PrestoFileSystem(
FileSystem hadoopS3FileSystem,
String localTmpDirectory,
@Nullable String entropyInjectionKey,
int entropyLength,
@Nullable S3AccessHelper s3UploadHelper,
... | class FlinkS3PrestoFileSystem extends FlinkS3FileSystem {
public FlinkS3PrestoFileSystem(
FileSystem hadoopS3FileSystem,
String localTmpDirectory,
@Nullable String entropyInjectionKey,
int entropyLength,
@Nullable S3AccessHelper s3UploadHelper,
... |
```suggestion private static final Map<Byte, TransactionState> BYTE_TO_STATE = Arrays.stream(TransactionState.values()) .collect(Collectors.toMap(e -> e.state, e -> e)); static TransactionState fromByte(byte state) { TransactionState transact... | private static byte readTransactionState(ByteBuffer buffer) {
buffer.getLong();
buffer.getShort();
buffer.getInt();
return buffer.get();
} | private static byte readTransactionState(ByteBuffer buffer) {
buffer.getLong();
buffer.getShort();
buffer.getInt();
return buffer.get();
} | class KafkaTransactionLog implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(KafkaTransactionLog.class);
private static final Duration CONSUMER_POLL_DURATION = Duration.ofSeconds(1);
private static final Set<TransactionState> TERMINAL_TRANSACTION_STATES =
Immut... | class KafkaTransactionLog implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(KafkaTransactionLog.class);
private static final Duration CONSUMER_POLL_DURATION = Duration.ofSeconds(1);
private static final Set<TransactionState> TERMINAL_TRANSACTION_STATES =
Immut... | |
Can we share code between WriteWithResult and WriteVoid ? This introduces a significant amount of code duplication. | public PCollection<Void> expand(PCollection<T> input) {
WriteVoid<T> spec = this;
checkArgument(
(spec.getDataSourceProviderFn() != null),
"withDataSourceConfiguration() or withDataSourceProviderFn() is required");
if (input.hasSchema() && !spec.hasStatementAndSetter()) {
... | PCollection<Iterable<T>> iterables; | public PCollection<Void> expand(PCollection<T> input) {
WriteVoid<T> spec = this;
checkArgument(
(spec.getDataSourceProviderFn() != null),
"withDataSourceConfiguration() or withDataSourceProviderFn() is required");
if (input.hasSchema() && !spec.hasStatementAndSetter()) {
... | class Builder<T> {
abstract Builder<T> setAutoSharding(Boolean autoSharding);
abstract Builder<T> setDataSourceProviderFn(
SerializableFunction<Void, DataSource> dataSourceProviderFn);
abstract Builder<T> setStatement(ValueProvider<String> statement);
abstract Builder<T> setBatchSiz... | class Builder<T> {
abstract Builder<T> setAutoSharding(Boolean autoSharding);
abstract Builder<T> setDataSourceProviderFn(
SerializableFunction<Void, DataSource> dataSourceProviderFn);
abstract Builder<T> setStatement(ValueProvider<String> statement);
abstract Builder<T> setBatchSiz... |
Yes, you are right. I forgot that the code is waiting on the latch there. | public void taskCachedThreadPoolAllowsForSynchronousCheckpoints() throws Exception {
final Task task = createTask(SynchronousCheckpointTestingTask.class);
try (TaskCleaner ignored = new TaskCleaner(task)) {
task.startTaskThread();
executionLatch.await();
assertEquals(ExecutionState.RUNNING, task.getExec... | task.startTaskThread(); | public void taskCachedThreadPoolAllowsForSynchronousCheckpoints() throws Exception {
final Task task = createTask(SynchronousCheckpointTestingTask.class);
try (TaskCleaner ignored = new TaskCleaner(task)) {
task.startTaskThread();
assertThat(eventQueue.take(), is(Event.TASK_IS_RUNNING));
assertTrue(event... | class SynchronousCheckpointITCase {
private static OneShotLatch executionLatch;
private static OneShotLatch cancellationLatch;
private static OneShotLatch checkpointCompletionLatch;
private static OneShotLatch notifyLatch;
private static OneShotLatch checkpointTriggered = new OneShotLatch();
private static Mult... | class SynchronousCheckpointITCase {
private static OneShotLatch checkpointTriggered = new OneShotLatch();
private static LinkedBlockingQueue<Event> eventQueue = new LinkedBlockingQueue<>();
@Rule
public final Timeout timeoutPerTest = Timeout.seconds(10);
@Test
/**
* A {@link StreamTask} which makes s... |
It seems this is the only use for the `jpaConfig` object. Does this stricly need some lazy initialization, or could you read the field earlier and store only an immutable boolean field rather than keeping a reference to the bootstrap proxy? | public boolean validateExistingCurrentSessions() {
return jpaConfig.isValidateTenantInCurrentSessions();
} | return jpaConfig.isValidateTenantInCurrentSessions(); | public boolean validateExistingCurrentSessions() {
return false;
} | class HibernateCurrentTenantIdentifierResolver implements CurrentTenantIdentifierResolver {
private static final Logger LOG = Logger.getLogger(HibernateCurrentTenantIdentifierResolver.class);
private final JPAConfig jpaConfig;
public HibernateCurrentTenantIdentifierResolver(final JPAConfig jpaConfig) {
... | class HibernateCurrentTenantIdentifierResolver implements CurrentTenantIdentifierResolver {
private static final Logger LOG = Logger.getLogger(HibernateCurrentTenantIdentifierResolver.class);
@Override
public String resolveCurrentTenantIdentifier() {
if (!Arc.container().requestContext()... |
The retryRate is not used in this method, probably can move this logic to reevaluateThresholds | private void recordOperation(boolean isRetry) {
long totalSnapshot = this.totalOperationCount.incrementAndGet();
CurrentIntervalThresholds currentThresholdsSnapshot = this.currentThresholds.get();
long currentTotalCountSnapshot = currentThresholdsSnapshot.currentOperationCount.incrementAndGet();... | double retryRate = (double)currentRetryCountSnapshot / currentTotalCountSnapshot; | private void recordOperation(boolean isRetry) {
long totalSnapshot = this.totalOperationCount.incrementAndGet();
CurrentIntervalThresholds currentThresholdsSnapshot = this.currentThresholds.get();
long currentTotalCountSnapshot = currentThresholdsSnapshot.currentOperationCount.incrementAndGet();... | class PartitionScopeThresholds<TContext> {
private final static Logger logger = LoggerFactory.getLogger(PartitionScopeThresholds.class);
private final String pkRangeId;
private final BulkProcessingOptions<TContext> options;
private final AtomicInteger targetMicroBatchSize;
private final AtomicLong ... | class PartitionScopeThresholds<TContext> {
private final static Logger logger = LoggerFactory.getLogger(PartitionScopeThresholds.class);
private final String pkRangeId;
private final BulkProcessingOptions<TContext> options;
private final AtomicInteger targetMicroBatchSize;
private final AtomicLong ... |
Shall we extract `peek()` to a separate variable and reuse it at the recovery call? | private boolean isServiceDeclStart(ParserRuleContext currentContext, int lookahead) {
switch (peek(lookahead + 1).kind) {
case IDENTIFIER_TOKEN:
SyntaxKind tokenAfterIdentifier = peek(lookahead + 2).kind;
switch (tokenAfterIdentifier) {
ca... | switch (peek().kind) { | private boolean isServiceDeclStart(ParserRuleContext currentContext, int lookahead) {
switch (peek(lookahead + 1).kind) {
case IDENTIFIER_TOKEN:
SyntaxKind tokenAfterIdentifier = peek(lookahead + 2).kind;
switch (tokenAfterIdentifier) {
ca... | class member, object member or object member descriptor.
* </p>
* <code>
* class-member := object-field | method-defn | object-type-inclusion
* <br/>
* object-member := object-field | method-defn
* <br/>
* object-member-descriptor := object-field-descriptor | method-decl | object-type... | class member, object member or object member descriptor.
* </p>
* <code>
* class-member := object-field | method-defn | object-type-inclusion
* <br/>
* object-member := object-field | method-defn
* <br/>
* object-member-descriptor := object-field-descriptor | method-decl | object-type... |
Not this particular one, that was just an example of one having a comma (taken from a non-hosted app). Maybe we should disallow `-Xrunjdwp:transport` completely in hosted? Right now we warn or fail deployment for hosted (depending on feature flag value) and warn for non-hosted for JVM options like these. A JVM option ... | public void requireThatJvmOptionsAreLogged() throws IOException, SAXException {
verifyLoggingOfJvmOptions(true,
"options",
"-Xms2G foo bar",
"foo", "bar");
verifyLoggingOfJvmOptions(true,
... | verifyLoggingOfJvmOptions(true, "options", "-Djava.library.path=/opt/vespa/lib64:/home/y/lib64 -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005"); | public void requireThatJvmOptionsAreLogged() throws IOException, SAXException {
verifyLoggingOfJvmOptions(true,
"options",
"-Xms2G foo bar",
"foo", "bar");
verifyLoggingOfJvmOptions(true,
... | class JvmOptionsTest extends ContainerModelBuilderTestBase {
@Test
public void verify_jvm_tag_with_attributes() throws IOException, SAXException {
String servicesXml =
"<container version='1.0'>" +
" <search/>" +
" <nodes>" +
... | class JvmOptionsTest extends ContainerModelBuilderTestBase {
@Test
public void verify_jvm_tag_with_attributes() throws IOException, SAXException {
String servicesXml =
"<container version='1.0'>" +
" <search/>" +
" <nodes>" +
... |
Instead of doing multiple String::format calls across if statements, why not use a string builder? | public URL getDirectoryUrl() {
String directoryURLString = String.format("%s/%s/%s", azureFileStorageClient.getUrl(),
shareName, directoryPath);
if (snapshot != null) {
directoryURLString = String.format("%s?snapshot=%s", directoryURLString, snapshot);
}
try {
... | directoryURLString = String.format("%s?snapshot=%s", directoryURLString, snapshot); | public URL getDirectoryUrl() {
StringBuilder directoryURLString = new StringBuilder(azureFileStorageClient.getUrl()).append("/")
.append(shareName).append("/").append(directoryPath);
if (snapshot != null) {
directoryURLString.append("?snapshot=").append(snapshot);
}
... | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
/**
* Creates a Dire... | class DirectoryAsyncClient {
private final ClientLogger logger = new ClientLogger(DirectoryAsyncClient.class);
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareName;
private final String directoryPath;
private final String snapshot;
/**
* Creates a Dire... |
We need to handle other places where we call the semantic analyzer from the type checker too. Please check and create an issue. | private void analyzeObjectConstructor(BLangNode node, SymbolEnv env) {
if (!nonErrorLoggingCheck) {
semanticAnalyzer.analyzeNode(node, env);
}
} | semanticAnalyzer.analyzeNode(node, env); | private void analyzeObjectConstructor(BLangNode node, SymbolEnv env) {
if (!nonErrorLoggingCheck) {
semanticAnalyzer.analyzeNode(node, env);
}
} | class TypeChecker extends BLangNodeVisitor {
private static final CompilerContext.Key<TypeChecker> TYPE_CHECKER_KEY = new CompilerContext.Key<>();
private static Set<String> listLengthModifierFunctions = new HashSet<>();
private static Map<String, HashSet<String>> modifierFunctions = new HashMap<>();
... | class TypeChecker extends BLangNodeVisitor {
private static final CompilerContext.Key<TypeChecker> TYPE_CHECKER_KEY = new CompilerContext.Key<>();
private static Set<String> listLengthModifierFunctions = new HashSet<>();
private static Map<String, HashSet<String>> modifierFunctions = new HashMap<>();
... |
No, I'm not sure if it's the case. | public void setNodeName(final TransactionManagerConfiguration transactions) {
try {
arjPropertyManager.getCoreEnvironmentBean().setNodeIdentifier(transactions.nodeName);
jtaPropertyManager.getJTAEnvironmentBean().setXaRecoveryNodes(Collections.singletonList(transactions.nodeName));
... | TxControl.setXANodeName(transactions.nodeName); | public void setNodeName(final TransactionManagerConfiguration transactions) {
try {
arjPropertyManager.getCoreEnvironmentBean().setNodeIdentifier(transactions.nodeName);
jtaPropertyManager.getJTAEnvironmentBean().setXaRecoveryNodes(Collections.singletonList(transactions.nodeName));
... | class NarayanaJtaRecorder {
private static Properties defaultProperties;
private static final Logger log = Logger.getLogger(NarayanaJtaRecorder.class);
public void setDefaultProperties(Properties properties) {
try {
Field field = PropertiesFactory.class.getDecl... | class NarayanaJtaRecorder {
private static Properties defaultProperties;
private static final Logger log = Logger.getLogger(NarayanaJtaRecorder.class);
public void setDefaultProperties(Properties properties) {
try {
Field field = PropertiesFactory.class.getDecl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.