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 |
|---|---|---|---|---|---|
We can merge records and objects into one by casting the typeNode to `BStructureTypeNode` | private void createDummyTypeDefSymbol(BLangTypeDefinition typeDef, SymbolEnv env) {
typeDef.symbol = Symbols.createTypeSymbol(SymTag.TYPE_DEF, Flags.asMask(typeDef.flagSet),
names.fromIdNode(typeDef.name), env.enclPkg.symbol.pkgID, typeDef.typeNode.type, env.scope.owner);
typeDe... | case TypeTags.OBJECT: | private void createDummyTypeDefSymbol(BLangTypeDefinition typeDef, SymbolEnv env) {
typeDef.symbol = Symbols.createTypeSymbol(SymTag.TYPE_DEF, Flags.asMask(typeDef.flagSet),
names.fromIdNode(typeDef.name), env.enclPkg.symbol.pkgID, typeDef.typeNode.type, env.scope.owner);
typeDe... | class SymbolEnter extends BLangNodeVisitor {
private static final CompilerContext.Key<SymbolEnter> SYMBOL_ENTER_KEY =
new CompilerContext.Key<>();
private final PackageLoader pkgLoader;
private final SymbolTable symTable;
private final Names names;
private final SymbolResolver symResol... | class SymbolEnter extends BLangNodeVisitor {
private static final CompilerContext.Key<SymbolEnter> SYMBOL_ENTER_KEY =
new CompilerContext.Key<>();
private final PackageLoader pkgLoader;
private final SymbolTable symTable;
private final Names names;
private final SymbolResolver symResol... |
@geoand is it the expected behavior? I'm surprised that RestEasy Reactive does not decode the path parameter. | void shouldDetermineUrlViaStorkWhenUsingTarget() throws URISyntaxException {
String greeting = ClientBuilder.newClient().target("stork:
.get(String.class);
assertThat(greeting).isEqualTo("Hello, World!");
greeting = ClientBuilder.newClient().target(new URI("stork:
assert... | assertThat(greeting).isEqualTo("Hello, big%20bird"); | void shouldDetermineUrlViaStorkWhenUsingTarget() throws URISyntaxException {
String greeting = ClientBuilder.newClient().target("stork:
.get(String.class);
assertThat(greeting).isEqualTo("Hello, World!");
greeting = ClientBuilder.newClient().target(new URI("stork:
assert... | class StorkIntegrationTest {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(HelloClient.class, HelloResource.class))
.withConfigurationResource("stork-application.properties");
@RestClien... | class StorkIntegrationTest {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(HelloClient.class, HelloResource.class))
.withConfigurationResource("stork-application.properties");
@RestClien... |
The only thing I ask you @mkouba to think about is that in logging, when receiving null in the handler, to send to the log and `Thread.currentThread().getStackTrace()` so that you can roughly understand which extension had an error. Please think about it and let me know | public StartupContext() {
ShutdownContext shutdownContext = new ShutdownContext() {
@Override
public void addShutdownTask(Runnable runnable) {
if (Objects.nonNull(runnable)) {
shutdownTasks.addFirst(runnable);
} else {
... | if (Objects.nonNull(runnable)) { | public StartupContext() {
ShutdownContext shutdownContext = new ShutdownContext() {
@Override
public void addShutdownTask(Runnable runnable) {
if (runnable != null) {
shutdownTasks.addFirst(runnable);
} else {
throw ... | class StartupContext implements Closeable {
public static final String RAW_COMMAND_LINE_ARGS = StartupContext.class.getName() + ".raw-command-line-args";
private static final Logger LOG = Logger.getLogger(StartupContext.class);
private final Map<String, Object> values = new HashMap<>();
private Objec... | class StartupContext implements Closeable {
public static final String RAW_COMMAND_LINE_ARGS = StartupContext.class.getName() + ".raw-command-line-args";
private static final Logger LOG = Logger.getLogger(StartupContext.class);
private final Map<String, Object> values = new HashMap<>();
private Objec... |
The builder methods can be chained instead. ```java ServiceBusProcessorClient processor = new ServiceBusClientBuilder() .connectionString(connectionString) .processor() .queueName(queueName) .processMessage(System.out::println) .processError(context -> System.... | public void instantiateProcessor() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusProcessorClient processor = builder
.processor()
.queueName(queueName)
.processMessage(Sys... | ServiceBusProcessorClient processor = builder | public void instantiateProcessor() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusProcessorClient processor = builder
.processor()
.queueName(queueName)
.processMessage(Sys... | class ServiceBusClientBuilderJavaDocCodeSamples {
String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING");
String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME");
String topicName = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME");
String subscriptionNa... | class ServiceBusClientBuilderJavaDocCodeSamples {
String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING");
String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME");
String topicName = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME");
String subscriptionNa... |
Sounds reasonable. I'll change it. | DevConsoleRouteBuildItem handlePost() {
return new DevConsoleRouteBuildItem("config", "POST", new DevConsolePostHandler() {
@Override
protected void handlePost(RoutingContext event, MultiMap form) throws Exception {
String key = event.request().getFormAttribute("name");
... | lines.add(generatedLine + 1, profileKey + "=" + value); | DevConsoleRouteBuildItem handlePost() {
return new DevConsoleRouteBuildItem("config", "POST", new DevConsolePostHandler() {
@Override
protected void handlePost(RoutingContext event, MultiMap form) throws Exception {
String name = event.request().getFormAttribute("name");
... | class ConfigEditorProcessor {
@BuildStep(onlyIf = IsDevelopment.class)
@Record(ExecutionTime.RUNTIME_INIT)
public DevConsoleRuntimeTemplateInfoBuildItem config(ConfigRecorder recorder,
List<ConfigDescriptionBuildItem> configDescriptionBuildItems) {
List<ConfigDescription> configDescripti... | class ConfigEditorProcessor {
@BuildStep(onlyIf = IsDevelopment.class)
@Record(ExecutionTime.RUNTIME_INIT)
public DevConsoleRuntimeTemplateInfoBuildItem config(ConfigRecorder recorder,
List<ConfigDescriptionBuildItem> configDescriptionBuildItems) {
List<ConfigDescription> configDescripti... |
Why cannot change the parallelism of a job running in reactive mode | public static RestHandlerConfiguration fromConfiguration(Configuration configuration) {
final long refreshInterval = configuration.getLong(WebOptions.REFRESH_INTERVAL);
final int maxCheckpointStatisticCacheEntries =
configuration.getInteger(WebOptions.CHECKPOINTS_HISTORY_SIZE);
... | && !ClusterOptions.isReactiveModeEnabled(configuration); | public static RestHandlerConfiguration fromConfiguration(Configuration configuration) {
final long refreshInterval = configuration.getLong(WebOptions.REFRESH_INTERVAL);
final int maxCheckpointStatisticCacheEntries =
configuration.getInteger(WebOptions.CHECKPOINTS_HISTORY_SIZE);
... | class RestHandlerConfiguration {
private final long refreshInterval;
private final int maxCheckpointStatisticCacheEntries;
private final Time timeout;
private final File webUiDir;
private final boolean webSubmitEnabled;
private final boolean webCancelEnabled;
private final boolean web... | class RestHandlerConfiguration {
private final long refreshInterval;
private final int maxCheckpointStatisticCacheEntries;
private final Time timeout;
private final File webUiDir;
private final boolean webSubmitEnabled;
private final boolean webCancelEnabled;
private final boolean web... |
Okay, thanks for the hint. Changed | void assertFind() {
ShardingRuleConfiguration ruleConfig = new ShardingRuleConfiguration();
ShardingTableRuleConfiguration shardingTableRuleConfiguration = getShardingTableRuleConfiguration();
Map<String, AlgorithmConfiguration> allAlgorithms = getAlgorithms();
ruleConf... | Map<String, AlgorithmConfiguration> allAlgorithms = getAlgorithms(); | void assertFind() {
ShardingRuleConfiguration ruleConfig = new ShardingRuleConfiguration();
ShardingTableRuleConfiguration shardingTableRuleConfig = getShardingTableRuleConfiguration();
ruleConfig.getTables().add(shardingTableRuleConfig);
ruleConfig.getShardingAlgorithms().putAll(getAlgo... | class UnusedAlgorithmFinderTest {
private static final String USED_TABLE_SHARDING_ALGORITHM = "used_table_sharding_algorithm";
private static final String USED_TABLE_SHARDING_DEFAULT_ALGORITHM = "used_table_sharding_default_algorithm";
private static final String USED_DATABASE_SHARDING_ALGORI... | class UnusedAlgorithmFinderTest {
private static final String USED_TABLE_SHARDING_ALGORITHM = "used_table_sharding_algorithm";
private static final String USED_TABLE_SHARDING_DEFAULT_ALGORITHM = "used_table_sharding_default_algorithm";
private static final String USED_DATABASE_SHARDING_ALGORI... |
@lirui-apache I thought that `SHOW PARTITIONS` is DQL. I will modify `getDQLOpExecuteErrorMsg` to `getDDLOpExecuteErrorMsg`. | private TableResult executeOperation(Operation operation) {
if (operation instanceof ModifyOperation) {
return executeInternal(Collections.singletonList((ModifyOperation) operation));
} else if (operation instanceof CreateTableOperation) {
CreateTableOperation createTableOperation = (CreateTableOperation) ope... | String exMsg = getDQLOpExecuteErrorMsg(operation.asSummaryString()); | private TableResult executeOperation(Operation operation) {
if (operation instanceof ModifyOperation) {
return executeInternal(Collections.singletonList((ModifyOperation) operation));
} else if (operation instanceof CreateTableOperation) {
CreateTableOperation createTableOperation = (CreateTableOperation) ope... | class TableEnvironmentImpl implements TableEnvironmentInternal {
private static final boolean IS_STREAM_TABLE = true;
private final CatalogManager catalogManager;
private final ModuleManager moduleManager;
private final OperationTreeBuilder operationTreeBuilder;
private final List<ModifyOperation> bufferedModi... | class TableEnvironmentImpl implements TableEnvironmentInternal {
private static final boolean IS_STREAM_TABLE = true;
private final CatalogManager catalogManager;
private final ModuleManager moduleManager;
private final OperationTreeBuilder operationTreeBuilder;
private final List<ModifyOperation> bufferedModi... |
Can we combine queries with `;`? E.g.: ```java BeamSqlLine.testMain( new String[] { "-e", "CREATE TABLE table_test (col_a VARCHAR, col_b VARCHAR) TYPE 'test'; \n" + "INSERT INTO table_test SELECT '3', 'foo'; \n" + "INSERT INTO table_test SELECT '3', 'bar'; \n" + "SELECT col_a, count(*) FROM table... | public void testSqlLine_GroupBy() throws Exception {
BeamSqlLine.testMain(
new String[] {
"-e",
"CREATE TABLE table_test (col_a VARCHAR, col_b VARCHAR) TYPE 'test';",
"-e",
"INSERT INTO table_test SELECT '3', 'foo';",
"-e",
"INSERT INTO table_test ... | "INSERT INTO table_test SELECT '4', 'foo';", | public void testSqlLine_GroupBy() throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String[] args =
buildArgs(
"CREATE TABLE table_test (col_a VARCHAR, col_b VARCHAR) TYPE 'test';",
"INSERT INTO table_test SELECT '3', 'foo';",
... | class BeamSqlLineTest {
@Rule public TemporaryFolder folder = new TemporaryFolder();
public ByteArrayOutputStream byteArrayOutputStream;
@Before
public void setUp() {
byteArrayOutputStream = new ByteArrayOutputStream();
}
@Test
public void testSqlLine_emptyArgs() throws Exception {
BeamSqlLine.... | class BeamSqlLineTest {
private static final String QUERY_ARG = "-e";
@Rule public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testSqlLine_emptyArgs() throws Exception {
BeamSqlLine.main(new String[] {});
}
@Test
public void testSqlLine_nullCommand() throws Exception {
Bea... |
I don't think so. If the key is available locally and is valid the client will always try to perform the operation locally. Might want to change that behavior to what you suggested in a future PR. | private void unpackAndValidateId(String keyId) {
if (CoreUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
... | throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e)); | private void unpackAndValidateId(String keyId) {
if (CoreUtils.isNullOrEmpty(keyId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
... | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
static final String SECRETS_COLLECTION = "secrets";
static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault";
JsonWebKey key;
private final ClientLogger logger = new ClientLogger(Cryptography... | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
static final String SECRETS_COLLECTION = "secrets";
static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault";
JsonWebKey key;
private final ClientLogger logger = new ClientLogger(Cryptography... |
We should probably also do the other cleanup, like removing DNS entries? | public LockedApplication storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
applicationPackageValidator.validate(application.get(), applicationPackage, clock.instant());
application = application.with(applicationPackage.deploymentSpec());
application ... | controller.notificationsDb().removeNotifications(NotificationSource.from(application.get().id().instance(name))); | public LockedApplication storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
applicationPackageValidator.validate(application.get(), applicationPackage, clock.instant());
application = application.with(applicationPackage.deploymentSpec());
application ... | class ApplicationController {
private static final Logger log = Logger.getLogger(ApplicationController.class.getName());
/** The controller owning this */
private final Controller controller;
/** For persistence */
private final CuratorDb curator;
private final ArtifactRepository artifactRep... | class ApplicationController {
private static final Logger log = Logger.getLogger(ApplicationController.class.getName());
/** The controller owning this */
private final Controller controller;
/** For persistence */
private final CuratorDb curator;
private final ArtifactRepository artifactRep... |
Updated. I kept the first %s for now. | public ExpressionChecker addExpr(String expression, Object expectedValue) {
TypeName resultTypeName = JAVA_CLASS_TO_TYPENAME.get(expectedValue.getClass());
checkArgument(
resultTypeName != null,
String.format(
"The type of the expected object '%s' is unknown in 'addExpr(Str... | "The type of the expected object '%s' is unknown in 'addExpr(String %s, Object %s)'" | public ExpressionChecker addExpr(String expression, Object expectedValue) {
TypeName resultTypeName = JAVA_CLASS_TO_TYPENAME.get(expectedValue.getClass());
checkArgument(
resultTypeName != null,
String.format(
"The type of the expected value '%s' is unknown in 'addExpr(Stri... | class ExpressionChecker {
private transient List<ExpressionTestCase> exps = new ArrayList<>();
public ExpressionChecker addExpr(
String expression, Object expectedValue, FieldType resultFieldType) {
exps.add(ExpressionTestCase.of(expression, expectedValue, resultFieldType));
return th... | class ExpressionChecker {
private transient List<ExpressionTestCase> exps = new ArrayList<>();
public ExpressionChecker addExpr(
String expression, Object expectedValue, FieldType resultFieldType) {
exps.add(ExpressionTestCase.of(expression, expectedValue, resultFieldType));
return th... |
Negative case handles at https://github.com/ballerina-platform/ballerina-lang/pull/19723/files#diff-89edaaa1baefeea805366138354f0258R225. If maxAttempts = 0, we need to retry infinitely. so check this condition here. | public static boolean reconnect(WebSocketConnectionInfo connectionInfo) {
ObjectValue webSocketClient = connectionInfo.getWebSocketEndpoint();
RetryContext retryConnectorConfig = (RetryContext) webSocketClient.getNativeData(WebSocketConstants.
RETRY_CONFIG);
int interval = retryC... | if (((noOfReconnectAttempts < maxAttempts) && maxAttempts > 0) || maxAttempts == 0) { | public static boolean reconnect(WebSocketConnectionInfo connectionInfo) {
ObjectValue webSocketClient = connectionInfo.getWebSocketEndpoint();
RetryContext retryConnectorConfig = (RetryContext) webSocketClient.getNativeData(WebSocketConstants.
RETRY_CONFIG);
int interval = retryC... | class WebSocketUtil {
private static final Logger logger = LoggerFactory.getLogger(WebSocketUtil.class);
private static final String STATEMENT_FOR_RECONNECT = "Maximum retry attempts but couldn't connect " +
"to the server: ";
private static final String CLIENT_ENDPOINT_CONFIG = "config";
... | class WebSocketUtil {
private static final Logger logger = LoggerFactory.getLogger(WebSocketUtil.class);
private static final String CLIENT_ENDPOINT_CONFIG = "config";
public static ObjectValue createAndPopulateWebSocketCaller(WebSocketConnection webSocketConnection,
... |
Can you elaborate why we mix jre and jdk here? My understanding of this article is that java.specification.version adheres to current jre specification. https://docs.oracle.com/javase/7/docs/technotes/guides/versioning/spec/versioning2.html | public static DataflowRunner fromOptions(PipelineOptions options) {
DataflowPipelineOptions dataflowOptions =
PipelineOptionsValidator.validate(DataflowPipelineOptions.class, options);
ArrayList<String> missing = new ArrayList<>();
if (dataflowOptions.getAppName() == null) {
missing.add("appN... | String userAgent = | public static DataflowRunner fromOptions(PipelineOptions options) {
DataflowPipelineOptions dataflowOptions =
PipelineOptionsValidator.validate(DataflowPipelineOptions.class, options);
ArrayList<String> missing = new ArrayList<>();
if (dataflowOptions.getAppName() == null) {
missing.add("appN... | class path allowing for
* user specified configuration injection into the ObjectMapper. This supports user custom types
* on {@link PipelineOptions} | class path allowing for
* user specified configuration injection into the ObjectMapper. This supports user custom types
* on {@link PipelineOptions} |
this should just be set to the default value now. | FirestoreStub getFirestoreStub(PipelineOptions options) {
try {
FirestoreSettings.Builder builder =
FirestoreSettings.newBuilder()
.setHeaderProvider(
new FixedHeaderProvider() {
@Override
public Map<@NonNull String, @NonNull St... | host = System.getenv().getOrDefault(FIRESTORE_HOST_ENV_VARIABLE, DEFAULT_FIRESTORE_HOST); | FirestoreStub getFirestoreStub(PipelineOptions options) {
try {
FirestoreSettings.Builder builder =
FirestoreSettings.newBuilder()
.setHeaderProvider(
new FixedHeaderProvider() {
@Override
public Map<@NonNull String, @NonNull St... | class FirestoreStatefulComponentFactory implements Serializable {
private static final String DEFAULT_FIRESTORE_HOST = "batch-firestore.googleapis.com:443";
private static final String FIRESTORE_HOST_ENV_VARIABLE = "FIRESTORE_HOST";
private static final String FIRESTORE_EMULATOR_HOST_ENV_VARIABLE = "FIRESTORE_EM... | class FirestoreStatefulComponentFactory implements Serializable {
static final FirestoreStatefulComponentFactory INSTANCE = new FirestoreStatefulComponentFactory();
private FirestoreStatefulComponentFactory() {}
/**
* Given a {@link PipelineOptions}, return a pre-configured {@link FirestoreStub} with values... |
This still needs to be addressed. | private static Long getExpiresJwtClaim(String accessToken) {
String[] parts = accessToken.split("\\.");
if (parts.length == 3) {
try {
JsonObject claims = new JsonObject(new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8));
return claim... | try { | private static Long getExpiresJwtClaim(String accessToken) {
JsonObject claims = decodeJwtToken(accessToken);
if (claims != null) {
try {
return claims.getLong(Claims.exp.name());
} catch (IllegalArgumentException ex) {
LOG.debug("JWT expiry claim ... | class OidcClientImpl implements OidcClient {
private static final Logger LOG = Logger.getLogger(OidcClientImpl.class);
private static final String ACCESS_TOKEN = "access_token";
private static final String REFRESH_TOKEN = "refresh_token";
private static final String EXPIRES_AT = "expires_at";
pri... | class OidcClientImpl implements OidcClient {
private static final Logger LOG = Logger.getLogger(OidcClientImpl.class);
private static final String ACCESS_TOKEN = "access_token";
private static final String REFRESH_TOKEN = "refresh_token";
private static final String EXPIRES_AT = "expires_at";
pri... |
Yes, initializers are not added to attached function. | private void defineFunction(DataInputStream dataInStream) throws IOException {
skipPosition(dataInStream);
String funcName = getStringCPEntryValue(dataInStream);
String workerName = getStringCPEntryValue(dataInStream);
int flags = dataInStream.readInt();
BInvokableType... | structureTypeSymbol.attachedFuncs.add(attachedFunc); | private void defineFunction(DataInputStream dataInStream) throws IOException {
skipPosition(dataInStream);
String funcName = getStringCPEntryValue(dataInStream);
String workerName = getStringCPEntryValue(dataInStream);
int flags = dataInStream.readInt();
BInvokableType... | class BIRPackageSymbolEnter {
private final PackageLoader packageLoader;
private final SymbolResolver symbolResolver;
private final SymbolTable symTable;
private final Names names;
private final TypeParamAnalyzer typeParamAnalyzer;
private final BLangDiagnosticLog dlog;
private BIRTypeReader... | class BIRPackageSymbolEnter {
private final PackageLoader packageLoader;
private final SymbolResolver symbolResolver;
private final SymbolTable symTable;
private final Names names;
private final TypeParamAnalyzer typeParamAnalyzer;
private final BLangDiagnosticLog dlog;
private BIRTypeReader... |
Do we need this `exprs`? It can directly be `arrayLiteral.exprs` | 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... |
Add a comment here to explain that this is the special case where we split after removing the root of a path that is just the root. | private String[] splitToElements(String str) {
String[] arr = str.split(this.parentFileSystem.getSeparator());
if (arr.length == 1 && arr[0].isEmpty()) {
return new String[0];
}
return arr;
} | if (arr.length == 1 && arr[0].isEmpty()) { | private String[] splitToElements(String str) {
String[] arr = str.split(this.parentFileSystem.getSeparator());
/*
This is a special case where we split after removing the root from a path that is just the root. Or otherwise
have an empty path.
*/
if (arr.length == 1 && a... | class AzurePath implements Path {
private final ClientLogger logger = new ClientLogger(AzurePath.class);
private static final String ROOT_DIR_SUFFIX = ":";
private final AzureFileSystem parentFileSystem;
private final String pathString;
AzurePath(AzureFileSystem parentFileSystem, String s, String.... | class AzurePath implements Path {
private final ClientLogger logger = new ClientLogger(AzurePath.class);
private static final String ROOT_DIR_SUFFIX = ":";
private final AzureFileSystem parentFileSystem;
private final String pathString;
AzurePath(AzureFileSystem parentFileSystem, String first, Str... |
Maybe it would be better to open a JIRA issue for supporting UPSERT (as a placeholder, simply stating that the semantics need to be defined first) and then link to that ticket from here rather than the one that causes us to disallow it? What do you think? | public void validateInsert(SqlInsert insert) {
super.validateInsert(insert);
if (insert.isUpsert()) {
throw new ValidationException("UPSERT INTO statement is not supported");
}
} | public void validateInsert(SqlInsert insert) {
if (insert.isUpsert()) {
throw new ValidationException(
"UPSERT INTO statement is not supported. Please use INSERT INTO instead.");
}
} | class FlinkCalciteSqlValidator extends SqlValidatorImpl {
private SqlNode sqlNodeForExpectedOutputType;
private RelDataType expectedOutputType;
public FlinkCalciteSqlValidator(
SqlOperatorTable opTab,
SqlValidatorCatalogReader catalogReader,
RelDataTypeFactory type... | class FlinkCalciteSqlValidator extends SqlValidatorImpl {
private SqlNode sqlNodeForExpectedOutputType;
private RelDataType expectedOutputType;
public FlinkCalciteSqlValidator(
SqlOperatorTable opTab,
SqlValidatorCatalogReader catalogReader,
RelDataTypeFactory type... | |
I don't mind either. I like your substitution in principle but agree we shouldn't have substitutions when we can avoid them... my suggestion was more hypotethical about contributing a similar patch upstream: if the driver could store the `Version` initialized in a static block, we wouldn't need patching. But I wonder i... | void addNativeImageResources(BuildProducer<NativeImageResourceBuildItem> resources) {
resources.produce(new NativeImageResourceBuildItem("mariadb.properties", "driver.properties"));
} | resources.produce(new NativeImageResourceBuildItem("mariadb.properties", "driver.properties")); | void addNativeImageResources(BuildProducer<NativeImageResourceBuildItem> resources) {
resources.produce(new NativeImageResourceBuildItem("mariadb.properties"));
} | class JDBCMariaDBProcessor {
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(Feature.JDBC_MARIADB);
}
@BuildStep
void registerDriver(BuildProducer<JdbcDriverBuildItem> jdbcDriver) {
jdbcDriver.produce(
new JdbcDriverBuildItem(DatabaseKind.MARIADB... | class JDBCMariaDBProcessor {
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(Feature.JDBC_MARIADB);
}
@BuildStep
void registerDriver(BuildProducer<JdbcDriverBuildItem> jdbcDriver, BuildProducer<DefaultDataSourceDbKindBuildItem> dbKind) {
jdbcDriver.produce(
... |
We also need a ut for alter table? | public void testNormal() throws DdlException {
ExceptionChecker.expectThrowsNoException(
() -> createTable("create table test.tbl1\n" + "(k1 int, k2 int)\n" + "duplicate key(k1)\n"
+ "distributed by hash(k2) buckets 1\n" + "properties('replication_num' = '1'); "));
... | ExceptionChecker | public void testNormal() throws DdlException {
ExceptionChecker.expectThrowsNoException(
() -> createTable("create table test.tbl1\n" + "(k1 int, k2 int)\n" + "duplicate key(k1)\n"
+ "distributed by hash(k2) buckets 1\n" + "properties('replication_num' = '1'); "));
... | class CreateTableTest {
private static String runningDir = "fe/mocked/CreateTableTest2/" + UUID.randomUUID().toString() + "/";
private static ConnectContext connectContext;
@BeforeClass
public static void beforeClass() throws Exception {
Config.disable_storage_medium_check = true;
UtFr... | class CreateTableTest {
private static String runningDir = "fe/mocked/CreateTableTest2/" + UUID.randomUUID().toString() + "/";
private static ConnectContext connectContext;
@BeforeClass
public static void beforeClass() throws Exception {
Config.disable_storage_medium_check = true;
UtFr... |
Ok, let's start with `CLASS`... | private List<BeanInfo> findMatching(TypeAndQualifiers typeAndQualifiers) {
List<BeanInfo> resolved = new ArrayList<>();
Collection<BeanInfo> potentialBeans = typeAndQualifiers.type.kind() == CLASS
? beanDeployment.getBeansByType(typeAndQualifiers.type)
: beanDepl... | Collection<BeanInfo> potentialBeans = typeAndQualifiers.type.kind() == CLASS | private List<BeanInfo> findMatching(TypeAndQualifiers typeAndQualifiers) {
List<BeanInfo> resolved = new ArrayList<>();
Collection<BeanInfo> potentialBeans = typeAndQualifiers.type.kind() == CLASS
? beanDeployment.getBeansByType(typeAndQualifiers.type)
: beanDepl... | class BeanResolverImpl implements BeanResolver {
private final BeanDeployment beanDeployment;
private final Map<TypeAndQualifiers, List<BeanInfo>> resolved;
BeanResolverImpl(BeanDeployment beanDeployment) {
this.beanDeployment = beanDeployment;
this.resolved = new ConcurrentHashMap<>();
... | class BeanResolverImpl implements BeanResolver {
private final BeanDeployment beanDeployment;
private final Map<TypeAndQualifiers, List<BeanInfo>> resolved;
BeanResolverImpl(BeanDeployment beanDeployment) {
this.beanDeployment = beanDeployment;
this.resolved = new ConcurrentHashMap<>();
... |
The error msg is confusing. The `if` says `not a client local file`, but err msg says "not support local file from client"? | private void handleLoadStmt() {
try {
LoadStmt loadStmt = (LoadStmt) parsedStmt;
EtlJobType jobType = loadStmt.getEtlJobType();
if (jobType == EtlJobType.UNKNOWN) {
throw new DdlException("Unknown load job type");
}
if (jobType == EtlJo... | throw new DdlException("Doris server does not support load local file from mysql client."); | private void handleLoadStmt() {
try {
LoadStmt loadStmt = (LoadStmt) parsedStmt;
EtlJobType jobType = loadStmt.getEtlJobType();
if (jobType == EtlJobType.UNKNOWN) {
throw new DdlException("Unknown load job type");
}
if (jobType == EtlJo... | class StmtExecutor implements ProfileWriter {
private static final Logger LOG = LogManager.getLogger(StmtExecutor.class);
private static final AtomicLong STMT_ID_GENERATOR = new AtomicLong(0);
private static final int MAX_DATA_TO_SEND_FOR_TXN = 100;
private static final String NULL_VALUE_FOR_LOAD = "\\... | class StmtExecutor implements ProfileWriter {
private static final Logger LOG = LogManager.getLogger(StmtExecutor.class);
private static final AtomicLong STMT_ID_GENERATOR = new AtomicLong(0);
private static final int MAX_DATA_TO_SEND_FOR_TXN = 100;
private static final String NULL_VALUE_FOR_LOAD = "\\... |
I wonder if you shouldn't just rely exclusively on `agroalSupport.entries` and get rid of `support.getConfiguredNames()` altogether. `support.getConfiguredNames()` is sometimes returning non-agroal datasource names (which you're working around here), and I've noticed before (#37779) that it may not even return the name... | protected void init() {
if (!dataSources.isResolvable()) {
return;
}
DataSourceSupport support = Arc.container().instance(DataSourceSupport.class)
.get();
AgroalDataSourceSupport agroalSupport = Arc.container().instance(AgroalDataSourceSupport.cla... | Set<String> names = support.getConfiguredNames(); | protected void init() {
if (!dataSources.isResolvable()) {
return;
}
DataSourceSupport support = Arc.container().instance(DataSourceSupport.class)
.get();
AgroalDataSourceSupport agroalSupport = Arc.container().instance(AgroalDataSourceSupport.cla... | class DataSourceHealthCheck implements HealthCheck {
@Inject
Instance<DataSources> dataSources;
private final Map<String, DataSource> checkedDataSources = new HashMap<>();
@PostConstruct
@Override
public HealthCheckResponse call() {
HealthCheckResponseBuilder builder = HealthChe... | class DataSourceHealthCheck implements HealthCheck {
@Inject
Instance<DataSources> dataSources;
private final Map<String, DataSource> checkedDataSources = new HashMap<>();
@PostConstruct
@Override
public HealthCheckResponse call() {
HealthCheckResponseBuilder builder = HealthChe... |
@heyams I pushed this to show an option that avoids relying on the (confusing to me at least) `additionalProperties` (here's the full commit I pushed: https://github.com/Azure/azure-sdk-for-java/pull/41106/commits/75f6fe2845fb0e22d7a73afdf1d3beedc3723f2c) | private static void validateSpan(TelemetryItem telemetryItem) throws IOException {
assertThat(telemetryItem.getName()).isEqualTo("RemoteDependency");
assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY);
assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role... | RemoteDependencyData actualData = toRemoteDependencyData(telemetryItem.getData().getBaseData()); | private static void validateSpan(TelemetryItem telemetryItem) {
assertThat(telemetryItem.getName()).isEqualTo("RemoteDependency");
assertThat(telemetryItem.getInstrumentationKey()).isEqualTo(INSTRUMENTATION_KEY);
assertThat(telemetryItem.getTags()).containsEntry("ai.cloud.role", "unknown_service... | class AzureMonitorExportersEndToEndTest extends MonitorExporterClientTestBase {
private static final String CONNECTION_STRING_ENV =
"InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;"
+ "IngestionEndpoint=https:
+ "LiveEndpoint=https:
private static final String INSTRUME... | class AzureMonitorExportersEndToEndTest extends MonitorExporterClientTestBase {
private static final String CONNECTION_STRING_ENV =
"InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;"
+ "IngestionEndpoint=https:
+ "LiveEndpoint=https:
private static final String INSTRUME... |
Since there is only one usage, no need to define a separate variable. ```suggestion switch (nextToken.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... | switch (nextTokenKind) { | 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... |
Actually, we require Jandex 2.1+ and re-index dependencies if necessary (https://github.com/quarkusio/quarkus/blob/master/core/deployment/src/main/java/io/quarkus/deployment/index/ApplicationArchiveBuildStep.java#L200-L202). So `hasNoArgsConstructor()` should be enough. I'll update the PR. | public void addMissingConstructors() throws Exception {
Set<ClassInfo> targetClasses = new HashSet<>();
Set<DotName> normalScopes = initNormalScopes();
for (DotName normalScope : normalScopes) {
collectTargetClasses(targetClasses, normalScope);
}
for (Iterator<ClassI... | || targetClass.methods().stream().anyMatch(m -> m.name().equals("<init>") && m.parameters().isEmpty())) { | public void addMissingConstructors() throws Exception {
Set<ClassInfo> targetClasses = new HashSet<>();
Set<DotName> normalScopes = initNormalScopes();
for (DotName normalScope : normalScopes) {
collectTargetClasses(targetClasses, normalScope);
}
for (Iterator<ClassI... | class NoArgsConstructorProcessor {
private static final Logger LOGGER = Logger.getLogger(NoArgsConstructorProcessor.class);
private static final int ANNOTATION = 0x00002000;
@Inject
BeanArchiveIndexBuildItem beanArchiveIndex;
@Inject
CombinedIndexBuildItem combinedIndex;
@Inje... | class NoArgsConstructorProcessor {
private static final Logger LOGGER = Logger.getLogger(NoArgsConstructorProcessor.class);
private static final int ANNOTATION = 0x00002000;
@Inject
BeanArchiveIndexBuildItem beanArchiveIndex;
@Inject
CombinedIndexBuildItem combinedIndex;
@Inje... |
possible NPE if the volume of the svId not exist? | public String getStorageVolumeName(String svId) {
try (LockCloseable lock = new LockCloseable(rwLock.readLock())) {
return getStorageVolume(svId).getName();
}
} | return getStorageVolume(svId).getName(); | public String getStorageVolumeName(String svId) {
try (LockCloseable lock = new LockCloseable(rwLock.readLock())) {
StorageVolume sv = getStorageVolume(svId);
if (sv == null) {
return "";
}
return getStorageVolume(svId).getName();
}
} | class StorageVolumeMgr implements GsonPostProcessable {
private static final String ENABLED = "enabled";
public static final String DEFAULT = "default";
public static final String LOCAL = "local";
public static final String BUILTIN_STORAGE_VOLUME = "builtin_storage_volume";
@SerializedName("defa... | class StorageVolumeMgr implements GsonPostProcessable {
private static final String ENABLED = "enabled";
public static final String DEFAULT = "default";
public static final String LOCAL = "local";
public static final String BUILTIN_STORAGE_VOLUME = "builtin_storage_volume";
@SerializedName("defa... |
Can a lang lib invocation requiredArgs be empty at desugar? | private BLangBlockStmt desugarForeachToWhile(BLangForeach foreach, BLangSimpleVariableDef varDef) {
... | if (!invocation.requiredArgs.isEmpty() && invocation.langLibInvocation) { | 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... |
It would be safer to use `cacheMaxSize <= 0 || cacheExpireMs <= 0`. | public void open(FunctionContext context) {
LOG.info("start open ...");
Configuration config = prepareRuntimeConfiguration();
CompletableFuture<AsyncConnection> asyncConnectionFuture = ConnectionFactory.createAsyncConnection(config);
try {
asyncConnection = asyncConnectionFut... | this.cache = cacheMaxSize == -1 || cacheExpireMs == 0 ? null : CacheBuilder.newBuilder() | public void open(FunctionContext context) {
LOG.info("start open ...");
final ExecutorService threadPool =
Executors.newFixedThreadPool(
THREAD_POOL_SIZE,
new ExecutorThreadFactory(
"hbase-aysnc-lookup-worker... | class HBaseRowDataAsyncLookupFunction extends AsyncTableFunction<RowData> {
private static final Logger LOG = LoggerFactory.getLogger(HBaseRowDataAsyncLookupFunction.class);
private static final long serialVersionUID = 1L;
private final String hTableName;
private final byte[] serializedConfig;
pri... | class HBaseRowDataAsyncLookupFunction extends AsyncTableFunction<RowData> {
private static final Logger LOG =
LoggerFactory.getLogger(HBaseRowDataAsyncLookupFunction.class);
private static final long serialVersionUID = 1L;
private final String hTableName;
private final byte[] serializedCon... |
Okay, I added a test for this case as well. But this required adding the MonitoringInfoSpec for SampledByteCount, which I was going to do in this PR which is queued up after this one. But I have pulled it into this PR. https://github.com/apache/beam/pull/8416/files | public void testMonitoringInfosArePopulatedForUserDistributions() {
MetricsContainerImpl testObject = new MetricsContainerImpl("step1");
DistributionCell c1 = testObject.getDistribution(MetricName.named("ns", "name1"));
DistributionCell c2 = testObject.getDistribution(MetricName.named("ns", "name2"));
c... | DistributionCell c2 = testObject.getDistribution(MetricName.named("ns", "name2")); | public void testMonitoringInfosArePopulatedForUserDistributions() {
MetricsContainerImpl testObject = new MetricsContainerImpl("step1");
DistributionCell c1 = testObject.getDistribution(MetricName.named("ns", "name1"));
DistributionCell c2 = testObject.getDistribution(MetricName.named("ns", "name2"));
c... | class MetricsContainerImplTest {
@Test
public void testCounterDeltas() {
MetricsContainerImpl container = new MetricsContainerImpl("step1");
CounterCell c1 = container.getCounter(MetricName.named("ns", "name1"));
CounterCell c2 = container.getCounter(MetricName.named("ns", "name2"));
assertThat(
... | class MetricsContainerImplTest {
@Test
public void testCounterDeltas() {
MetricsContainerImpl container = new MetricsContainerImpl("step1");
CounterCell c1 = container.getCounter(MetricName.named("ns", "name1"));
CounterCell c2 = container.getCounter(MetricName.named("ns", "name2"));
assertThat(
... |
If no transformers are registered, this method should return the original set of annotations immediately. | public Set<AnnotationInstance> applyTransformers(Type type, AnnotationTarget target, Set<AnnotationInstance> qualifiers) {
TransformationContextImpl transformationContext = new TransformationContextImpl(target, qualifiers,
annotationStore);
for (InjectionPointsTransformer transformer : t... | transformer.transform(transformationContext); | public Set<AnnotationInstance> applyTransformers(Type type, AnnotationTarget target, Set<AnnotationInstance> qualifiers) {
if (transformers.isEmpty()) {
return qualifiers;
}
TransformationContextImpl transformationContext = new TransformationContextImpl(target, qualifiers,
... | class InjectionPointModifier {
private List<InjectionPointsTransformer> transformers;
private BuildExtension.BuildContext buildContext;
private AnnotationStore annotationStore;
InjectionPointModifier(List<InjectionPointsTransformer> tranformers, BuildExtension.BuildContext buildContext) {
this... | class InjectionPointModifier {
private List<InjectionPointsTransformer> transformers;
private BuildExtension.BuildContext buildContext;
private AnnotationStore annotationStore;
InjectionPointModifier(List<InjectionPointsTransformer> transformers, BuildExtension.BuildContext buildContext) {
thi... |
Nothing else @menghaoranss. Will make that commit soon | public void watch(final String key, final DataChangedEventListener dataChangedEventListener) {
Watch.Listener listener = Watch.listener(response -> {
for (WatchEvent each : response.getEvents()) {
ChangedType changedType = getEventChangedType(each);
if (ChangedType.IG... | , each.getKeyValue().getValue().toString(StandardCharsets.UTF_8), changedType)); | public void watch(final String key, final DataChangedEventListener dataChangedEventListener) {
Watch.Listener listener = Watch.listener(response -> {
for (WatchEvent each : response.getEvents()) {
ChangedType changedType = getEventChangedType(each);
if (ChangedType.IG... | class EtcdRepository implements ConfigurationRepository, RegistryRepository {
private Client client;
@Getter
@Setter
private Properties props = new Properties();
private EtcdProperties etcdProperties;
@Override
public void init(final String name, final GovernanceCenterConfigurati... | class EtcdRepository implements ConfigurationRepository, RegistryRepository {
private Client client;
@Getter
@Setter
private Properties props = new Properties();
private EtcdProperties etcdProperties;
@Override
public void init(final String name, final GovernanceCenterConfigurati... |
If a ballerina test fails it will anyway have the mentioned text in the program output. But, if it fails due to a compilation error, this fails to capture that. So, I'll add an else statement to capture unforeseen errors. | public static void assertForTestFailures(String programOutput, String errMessage) throws BallerinaTestException {
if (programOutput.contains("error: there are test failures")) {
throw new BallerinaTestException("Test failed due to " + errMessage + " in test framework");
}
} | if (programOutput.contains("error: there are test failures")) { | public static void assertForTestFailures(String programOutput, String errMessage) throws BallerinaTestException {
if (programOutput.contains("error: there are test failures")) {
throw new BallerinaTestException("Test failed due to " + errMessage + " in test framework");
} else if (programOut... | class AssertionUtils {
} | class AssertionUtils {
} |
```suggestion // as "." are ignored. This is to be consistent with the "ballerina test" command, which only executes tests ``` | public void execute(BuildContext buildContext) {
Path sourceRootPath = buildContext.get(BuildContextField.SOURCE_ROOT);
Map<BLangPackage, TestarinaClassLoader> programFileMap = new HashMap<>();
List<BLangPackage> moduleBirMap = buildContext.getModules();
for (... | public void execute(BuildContext buildContext) {
Path sourceRootPath = buildContext.get(BuildContextField.SOURCE_ROOT);
Map<BLangPackage, TestarinaClassLoader> programFileMap = new HashMap<>();
List<BLangPackage> moduleBirMap = buildContext.getModules();
for (... | class ListTestGroupsTask implements Task {
@Override
} | class ListTestGroupsTask implements Task {
@Override
} | |
Normally, Context, like the name describes, does not do actions | public Collection<Integer> transform(Transformation<?> transformation) {
return streamGraphGenerator.transform(transformation);
} | return streamGraphGenerator.transform(transformation); | public Collection<Integer> transform(Transformation<?> transformation) {
return streamGraphGenerator.transform(transformation);
} | class ContextImpl implements TransformationTranslator.Context {
private final StreamGraphGenerator streamGraphGenerator;
private final StreamGraph streamGraph;
private final String slotSharingGroup;
private final ReadableConfig config;
public ContextImpl(
fin... | class ContextImpl implements TransformationTranslator.Context {
private final StreamGraphGenerator streamGraphGenerator;
private final StreamGraph streamGraph;
private final String slotSharingGroup;
private final ReadableConfig config;
public ContextImpl(
fin... |
Would it be possible to add test case for bw compatible code path? | public Params decode(InputStream inStream) throws IOException {
String prefix = STRING_CODER.decode(inStream);
String shardTemplate = STRING_CODER.decode(inStream);
String suffix = STRING_CODER.decode(inStream);
ResourceId baseFilename;
if (inStream.available() > 0) {
baseFilename ... | baseFilename = FileBasedSink.convertToFileResourceIfPossible(prefix); | public Params decode(InputStream inStream) throws IOException {
ResourceId prefix =
FileBasedSink.convertToFileResourceIfPossible(STRING_CODER.decode(inStream));
String shardTemplate = STRING_CODER.decode(inStream);
String suffix = STRING_CODER.decode(inStream);
return new Params()
... | class ParamsCoder extends AtomicCoder<Params> {
private static final ParamsCoder INSTANCE = new ParamsCoder();
private static final Coder<String> STRING_CODER = StringUtf8Coder.of();
private static final Coder<Boolean> BOOLEAN_CODER = BooleanCoder.of();
public static ParamsCoder of() {
return INS... | class ParamsCoder extends AtomicCoder<Params> {
private static final ParamsCoder INSTANCE = new ParamsCoder();
private static final Coder<String> STRING_CODER = StringUtf8Coder.of();
public static ParamsCoder of() {
return INSTANCE;
}
@Override
public void encode(Params value, OutputStre... |
I think we can dlog here since rest param can only be of array type? | public void visit(BLangTupleVarRef varRefExpr) {
List<BType> results = new ArrayList<>();
for (int i = 0; i < varRefExpr.expressions.size(); i++) {
((BLangVariableReference) varRefExpr.expressions.get(i)).lhsVar = true;
results.add(checkExpr(varRefExpr.expressions.get(i), env, sy... | actualType.restType = checkedType; | public void visit(BLangTupleVarRef varRefExpr) {
List<BType> results = new ArrayList<>();
for (int i = 0; i < varRefExpr.expressions.size(); i++) {
((BLangVariableReference) varRefExpr.expressions.get(i)).lhsVar = true;
results.add(checkExpr(varRefExpr.expressions.get(i), env, sy... | class TypeChecker extends BLangNodeVisitor {
private static final CompilerContext.Key<TypeChecker> TYPE_CHECKER_KEY =
new CompilerContext.Key<>();
private static final String TABLE_TNAME = "table";
private Names names;
private SymbolTable symTable;
private SymbolEnter symbolEnter;
... | class TypeChecker extends BLangNodeVisitor {
private static final CompilerContext.Key<TypeChecker> TYPE_CHECKER_KEY =
new CompilerContext.Key<>();
private static final String TABLE_TNAME = "table";
private Names names;
private SymbolTable symTable;
private SymbolEnter symbolEnter;
... |
How is `update` different from `updateInternal` From reading their comments, it seems they are different somehow, but the changelogger seems to be same. Similar to other states. | public void updateInternal(List<V> valueToStore) throws Exception {
changeLogger.stateUpdated(valueToStore, getCurrentNamespace());
delegatedState.updateInternal(valueToStore);
} | changeLogger.stateUpdated(valueToStore, getCurrentNamespace()); | public void updateInternal(List<V> valueToStore) throws Exception {
delegatedState.updateInternal(valueToStore);
changeLogger.valueUpdatedInternal(valueToStore, getCurrentNamespace());
} | class ChangelogListState<K, N, V>
extends AbstractChangelogState<K, N, List<V>, InternalListState<K, N, V>>
implements InternalListState<K, N, V> {
ChangelogListState(
InternalListState<K, N, V> delegatedState,
KvStateChangeLogger<List<V>, N> changeLogger) {
super(de... | class ChangelogListState<K, N, V>
extends AbstractChangelogState<K, N, List<V>, InternalListState<K, N, V>>
implements InternalListState<K, N, V> {
ChangelogListState(
InternalListState<K, N, V> delegatedState,
KvStateChangeLogger<List<V>, N> changeLogger) {
super(de... |
I created an issue for this. #32034 | public void visit(BLangArrayType arrayTypeNode) {
resultType = resolveTypeNode(arrayTypeNode.elemtype, env, diagCode);
if (resultType == symTable.noType) {
return;
}
boolean isError = false;
for (int i = 0; i < arrayTypeNode.dimensions; i++) {
... | long lengthCheck = Long.parseLong(sizeConstSymbol.type.toString()); | public void visit(BLangArrayType arrayTypeNode) {
resultType = resolveTypeNode(arrayTypeNode.elemtype, env, diagCode);
if (resultType == symTable.noType) {
return;
}
boolean isError = false;
for (int i = 0; i < arrayTypeNode.dimensions; i++) {
... | class SymbolResolver extends BLangNodeVisitor {
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 10;
private static final CompilerContext.Key<SymbolResolver> SYMBOL_RESOLVER_KEY =
new CompilerContext.Key<>();
private SymbolTable symTable;
private Names names;
private BLang... | class SymbolResolver extends BLangNodeVisitor {
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 10;
private static final CompilerContext.Key<SymbolResolver> SYMBOL_RESOLVER_KEY =
new CompilerContext.Key<>();
private SymbolTable symTable;
private Names names;
private BLang... |
Why is Vert.x mentioned here? | AdditionalBeanBuildItem createCDIEventConsumer() {
return AdditionalBeanBuildItem.builder()
.addBeanClass(KAFKA_EVENT_CONSUMER_CLASS_NAME)
.setUnremovable().build();
} | AdditionalBeanBuildItem createCDIEventConsumer() {
return AdditionalBeanBuildItem.builder()
.addBeanClass(KAFKA_EVENT_CONSUMER_CLASS_NAME)
.setUnremovable().build();
} | class KafkaSupportEnabled implements BooleanSupplier {
MicrometerConfig mConfig;
public boolean getAsBoolean() {
return KAFKA_CONSUMER_CLASS_CLASS != null && mConfig.checkBinderEnabledWithDefault(mConfig.binder.kafka);
}
} | class KafkaSupportEnabled implements BooleanSupplier {
MicrometerConfig mConfig;
public boolean getAsBoolean() {
return KAFKA_CONSUMER_CLASS_CLASS != null && mConfig.checkBinderEnabledWithDefault(mConfig.binder.kafka);
}
} | |
Hm, this means that we only support field injection. In fact, we can simply iterate over all injection points: ```java for (InjectionPointInfo injectionPoint : validationContext.get(Key.INJECTION_POINTS)) { // TODO } ``` I'll try to update this PR in a moment... | public void validate(ValidationContext validationContext) {
AnnotationStore annotationStore = validationContext.get(Key.ANNOTATION_STORE);
for (BeanInfo bean : validationContext.get(Key.BEANS)) {
if (bean.isClassBean()) {
... | for (FieldInfo field : ci.fields()) { | public void validate(ValidationContext validationContext) {
AnnotationStore annotationStore = validationContext.get(Key.ANNOTATION_STORE);
for (BeanInfo bean : validationContext.get(Key.BEANS)) {
if (bean.isClassBean()) {
... | class SmallRyeReactiveMessagingProcessor {
private static final Logger LOGGER = Logger.getLogger("io.quarkus.smallrye-reactive-messaging.deployment.processor");
static final DotName NAME_INCOMING = DotName.createSimple(Incoming.class.getName());
static final DotName NAME_OUTGOING = DotName.createSimple(Ou... | class SmallRyeReactiveMessagingProcessor {
private static final Logger LOGGER = Logger.getLogger("io.quarkus.smallrye-reactive-messaging.deployment.processor");
static final DotName NAME_INCOMING = DotName.createSimple(Incoming.class.getName());
static final DotName NAME_OUTGOING = DotName.createSimple(Ou... |
I've now replaced this with a `RestAssured.get("/")` call to trigger the application restart (I am not aware of any better way to do this) and instead verify the response to `GET /flyway/current-version` inside the Awaitility assertion. | public void testRepairUsingDevMode() {
String version = RestAssured.get("/flyway/current-version").then().statusCode(200).extract().asString();
assertEquals("1.0.0", version);
config.clearLogRecords();
config.modifyResourceFile("db/migration/V1.0.0__Quarkus.sql", s -> s + "\nalter table... | RestAssured.get("/flyway/current-version").thenReturn(); | public void testRepairUsingDevMode() {
assertThat(RestAssured.get("/flyway/current-version").then().statusCode(200).extract().asString()).isEqualTo("1.0.0");
config.clearLogRecords();
config.modifyResourceFile("db/migration/V1.0.0__Quarkus.sql", s -> s + "\nNONSENSE STATEMENT CHANGING CHECKSUM;... | class FlywayExtensionRepairAtStartTest {
@RegisterExtension
static final QuarkusDevModeTest config = new QuarkusDevModeTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClass(FlywayResource.class)
.addAsResource("db/migration/V1.0.0__Q... | class FlywayExtensionRepairAtStartTest {
@RegisterExtension
static final QuarkusDevModeTest config = new QuarkusDevModeTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClass(FlywayResource.class)
.addAsResource("db/migration/V1.0.0__Q... |
It says in the javadoc for ResourceId.java that a resource id represents a file-like resource, so AzfsResourceId does not support resource id's without a container. | public boolean isContainer() {
return blob == null;
} | return blob == null; | public boolean isContainer() {
return blob == null;
} | class AzfsResourceId implements ResourceId {
static final String SCHEME = "azfs";
private static final Pattern AZFS_URI =
Pattern.compile("(?<SCHEME>[^:]+):
/** Matches a glob containing a wildcard, capturing the portion before the first wildcard. */
private static final Pattern GLOB_PREFIX = Pattern.com... | class AzfsResourceId implements ResourceId {
static final String SCHEME = "azfs";
private static final Pattern AZFS_URI =
Pattern.compile("(?<SCHEME>[^:]+):
/** Matches a glob containing a wildcard, capturing the portion before the first wildcard. */
private static final Pattern GLOB_PREFIX = Pattern.com... |
Is it possible to find a more specific exception type? RuntimeException is generally only viewed as abstract base class. Maybe IllegalStateException, or InvalidArgumentException (if we take that defaultSubscription only works for 1 subscription). | public Azure withDefaultSubscription() {
if (profile.subscriptionId() == null) {
List<Subscription> subscriptions = new ArrayList<>();
this.subscriptions().list().forEach(subscription -> {
subscriptions.add(subscription);
});
... | new RuntimeException("Please create a subscription before you start resource management. " | public Azure withDefaultSubscription() {
if (profile.subscriptionId() == null) {
profile.withSubscriptionId(Utils.defaultSubscription(this.subscriptions().list()));
}
return new Azure(httpPipeline, profile, this);
} | class AuthenticatedImpl implements Authenticated {
private final ClientLogger logger = new ClientLogger(AuthenticatedImpl.class);
private final HttpPipeline httpPipeline;
private final AzureProfile profile;
private final ResourceManager.Authenticated resourceManagerAuthenticated;
... | class AuthenticatedImpl implements Authenticated {
private final HttpPipeline httpPipeline;
private final AzureProfile profile;
private final ResourceManager.Authenticated resourceManagerAuthenticated;
private final GraphRbacManager graphRbacManager;
private SdkContext sdkContext... |
Consider adding factory function for `NodeEvent.forBucketSpace` to avoid overloading confusion | private static NodeEvent createNodeEvent(NodeInfo nodeInfo, String description, PerStateParams params) {
if (params.bucketSpace.isPresent()) {
return new NodeEvent(nodeInfo, params.bucketSpace.get(), description, NodeEvent.Type.CURRENT, params.currentTime);
} else {
return new No... | return new NodeEvent(nodeInfo, params.bucketSpace.get(), description, NodeEvent.Type.CURRENT, params.currentTime); | private static NodeEvent createNodeEvent(NodeInfo nodeInfo, String description, PerStateParams params) {
if (params.bucketSpace.isPresent()) {
return NodeEvent.forBucketSpace(nodeInfo, params.bucketSpace.get(), description, NodeEvent.Type.CURRENT, params.currentTime);
} else {
re... | class PerStateParams {
final ContentCluster cluster;
final Optional<String> bucketSpace;
final AnnotatedClusterState fromState;
final AnnotatedClusterState toState;
final long currentTime;
PerStateParams(ContentCluster cluster,
Optional<String> buc... | class PerStateParams {
final ContentCluster cluster;
final Optional<String> bucketSpace;
final AnnotatedClusterState fromState;
final AnnotatedClusterState toState;
final long currentTime;
PerStateParams(ContentCluster cluster,
Optional<String> buc... |
Was this required for all or just one of the tests? | static void beforeAll() throws InterruptedException {
TimeUnit.SECONDS.sleep(180);
StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
} | TimeUnit.SECONDS.sleep(180); | static void beforeAll() throws InterruptedException {
TimeUnit.SECONDS.sleep(180);
StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
} | class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase {
private TextAnalyticsAsyncClient client;
@BeforeAll
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
private HttpClient buildAsyncAssertingClient(HttpClient httpClient) {
retu... | class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase {
private TextAnalyticsAsyncClient client;
@BeforeAll
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
private HttpClient buildAsyncAssertingClient(HttpClient httpClient) {
retu... |
Will need a design or documentation in the case if there is a row that does not match the schema. If you check pubsub json support, it supports a dead letter queue that sends rows to that queue if those rows does not match with the schema. You might reuse the same design. | public PCollection<Row> expand(PCollection<String> input) {
return input
.apply(
ParDo.of(
new DoFn<String, Row>() {
@ProcessElement
public void processElement(ProcessContext context) {
context.output(jsonToRow... | public void processElement(ProcessContext context) { | public PCollection<Row> expand(PCollection<String> input) {
return input
.apply(
"linesToRows",
MapElements.into(TypeDescriptors.rows())
.via(s -> Row.withSchema(SCHEMA).addValue(s).build()))
.setRowSchema(SCHEMA);
} | class LinesReadConverter extends PTransform<PCollection<String>, PCollection<Row>>
implements Serializable {
private static final Schema SCHEMA = Schema.builder().addStringField("line").build();
public LinesReadConverter() {}
@Override
} | class LinesReadConverter extends PTransform<PCollection<String>, PCollection<Row>>
implements Serializable {
private static final Schema SCHEMA = Schema.builder().addStringField("line").build();
public LinesReadConverter() {}
@Override
} |
Could we add requestId generator? There're much hard-coded code for now | public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) {
if (evt instanceof CreateSubscriptionEvent) {
Builder builder = CDCRequest.newBuilder();
builder.setCreateSubscription(buildCreateSubscriptionRequest());
builder.setRequestId(UUID.randomUUID()... | builder.setRequestId(UUID.randomUUID().toString()); | public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) {
if (evt instanceof CreateSubscriptionEvent) {
CDCRequest request = CDCRequest.newBuilder().setCreateSubscription(buildCreateSubscriptionRequest()).setRequestId(RequestIdUtil.generateRequestId()).build();
... | class SubscriptionRequestHandler extends ChannelInboundHandlerAdapter {
@Override
private CreateSubscriptionRequest buildCreateSubscriptionRequest() {
return CreateSubscriptionRequest.newBuilder().setSubscriptionMode(SubscriptionMode.INCREMENTAL).setSubscriptionName("sharding_db").setData... | class SubscriptionRequestHandler extends ChannelInboundHandlerAdapter {
@Override
private CreateSubscriptionRequest buildCreateSubscriptionRequest() {
TableName tableName = TableName.newBuilder().build();
return CreateSubscriptionRequest.newBuilder().setSubscriptionMode(S... |
According to your Comment, fixed in new version. | public void run() throws InterruptedException {
ServiceBusSenderClient senderClient = new ServiceBusClientBuilder()
.connectionString(connectionString)
.sender()
.queueName(queueName)
.buildClient();
sendMessagesAsync(senderClient, 1);
de... | sendMessagesAsync(senderClient, 1); | public void run() {
final String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING");
final String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME");
final ServiceBusClien... | class DeadletterQueueSample {
String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING");
String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME");
/**
* Main method to show how to dead letter within an Azure Service Bus Queue.
*
* @param args Unuse... | class DeadletterQueueSample {
private final List<Person> personList = Arrays.asList(
new Person("Einstein", "Albert"),
new Person("Heisenberg", "Werner"),
new Person("Curie", "Marie"),
new Person("Hawking", "Steven"),
new Person("Newton", "Isaac"),
new Person("Bohr", ... |
Thanks @snuyanzin, I'm trying to support `RESPECT NULLS | IGNORE NULLS` syntax. | Stream<TestSpec> getTestCaseSpecs() {
return Stream.of(
TestSpec.forFunction(BuiltInFunctionDefinitions.ARRAY_AGG)
.withDescription("ARRAY changelog stream aggregation")
.withSource(
ROW(STRING(), INT()),
... | Row.of("D", null), | Stream<TestSpec> getTestCaseSpecs() {
return Stream.of(
TestSpec.forFunction(BuiltInFunctionDefinitions.ARRAY_AGG)
.withDescription("ARRAY changelog stream aggregation")
.withSource(
ROW(STRING(), INT()),
... | class ArrayAggFunctionITCase extends BuiltInAggregateFunctionTestBase {
@Override
} | class ArrayAggFunctionITCase extends BuiltInAggregateFunctionTestBase {
@Override
} |
The main part of the fix is `GeneratedClassGizmoAdaptor.isApplicationClass(name)` -> `GeneratedClassGizmoAdaptor.isApplicationClass(className)`! | public boolean test(String name) {
int idx = name.lastIndexOf(SUFFIX);
String className = name.substring(0, idx).replace("/", ".");
if (className.contains(ValueResolverGenerator.NESTED_SEPARATOR)) {
className = className.replace(ValueResolverGenerator.NES... | return GeneratedClassGizmoAdaptor.isApplicationClass(className); | public boolean test(String name) {
int idx = name.lastIndexOf(SUFFIX);
String className = name.substring(0, idx).replace("/", ".");
if (className.contains(ValueResolverGenerator.NESTED_SEPARATOR)) {
className = className.replace(ValueResolverGenerator.NES... | class AppClassPredicate implements Predicate<String> {
private final Function<String, String> additionalClassNameSanitizer;
public AppClassPredicate() {
this(Function.identity());
}
public AppClassPredicate(Function<String, String> additionalClassNameSanitizer) {
... | class AppClassPredicate implements Predicate<String> {
private final Function<String, String> additionalClassNameSanitizer;
public AppClassPredicate() {
this(Function.identity());
}
public AppClassPredicate(Function<String, String> additionalClassNameSanitizer) {
... |
We could make this a normal GET that just uses the values from the persisted settings. | private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request);
if (path.matches(... | if (path.matches("/application/v4/tenant/{tenant}/secret-store/{name}/validate")) return validateSecretStore(path.get("tenant"), path.get("name"), request); | private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request);
if (path.matches(... | class ApplicationApiHandler extends LoggingRequestHandler {
private static final ObjectMapper jsonMapper = new ObjectMapper();
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
private final TestCo... | class ApplicationApiHandler extends LoggingRequestHandler {
private static final ObjectMapper jsonMapper = new ObjectMapper();
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
private final TestCo... |
I think this TODO for a stream factory should be commented on the `streamFactory`. | public Optional<MaterializationRunnable> initMaterialization() throws Exception {
SequenceNumber upTo = getLastAppendedTo();
SequenceNumber lastMaterializedTo = changelogSnapshotState.lastMaterializedTo();
LOG.info(
"Initialize Materialization. Current changelog writers last app... | public Optional<MaterializationRunnable> initMaterialization() throws Exception {
SequenceNumber upTo = getLastAppendedTo();
SequenceNumber lastMaterializedTo = changelogSnapshotState.lastMaterializedTo();
LOG.info(
"Initialize Materialization. Current changelog writers last app... | class ChangelogKeyedStateBackend<K>
implements CheckpointableKeyedStateBackend<K>,
CheckpointListener,
TestableKeyedStateBackend<K> {
private static final Logger LOG = LoggerFactory.getLogger(ChangelogKeyedStateBackend.class);
/**
* ChangelogStateBackend only suppor... | class ChangelogKeyedStateBackend<K>
implements CheckpointableKeyedStateBackend<K>,
CheckpointListener,
TestableKeyedStateBackend<K> {
private static final Logger LOG = LoggerFactory.getLogger(ChangelogKeyedStateBackend.class);
/**
* ChangelogStateBackend only suppor... | |
Removed the modified error and provided the error generated by tree parser as it is. [`40558c7`](https://github.com/ballerina-platform/ballerina-lang/pull/37273/commits/40558c760c4979669408d0beed2760ea15600a44) | public BalShellGetResultResponse getResult(String source) {
BalShellGetResultResponse output = new BalShellGetResultResponse();
PrintStream originalOut = System.out;
PrintStream originalErr = System.err;
ConsoleOutCollector consoleOutCollector = new ConsoleOutCollector();
PrintSt... | "Please note that Ballerina shell commands are not supported in here.")); | public BalShellGetResultResponse getResult(String source) {
BalShellGetResultResponse output = new BalShellGetResultResponse();
PrintStream originalOut = System.out;
PrintStream originalErr = System.err;
ConsoleOutCollector consoleOutCollector = new ConsoleOutCollector();
PrintSt... | class InstanceHolder {
private static final ShellWrapper instance = new ShellWrapper();
} | class InstanceHolder {
private static final ShellWrapper instance = new ShellWrapper();
} |
Maybe we could further provide an utility for creating Execution like below: ``` private CompletableFuture<Execution> createExecution( TaskManagerGateway taskManagerGateway, JobVertex... vertices) throws Exception { SimpleSlot slot = new SimpleSlot( new SingleSlotTestingSlotOwner(), new LocalTaskManagerLo... | private void testPartitionReleaseAfterFinished(Consumer<Execution> postFinishedExecutionAction) throws Exception {
final Tuple2<JobID, Collection<ResultPartitionID>> releasedPartitions = Tuple2.of(null, null);
final SimpleAckingTaskManagerGateway taskManagerGateway = new SimpleAckingTaskManagerGateway();
taskMana... | execution.deploy(); | 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()... |
Shall we extract `matchExpr.type` and `errorMatchPattern.type` out to variables? | public BType resolvePatternTypeFromMatchExpr(BLangErrorMatchPattern errorMatchPattern, BLangExpression matchExpr) {
if (matchExpr == null) {
return errorMatchPattern.type;
}
if (isAssignable(matchExpr.type, errorMatchPattern.type)) {
return matchExpr.type;
}
... | if (isAssignable(matchExpr.type, errorMatchPattern.type)) { | public BType resolvePatternTypeFromMatchExpr(BLangErrorMatchPattern errorMatchPattern, BLangExpression matchExpr) {
if (matchExpr == null) {
return errorMatchPattern.type;
}
BType matchExprType = matchExpr.type;
BType patternType = errorMatchPattern.type;
if (isAssig... | 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 ... |
BTW, it seems that the precision will always set to the default, why not change it to a constant. | public ResourceSpec merge(final ResourceSpec other) {
checkNotNull(other, "Cannot merge with null resources");
if (this.equals(UNKNOWN) || other.equals(UNKNOWN)) {
return UNKNOWN;
}
ResourceSpec target = new ResourceSpec(
this.cpuCores.merge(other.cpuCores).getValue(),
this.heapMemoryInMB + other.h... | this.cpuCores.merge(other.cpuCores).getValue(), | public ResourceSpec merge(final ResourceSpec other) {
checkNotNull(other, "Cannot merge with null resources");
if (this.equals(UNKNOWN) || other.equals(UNKNOWN)) {
return UNKNOWN;
}
ResourceSpec target = new ResourceSpec(
this.cpuCores.merge(other.cpuCores),
this.taskHeapMemory.add(other.taskHeapMemo... | class ResourceSpec implements Serializable {
private static final long serialVersionUID = 1L;
/**
* A ResourceSpec that indicates an unknown set of resources.
*/
public static final ResourceSpec UNKNOWN = new ResourceSpec();
/**
* The default ResourceSpec used for operators and transformation functions.
... | class ResourceSpec implements Serializable {
private static final long serialVersionUID = 1L;
/**
* A ResourceSpec that indicates an unknown set of resources.
*/
public static final ResourceSpec UNKNOWN = new ResourceSpec();
/**
* The default ResourceSpec used for operators and transformation functions.
... |
should also have 503 and 500 - https://github.com/eclipse/microprofile-health/blob/master/spec/src/main/asciidoc/protocol-wireformat.adoc#status-codes | private APIResponses createAPIResponses() {
APIResponses responses = new APIResponsesImpl();
responses.addAPIResponse("200", createAPIResponse());
return responses;
} | responses.addAPIResponse("200", createAPIResponse()); | private APIResponses createAPIResponses() {
APIResponses responses = new APIResponsesImpl();
responses.addAPIResponse("200", createAPIResponse());
responses.addAPIResponse("503", createAPIResponse());
responses.addAPIResponse("500", createAPIResponse());
return responses;
} | class HealthOpenAPIFilter implements OASFilter {
private static final List<String> MICROPROFILE_HEALTH_TAG = Collections.singletonList("MicroProfile Health");
private final String rootPath;
private final String livenessPath;
private final String readinessPath;
public HealthOpenAPIFilter(String roo... | class HealthOpenAPIFilter implements OASFilter {
private static final List<String> MICROPROFILE_HEALTH_TAG = Collections.singletonList("MicroProfile Health");
private final String rootPath;
private final String livenessPath;
private final String readinessPath;
public HealthOpenAPIFilter(String roo... |
Is this going to `toString` correctly for the headers? If you want to do associations for URL and status code show it like this: `URL: %s, Status code: %d` | public void listKeySnippets() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeys()) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
keyWithMateria... | System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.headers(), | public void listKeySnippets() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeys()) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
keyWithMateria... | class KeyClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link KeyClient}
* @return An instance of {@link KeyClient}
*/
public KeyC... | class KeyClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Generates code sample for creating a {@link KeyClient}
* @return An instance of {@link KeyClient}
*/
public KeyC... |
@geoand: This is needed in order to deal with some `tck` issues which cause `config.getValue().initAndExit` to be always true. There is a comment right above (see lines 30-31) | public void exitIfNeeded() {
boolean initAndExitConfigured = propertyConfigured(QUARKUS_INIT_AND_EXIT);
if (initAndExitConfigured && config.getValue().initAndExit) {
if (ConfigProvider.getConfig().getValue(QUARKUS_INIT_AND_EXIT, boolean.class)) {
preventFurt... | if (initAndExitConfigured && config.getValue().initAndExit) { | public void exitIfNeeded() {
boolean initAndExitConfigured = propertyConfigured(QUARKUS_INIT_AND_EXIT);
if (initAndExitConfigured && config.getValue().initAndExit) {
if (ConfigProvider.getConfig().getValue(QUARKUS_INIT_AND_EXIT, boolean.class)) {
preventFurt... | class InitializationTaskRecorder {
private static final String QUARKUS_INIT_AND_EXIT = "quarkus.init-and-exit";
private final RuntimeValue<InitRuntimeConfig> config;
public InitializationTaskRecorder(RuntimeValue<InitRuntimeConfig> config) {
this.config = config;
}
public static voi... | class InitializationTaskRecorder {
private static final String QUARKUS_INIT_AND_EXIT = "quarkus.init-and-exit";
private final RuntimeValue<InitRuntimeConfig> config;
public InitializationTaskRecorder(RuntimeValue<InitRuntimeConfig> config) {
this.config = config;
}
public static voi... |
We can optimize the code as follow: ``` return LogicalTypeMerging.findCommonType( Arrays.asList( inputDataType.getLogicalType(), nullReplacementDataType.getLogicalType())) .map(t -> t.copy(nullReplacementData... | public Optional<DataType> inferType(CallContext callContext) {
final List<DataType> argumentDataTypes = callContext.getArgumentDataTypes();
final DataType inputDataType = argumentDataTypes.get(0);
final DataType nullReplacementDataType = argumentDataTypes.get(1);
if (!inputDataType.getL... | return LogicalTypeMerging.findCommonType( | public Optional<DataType> inferType(CallContext callContext) {
final List<DataType> argumentDataTypes = callContext.getArgumentDataTypes();
final DataType inputDataType = argumentDataTypes.get(0);
final DataType nullReplacementDataType = argumentDataTypes.get(1);
if (!inputDataType.getL... | class IfNullTypeStrategy implements TypeStrategy {
@Override
} | class IfNullTypeStrategy implements TypeStrategy {
@Override
} |
Same here about simplifying the logic. | public void handle(RoutingContext event) {
HttpServerRequest request = event.request();
HttpServerResponse response = event.response();
if (graphQLRuntimeConfig.enable) {
GraphQLSchema graphQLSchema = CDI.current().select(GraphQLSchema.class).get();
SchemaPrinter schema... | if (graphQLRuntimeConfig.enable) { | public void handle(RoutingContext event) {
HttpServerRequest request = event.request();
HttpServerResponse response = event.response();
GraphQLSchema graphQLSchema = CDI.current().select(GraphQLSchema.class).get();
SchemaPrinter schemaPrinter = CDI.current().select(SchemaPrinter.class).... | class SmallRyeGraphQLSchemaHandler implements Handler<RoutingContext> {
private static final String ALLOWED_METHODS = "GET, OPTIONS";
private static final String CONTENT_TYPE = "text/plain; charset=UTF-8";
private SmallRyeGraphQLRuntimeConfig graphQLRuntimeConfig;
public SmallRyeGraphQLSchemaHandler()... | class SmallRyeGraphQLSchemaHandler implements Handler<RoutingContext> {
private static final String ALLOWED_METHODS = "GET, OPTIONS";
private static final String CONTENT_TYPE = "text/plain; charset=UTF-8";
@Override
} |
No, it will return an Empty notExistClause*Context, it's EXISTS() method will return null | public ASTNode visitCreateTable(final CreateTableContext ctx) {
CreateTableStatement result = new CreateTableStatement((SimpleTableSegment) visit(ctx.tableName()), null != ctx.notExistClause_().EXISTS());
if (null != ctx.createDefinitionClause()) {
CollectionValue<CreateDefinitionSegment> cr... | CreateTableStatement result = new CreateTableStatement((SimpleTableSegment) visit(ctx.tableName()), null != ctx.notExistClause_().EXISTS()); | public ASTNode visitCreateTable(final CreateTableContext ctx) {
CreateTableStatement result = new CreateTableStatement((SimpleTableSegment) visit(ctx.tableName()), null != ctx.notExistClause_());
if (null != ctx.createDefinitionClause()) {
CollectionValue<CreateDefinitionSegment> createDefin... | class MySQLDDLVisitor extends MySQLVisitor implements DDLVisitor {
@Override
public ASTNode visitCreateView(final CreateViewContext ctx) {
return new CreateViewStatement();
}
@Override
public ASTNode visitDropView(final DropViewContext ctx) {
return new DropViewStatement();... | class MySQLDDLVisitor extends MySQLVisitor implements DDLVisitor {
@Override
public ASTNode visitCreateView(final CreateViewContext ctx) {
return new CreateViewStatement();
}
@Override
public ASTNode visitDropView(final DropViewContext ctx) {
return new DropViewStatement();... |
Ok, no problem, I didn't know it. I'm gonna do like this. | private void detectAndLogSpecificSpringPropertiesIfExist() {
Config config = ConfigProvider.getConfig();
Map<String, String> springJpaToQuarkusOrmPropertiesMap = new HashMap<>();
springJpaToQuarkusOrmPropertiesMap.put("spring.jpa.show-sql", "quarkus.hibernate-orm.log.sql");
springJpaToQu... | LOGGER.warn(warningLog + springProperty + " property. "); | private void detectAndLogSpecificSpringPropertiesIfExist() {
Config config = ConfigProvider.getConfig();
Iterable<String> iterablePropertyNames = config.getPropertyNames();
List<String> propertyNames = new ArrayList<String>();
iterablePropertyNames.forEach(propertyNames::add);
L... | class SpringDataJPAProcessor {
private static final Logger LOGGER = Logger.getLogger(SpringDataJPAProcessor.class.getName());
@BuildStep
FeatureBuildItem registerFeature() {
return new FeatureBuildItem(FeatureBuildItem.SPRING_DATA_JPA);
}
@BuildStep
IgnorableNonIndexedClasses ignorabl... | class SpringDataJPAProcessor {
private static final Logger LOGGER = Logger.getLogger(SpringDataJPAProcessor.class.getName());
private static final Pattern pattern = Pattern.compile("spring\\.jpa\\..*");
public static final String SPRING_JPA_SHOW_SQL = "spring.jpa.show-sql";
public static final String S... |
Shall we use `configValueMap.get(v1).getValue()` inside the assertion calls? Creating new variables can be redundant if we don't use them multiple times. | public void testCliWhenUnsupportedTypesWithinToml() {
ArrayType arrayType = TypeCreator.createArrayType(TYPE_STRING);
VariableKey v1 = new VariableKey(module, "v1", PredefinedTypes.TYPE_INT, true);
Type v2Type = new BIntersectionType(module, new Type[]{arrayType, PredefinedTypes.TYPE_READONLY},
... | Object v2Value = configValueMap.get(v2).getValue(); | public void testCliWhenUnsupportedTypesWithinToml() {
ArrayType arrayType = TypeCreator.createArrayType(TYPE_STRING);
VariableKey v1 = new VariableKey(module, "v1", PredefinedTypes.TYPE_INT, true);
Type v2Type = new BIntersectionType(module, new Type[]{arrayType, PredefinedTypes.TYPE_READONLY},
... | class ConfigTest {
private static final Module module = new Module("myOrg", "test_module", "1");
private static final Module ROOT_MODULE = new Module("rootOrg", "mod12", "1");
private static final List<Type> COLOR_ENUM_MEMBERS = List.of(
new BFiniteType("COLOR_RED", Set.of(StringUtils.fromStri... | class ConfigTest {
private static final Module module = new Module("myOrg", "test_module", "1");
private static final Module ROOT_MODULE = new Module("rootOrg", "mod12", "1");
private static final List<Type> COLOR_ENUM_MEMBERS = List.of(
new BFiniteType("COLOR_RED", Set.of(StringUtils.fromStri... |
Due to the concurrent access the synchronization is actually quite hard. I think I have pushed a good solution now. | public void setCurrentKey(Object key) {
if (stateful && usesTimers) {
synchronized (getKeyedStateBackend()) {
super.setCurrentKey(key);
}
} else if (usesTimers) {
super.setCurrentKey(key);
} else {
throw new UnsupportedOperationExcept... | if (stateful && usesTimers) { | public void setCurrentKey(Object key) {
if (!usesTimers) {
throw new UnsupportedOperationException(
"Current key for state backend can only be set by state requests from SDK workers or when processing timers.");
}
} | class BagUserStateFactory
implements StateRequestHandlers.BagUserStateHandlerFactory {
private final StateInternals stateInternals;
private final KeyedStateBackend<ByteBuffer> keyedStateBackend;
private BagUserStateFactory(
StateInternals stateInternals, KeyedStateBackend<ByteBuffer> keyedSt... | class BagUserStateFactory
implements StateRequestHandlers.BagUserStateHandlerFactory {
private final StateInternals stateInternals;
private final KeyedStateBackend<ByteBuffer> keyedStateBackend;
private BagUserStateFactory(
StateInternals stateInternals, KeyedStateBackend<ByteBuffer> keyedSt... |
Type of some `StatementExpressions` when created during desugar can be null. | private BLangBlockStmt desugarForeachToWhile(BLangForeach foreach, BLangSimpleVariableDef varDef) {
... | if (unaryExpr.getBType() != null && unaryExpr.getBType().isNullable() && | 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... |
Got it. I thought either regex or glob when hear pattern. | public void canCRUDEnterpriseTierDeployment() throws Exception {
allowAllSSL();
File tarGzFile = downloadFile(PETCLINIC_TAR_GZ_URL);
File jarFile = downloadFile(PETCLINIC_GATEWAY_JAR_URL);
String serviceName = generateRandomResourceName("springsvc", 15);
Region region = Region.U... | List<String> configFilePatterns = Arrays.asList("api-gateway", "customers-service"); | public void canCRUDEnterpriseTierDeployment() throws Exception {
allowAllSSL();
File tarGzFile = downloadFile(PETCLINIC_TAR_GZ_URL);
File jarFile = downloadFile(PETCLINIC_GATEWAY_JAR_URL);
String serviceName = generateRandomResourceName("springsvc", 15);
Region region = Region.U... | class SpringCloudLiveOnlyTest extends AppPlatformTest {
private static final String PIGGYMETRICS_CONFIG_URL = "https:
private static final String GATEWAY_JAR_URL = "https:
private static final String PIGGYMETRICS_TAR_GZ_URL = "https:
private static final String PETCLINIC_CONFIG_URL = "https:
private... | class SpringCloudLiveOnlyTest extends AppPlatformTest {
private static final String PIGGYMETRICS_CONFIG_URL = "https:
private static final String GATEWAY_JAR_URL = "https:
private static final String PIGGYMETRICS_TAR_GZ_URL = "https:
private static final String PETCLINIC_CONFIG_URL = "https:
private... |
You should also test that the exception is retryable or not, and if they have hit the maximum number of attempts. These are checks that are agnostic of the retry algorithm. | public Duration getNextRetryInterval(Exception lastException, Duration remainingTime) {
int baseWaitTime = 0;
if (lastException == null || !(lastException instanceof AmqpException)) {
return this.onGetNextRetryInterval(lastException, remainingTime, baseWaitTime, this.getRetryCount());
... | if (lastException == null || !(lastException instanceof AmqpException)) { | public Duration getNextRetryInterval(Exception lastException, Duration remainingTime) {
int baseWaitTime = 0;
if (!isRetriableException(lastException)) {
return null;
}
if (retryCount.get() >= maxRetryCount) {
return null;
}
if (((AmqpException)... | class Retry {
public static final Retry NO_RETRY = new RetryExponential(Duration.ofSeconds(0), Duration.ofSeconds(0), 0);
private AtomicInteger retryCount = new AtomicInteger(0);
/**
* Check if the existing exception is a retryable exception.
*
* @param exception A exception that was obser... | class Retry {
public static final Duration DEFAULT_RETRY_MIN_BACKOFF = Duration.ofSeconds(0);
public static final Duration DEFAULT_RETRY_MAX_BACKOFF = Duration.ofSeconds(30);
public static final int DEFAULT_MAX_RETRY_COUNT = 10;
private final AtomicInteger retryCount = new AtomicInteger();
private... |
The `SyntheticBean` constructor takes a `List<SomeBean>`, so the type argument here is inferred to be `List<SomeBean>`. | public SyntheticBean create(SyntheticCreationalContext<SyntheticBean> context) {
return new SyntheticBean(context.getInjectedReference(new TypeLiteral<>() {
}, All.Literal.INSTANCE));
} | return new SyntheticBean(context.getInjectedReference(new TypeLiteral<>() { | public SyntheticBean create(SyntheticCreationalContext<SyntheticBean> context) {
return new SyntheticBean(context.getInjectedReference(new TypeLiteral<List<SomeBean>>() {
}, All.Literal.INSTANCE));
} | class SynthBeanCreator implements BeanCreator<SyntheticBean> {
@Override
} | class SynthBeanCreator implements BeanCreator<SyntheticBean> {
@Override
} |
None of those functions is serializable therefore we cannot pass them directly to the sink. | public SinkRuntimeProvider getSinkRuntimeProvider(Context context) {
final SerializationSchema<RowData> keySerialization =
createSerialization(context, keyEncodingFormat, keyProjection, keyPrefix);
final SerializationSchema<RowData> valueSerialization =
createSerializati... | end.setParallelism(parallelism); | public SinkRuntimeProvider getSinkRuntimeProvider(Context context) {
final SerializationSchema<RowData> keySerialization =
createSerialization(context, keyEncodingFormat, keyProjection, keyPrefix);
final SerializationSchema<RowData> valueSerialization =
createSerializati... | class KafkaDynamicSink implements DynamicTableSink, SupportsWritingMetadata {
/** Metadata that is appended at the end of a physical sink row. */
protected List<String> metadataKeys;
/** Data type of consumed data type. */
protected DataType consumedDataType;
/** D... | class KafkaDynamicSink implements DynamicTableSink, SupportsWritingMetadata {
/** Metadata that is appended at the end of a physical sink row. */
protected List<String> metadataKeys;
/** Data type of consumed data type. */
protected DataType consumedDataType;
/** D... |
```suggestion assertThat(m).containsKeys(String.class, Boolean.class); ``` | void unwrapOptionalsPreservesOrder() {
LinkedOptionalMap<Class<?>, String> map = new LinkedOptionalMap<>();
map.put("a", String.class, "aaa");
map.put("b", Boolean.class, "bbb");
LinkedHashMap<Class<?>, String> m = map.unwrapOptionals();
assertThat(m).containsKey(String.class)... | assertThat(m).containsKey(String.class); | void unwrapOptionalsPreservesOrder() {
LinkedOptionalMap<Class<?>, String> map = new LinkedOptionalMap<>();
map.put("a", String.class, "aaa");
map.put("b", Boolean.class, "bbb");
LinkedHashMap<Class<?>, String> m = map.unwrapOptionals();
assertThat(m).containsKeys(String.class... | class LinkedOptionalMapTest {
@Test
void usageExample() {
LinkedOptionalMap<Class<?>, String> map = new LinkedOptionalMap<>();
map.put("java.lang.String", String.class, "a string class");
map.put("scala.Option", null, "a scala Option");
map.put("java.lang.Boolean", Boolean.clas... | class LinkedOptionalMapTest {
@Test
void usageExample() {
LinkedOptionalMap<Class<?>, String> map = new LinkedOptionalMap<>();
map.put("java.lang.String", String.class, "a string class");
map.put("scala.Option", null, "a scala Option");
map.put("java.lang.Boolean", Boolean.clas... |
Let's at least drop a TODO to add a more native ParDo.withBadRecordHandler() to reduce this boilerplate. | public PCollection<Integer> expand(PCollection<Integer> input) {
PCollectionTuple pCollectionTuple =
input.apply(
"NoOpDoFn",
ParDo.of(new OddIsBad(badRecordRouter))
.withOutputTags(RECORDS, TupleTagList.of(BadRecordRouter.BAD_RECORD_TAG)));
Coder<BadRecord> badR... | errorHandler.addErrorCollection( | public PCollection<Integer> expand(PCollection<Integer> input) {
PCollectionTuple pCollectionTuple =
input.apply(
"NoOpDoFn",
ParDo.of(new OddIsBad(badRecordRouter))
.withOutputTags(RECORDS, TupleTagList.of(BadRecordRouter.BAD_RECORD_TAG)));
errorHandler.add... | class BRHEnabledPTransform extends PTransform<PCollection<Integer>, PCollection<Integer>> {
private ErrorHandler<BadRecord, ?> errorHandler = new NoOpErrorHandler<>();
private BadRecordRouter badRecordRouter = BadRecordRouter.THROWING_ROUTER;
private static final TupleTag<Integer> RECORDS = new TupleTag<>();
... | class BRHEnabledPTransform extends PTransform<PCollection<Integer>, PCollection<Integer>> {
private ErrorHandler<BadRecord, ?> errorHandler = new DefaultErrorHandler<>();
private BadRecordRouter badRecordRouter = BadRecordRouter.THROWING_ROUTER;
private static final TupleTag<Integer> RECORDS = new TupleTag<>()... |
this looks like a workaround to ignore the order? | public void testTypeConversions() throws Exception {
List<Row> data =
Arrays.asList(
Row.of(
1,
"ABC",
java.sql.Timestamp.valueOf("2000-12-12 12:30:57.12"),
... | assertThat(new HashSet<>(actual)).isEqualTo(new HashSet<>(expected)); | public void testTypeConversions() throws Exception {
List<Row> data =
Arrays.asList(
Row.of(
1,
"ABC",
java.sql.Timestamp.valueOf("2000-12-12 12:30:57.12"),
... | class ValuesITCase extends StreamingTestBase {
@Test
@Test
public void testAllTypes() throws Exception {
List<Row> data =
Arrays.asList(
rowWithNestedRow(
(byte) 1,
(short) 1,
... | class ValuesITCase extends StreamingTestBase {
@Test
@Test
public void testAllTypes() throws Exception {
List<Row> data =
Arrays.asList(
rowWithNestedRow(
(byte) 1,
(short) 1,
... |
Please do not use `Map.Entry`, just use `Entry` | private Collection<EncryptColumnMetaData> getTableEncryptColumnMetaDatas() {
Collection<EncryptColumnMetaData> result = new LinkedList<>();
for (Map.Entry<String, ColumnMetaData> entry : schemaMetaData.get(tableName).getColumns().entrySet()) {
if (!(entry.getValue() instanceof EncryptColumnM... | for (Map.Entry<String, ColumnMetaData> entry : schemaMetaData.get(tableName).getColumns().entrySet()) { | private Collection<EncryptColumnMetaData> getTableEncryptColumnMetaDatas() {
Collection<EncryptColumnMetaData> result = new LinkedList<>();
for (Entry<String, ColumnMetaData> entry : schemaMetaData.get(tableName).getColumns().entrySet()) {
if (entry.getValue() instanceof EncryptColumnMetaDat... | class EncryptColumnsMergedResult implements MergedResult {
private final SchemaMetaData schemaMetaData;
private final String tableName;
protected EncryptColumnsMergedResult(final SQLStatementContext sqlStatementContext, final SchemaMetaData schemaMetaData) {
this.schemaMetaData = sche... | class EncryptColumnsMergedResult implements MergedResult {
private final SchemaMetaData schemaMetaData;
private final String tableName;
protected EncryptColumnsMergedResult(final SQLStatementContext sqlStatementContext, final SchemaMetaData schemaMetaData) {
this.schemaMetaData = sche... |
How do we know when data distribution has to completed if we add new nodes? Since we know from the event what the target is, wouldn't it be better to identify the nodes that we are scaling to (i.e. the `count` nodes that are `active`, not retired and have the same resources as the `cluster.targetResources()`), then fo... | private Cluster updateCompletion(Cluster cluster, NodeList clusterNodes) {
if (cluster.lastScalingEvent().isEmpty()) return cluster;
var event = cluster.lastScalingEvent().get();
if (event.completion().isPresent()) return cluster;
if (clusterNodes.retired().stream()
... | private Cluster updateCompletion(Cluster cluster, NodeList clusterNodes) {
if (cluster.lastScalingEvent().isEmpty()) return cluster;
var event = cluster.lastScalingEvent().get();
if (event.completion().isPresent()) return cluster;
if (clusterNodes.retired().stream()
... | class AutoscalingMaintainer extends NodeRepositoryMaintainer {
private final Autoscaler autoscaler;
private final MetricsDb metricsDb;
private final Deployer deployer;
private final Metric metric;
public AutoscalingMaintainer(NodeRepository nodeRepository,
MetricsD... | class AutoscalingMaintainer extends NodeRepositoryMaintainer {
private final Autoscaler autoscaler;
private final MetricsDb metricsDb;
private final Deployer deployer;
private final Metric metric;
public AutoscalingMaintainer(NodeRepository nodeRepository,
MetricsD... | |
I believe so. But it's a good point that we could be more defensive here... | BeanArchivePredicateBuildItem additionalBeanArchives() {
return new BeanArchivePredicateBuildItem(new Predicate<ApplicationArchive>() {
@Override
public boolean test(ApplicationArchive archive) {
return !archive.getIndex().getKnownDirectImplementors(Grpc... | return !archive.getIndex().getKnownDirectImplementors(GrpcDotNames.MUTINY_BEAN).isEmpty(); | BeanArchivePredicateBuildItem additionalBeanArchives() {
return new BeanArchivePredicateBuildItem(new Predicate<ApplicationArchive>() {
@Override
public boolean test(ApplicationArchive archive) {
return !archive.getIndex().getKnownDirectImplementors(Grpc... | class extends the impl base
continue;
}
boolean excluded = false;
for (String excludedPackage : excludedPackages) {
if (mutinyImplBaseName.startsWith(excludedPackage)) {
excluded = true;
break;
... | class extends the impl base
continue;
}
boolean excluded = false;
for (String excludedPackage : excludedPackages) {
if (mutinyImplBaseName.startsWith(excludedPackage)) {
excluded = true;
break;
... |
This is a good question. Flink will restart the pipeline every time we scale up/down. `addSplitsback` is called only when we enable [Restart Pipelined Region Failover Strategy](https://nightlies.apache.org/flink/flink-docs-master/docs/ops/state/task_failure_recovery/#restart-pipelined-region-failover-strategy) and som... | public void addSplitsBack(List<PulsarPartitionSplit> splits, int subtaskId) {
splitAssigner.addSplitsBack(splits, subtaskId);
if (context.registeredReaders().containsKey(subtaskId)) {
LOG.debug(
"Reader {} has been restarted after crashing, we will put ... | assignPendingPartitionSplits(readers); | public void addSplitsBack(List<PulsarPartitionSplit> splits, int subtaskId) {
splitAssigner.addSplitsBack(splits, subtaskId);
if (context.registeredReaders().containsKey(subtaskId)) {
LOG.debug(
"Reader {} has been restarted after crashing, we will put ... | class PulsarSourceEnumerator
implements SplitEnumerator<PulsarPartitionSplit, PulsarSourceEnumState> {
private static final Logger LOG = LoggerFactory.getLogger(PulsarSourceEnumerator.class);
private final PulsarAdmin pulsarAdmin;
private final PulsarSubscriber subscriber;
private final StartC... | class PulsarSourceEnumerator
implements SplitEnumerator<PulsarPartitionSplit, PulsarSourceEnumState> {
private static final Logger LOG = LoggerFactory.getLogger(PulsarSourceEnumerator.class);
private final PulsarAdmin pulsarAdmin;
private final PulsarSubscriber subscriber;
private final StartC... |
Addressed in https://github.com/ballerina-platform/ballerina-lang/pull/38093/commits/f6fc6deae6ab6005be97a5ccea07619863dcab63. | public void testSymbolLookupInModuleAlias() {
Project project = BCompileUtil.loadProject("test-src/symbol_lookup_with_module_alias_test.bal");
SemanticModel model = getDefaultModulesSemanticModel(project);
Document srcFile = getDocumentForSingleSource(project);
List<Symbol> visibleSymbol... | assertEquals(symbols.size(), 2); | public void testSymbolLookupInModuleAlias() {
Project project = BCompileUtil.loadProject("test-src/symbol_lookup_with_module_alias_test.bal");
SemanticModel model = getDefaultModulesSemanticModel(project);
Document srcFile = getDocumentForSingleSource(project);
List<Symbol> visibleSymbol... | class SymbolLookupTest {
@Test(dataProvider = "PositionProvider3")
public void testVarSymbolLookupInTypedefs(int line, int column, int expSymbols, List<String> expSymbolNames) {
Project project = BCompileUtil.loadProject("test-src/symbol_lookup_with_typedefs_test.bal");
Package currentPackage =... | class SymbolLookupTest {
@Test(dataProvider = "PositionProvider3")
public void testVarSymbolLookupInTypedefs(int line, int column, int expSymbols, List<String> expSymbolNames) {
Project project = BCompileUtil.loadProject("test-src/symbol_lookup_with_typedefs_test.bal");
Package currentPackage =... |
I'd move this to line 118, you don't need to query the typeToken if the classNamestack is empty. | private void checkMethodNamePrefix(DetailAST methodDefToken) {
if (!TokenUtil.findFirstTokenByPredicate(methodDefToken,
c -> c.getType() == TokenTypes.PARAMETERS && c.getChildCount() == 1).isPresent()) {
return;
}
final DetailAST typeToken = methodDefTo... | final DetailAST typeToken = methodDefToken.findFirstToken(TokenTypes.TYPE); | private void checkMethodNamePrefix(DetailAST methodDefToken) {
if (TokenUtil.findFirstTokenByPredicate(methodDefToken, parameters ->
parameters.getType() == TokenTypes.PARAMETERS && parameters.getChildCount() != 1).isPresent()) {
log(methodDefToken, "A fluent method should only ... | class names when traversals the AST tree.
*/
private Deque<String> classNameStack = new ArrayDeque<>();
/**
* Setter to specifies valid identifiers
* @param avoidStartWords the starting strings that should not start with in fluent method
*/
public final void setAvoidStartWords(String...... | class names when traversals the AST tree.
*/
private final Deque<String> classNameStack = new ArrayDeque<>();
/**
* Adds words that methods in fluent classes should not be prefixed with.
* @param avoidStartWords the starting strings that should not start with in fluent method
*/
public ... |
does it mean that in shared nothing mode, create db/table statement is not allowed to specify 'storage volume' property? I would say, we should respect what the db storageVolumeId is no matter it is a shared data or shared nothing mode. If the db is not allowed to have a storage volume property, just block it when cre... | private void handleShowCreateDb() throws AnalysisException {
ShowCreateDbStmt showStmt = (ShowCreateDbStmt) stmt;
String catalogName = showStmt.getCatalogName();
String dbName = showStmt.getDb();
List<List<String>> rows = Lists.newArrayList();
Database db;
if (Strings.is... | if (RunMode.getCurrentRunMode() == RunMode.SHARED_DATA && !Strings.isNullOrEmpty(db.getStorageVolumeId())) { | private void handleShowCreateDb() throws AnalysisException {
ShowCreateDbStmt showStmt = (ShowCreateDbStmt) stmt;
String catalogName = showStmt.getCatalogName();
String dbName = showStmt.getDb();
List<List<String>> rows = Lists.newArrayList();
Database db;
if (Strings.is... | class ShowExecutor {
private static final Logger LOG = LogManager.getLogger(ShowExecutor.class);
private static final List<List<String>> EMPTY_SET = Lists.newArrayList();
private final ConnectContext connectContext;
private final ShowStmt stmt;
private ShowResultSet resultSet;
private final Met... | class ShowExecutor {
private static final Logger LOG = LogManager.getLogger(ShowExecutor.class);
private static final List<List<String>> EMPTY_SET = Lists.newArrayList();
private final ConnectContext connectContext;
private final ShowStmt stmt;
private ShowResultSet resultSet;
private final Met... |
Can we please use one term? Extra vs Additional. | private BType checkInvocationParam(BLangInvocation iExpr, AnalyzerData data) {
if (Symbols.isFlagOn(iExpr.symbol.type.flags, Flags.ANY_FUNCTION)) {
dlog.error(iExpr.pos, DiagnosticErrorCode.INVALID_FUNCTION_POINTER_INVOCATION_WITH_TYPE);
return symTable.semanticError;
}
B... | boolean isIncRecordAllowExtraFields = incRecordParamAllowAdditionalFields != null; | private BType checkInvocationParam(BLangInvocation iExpr, AnalyzerData data) {
if (Symbols.isFlagOn(iExpr.symbol.type.flags, Flags.ANY_FUNCTION)) {
dlog.error(iExpr.pos, DiagnosticErrorCode.INVALID_FUNCTION_POINTER_INVOCATION_WITH_TYPE);
return symTable.semanticError;
}
B... | class InferredTupleDetails {
List<BType> fixedMemberTypes = new ArrayList<>();
List<BType> restMemberTypes = new ArrayList<>();
} | class InferredTupleDetails {
List<BType> fixedMemberTypes = new ArrayList<>();
List<BType> restMemberTypes = new ArrayList<>();
} |
How about return both `slot id` and `expr`. I'm afraid that `slot id` may be used for some tracing debug. And please fix all related unit tests after you change here. | public String toSqlImpl() {
StringBuilder sb = new StringBuilder();
if (tblName != null) {
return tblName.toSql() + "." + label + sb.toString();
} else if (label != null) {
return label + sb.toString();
... | return sb.toString(); | public String toSqlImpl() {
StringBuilder sb = new StringBuilder();
if (tblName != null) {
return tblName.toSql() + "." + label + sb.toString();
} else if (label != null) {
return label + sb.toString();
... | class SlotRef extends Expr {
private static final Logger LOG = LogManager.getLogger(SlotRef.class);
private TableName tblName;
private String col;
private String label;
protected SlotDescriptor desc;
private SlotRef() {
super();
}
public SlotRef(TableName tblNam... | class SlotRef extends Expr {
private static final Logger LOG = LogManager.getLogger(SlotRef.class);
private TableName tblName;
private String col;
private String label;
protected SlotDescriptor desc;
private SlotRef() {
super();
}
public SlotRef(TableName tblNam... |
Don't we need to change the doc comment with respect to the change? As this method only sets compression header now. | public static void setCompressionHeaders(Context context, HTTPCarbonMessage outboundMessage) {
AnnAttachmentInfo configAnn = context.getServiceInfo().getAnnotationAttachmentInfo(
HttpConstants.PROTOCOL_PACKAGE_HTTP, HttpConstants.ANN_NAME_CONFIG);
if (configAnn != null) {
Ann... | AnnAttributeValue compressionEnabled = configAnn.getAttributeValue( | public static void setCompressionHeaders(Context context, HTTPCarbonMessage outboundMessage) {
AnnAttachmentInfo configAnn = context.getServiceInfo().getAnnotationAttachmentInfo(
HttpConstants.PROTOCOL_PACKAGE_HTTP, HttpConstants.ANN_NAME_CONFIG);
if (configAnn != null) {
Ann... | class HttpUtil {
private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
private static final String METHOD_ACCESSED = "isMethodAccessed";
private static final String IO_EXCEPTION_OCCURED = "I/O exception occurred";
public static BValue[] getProperty(Context context,
... | class HttpUtil {
private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
private static final String METHOD_ACCESSED = "isMethodAccessed";
private static final String IO_EXCEPTION_OCCURED = "I/O exception occurred";
public static BValue[] getProperty(Context context,
... |
In which situation is it NESTED? We made the change originally because it wasn't prefixed, so trying to understand what changed. | private void prepareStateBackend(K key) {
ByteBuffer encodedKey =
FlinkKeyUtils.removeNestedContext(key, (Coder<ByteString>) keyCoder);
keyedStateBackend.setCurrentKey(encodedKey);
} | private void prepareStateBackend(K key) {
ByteBuffer encodedKey = FlinkKeyUtils.fromEncodedKey(key);
keyedStateBackend.setCurrentKey(encodedKey);
} | class BagUserStateFactory<K extends ByteString, V, W extends BoundedWindow>
implements StateRequestHandlers.BagUserStateHandlerFactory<K, V, W> {
private final StateInternals stateInternals;
private final KeyedStateBackend<ByteBuffer> keyedStateBackend;
private final Lock stateBackendLock;
priva... | class BagUserStateFactory<K extends ByteString, V, W extends BoundedWindow>
implements StateRequestHandlers.BagUserStateHandlerFactory<K, V, W> {
private final StateInternals stateInternals;
private final KeyedStateBackend<ByteBuffer> keyedStateBackend;
private final Lock stateBackendLock;
priva... | |
> I think we should keep this. because when TableEnvironment supports new operation but forgets to update SqlCommandParser I think we should never do this, either to refactor the code to keep SQL_CLI synced with table environment or keep the logic clean. | private Optional<SqlCommandCall> parseCommand(String line) {
final Optional<SqlCommandCall> parsedLine;
try {
parsedLine = SqlCommandParser.parse(executor.getSqlParser(sessionId), line);
} catch (SqlExecutionException e) {
printExecutionException(e);
return Optional.empty();
}
if (!parsedLine.isPrese... | printError(CliStrings.MESSAGE_UNKNOWN_SQL); | private Optional<SqlCommandCall> parseCommand(String line) {
final SqlCommandCall parsedLine;
try {
parsedLine = SqlCommandParser.parse(executor.getSqlParser(sessionId), line);
} catch (SqlExecutionException e) {
printExecutionException(e);
return Optional.empty();
}
return Optional.of(parsedLine);
... | class CliClient {
private static final Logger LOG = LoggerFactory.getLogger(CliClient.class);
private final Executor executor;
private final String sessionId;
private final Terminal terminal;
private final LineReader lineReader;
private final String prompt;
private boolean isRunning;
private static fina... | class CliClient {
private static final Logger LOG = LoggerFactory.getLogger(CliClient.class);
private final Executor executor;
private final String sessionId;
private final Terminal terminal;
private final LineReader lineReader;
private final String prompt;
private boolean isRunning;
private static fina... |
Modified it as `'Clazz' is abstract, and cannot be instantiated` per discussion. | private List<Executable> getExecutables(Class<?> clazz, String methodName, JMethodKind kind) {
if (kind == JMethodKind.CONSTRUCTOR) {
if (Modifier.isAbstract(clazz.getModifiers())) {
throw new JInteropException(DiagnosticErrorCode.INSTANTIATION_ERROR,
"'" + c... | throw new JInteropException(DiagnosticErrorCode.INSTANTIATION_ERROR, | private List<Executable> getExecutables(Class<?> clazz, String methodName, JMethodKind kind) {
if (kind == JMethodKind.CONSTRUCTOR) {
if (Modifier.isAbstract(clazz.getModifiers())) {
throw new JInteropException(DiagnosticErrorCode.INSTANTIATION_ERROR,
"'" + c... | class '" + jMethodRequest.declaringClass + "'");
}
} else {
return resolvedJMethods.get(0);
} | class '" + jMethodRequest.declaringClass + "'");
}
} else {
return resolvedJMethods.get(0);
} |
does it mean we no longer set error if all retries has failed? | private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) {
final String partitionKey = options.getPartitionKey();
final String partitionId = options.getPartitionId();
if (!CoreUtils.isNullOrEmpty(partitionKey)
&& !CoreUtils.isNullOrEmpty(partitionId)) {
... | final String partitionKey = options.getPartitionKey(); | private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) {
final String partitionKey = options.getPartitionKey();
final String partitionId = options.getPartitionId();
if (!CoreUtils.isNullOrEmpty(partitionKey)
&& !CoreUtils.isNullOrEmpty(partitionId)) {
... | class EventHubProducerAsyncClient implements Closeable {
private static final int MAX_PARTITION_KEY_LENGTH = 128;
private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s";
private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions();
private static final CreateBatchOption... | class EventHubProducerAsyncClient implements Closeable {
private static final int MAX_PARTITION_KEY_LENGTH = 128;
private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s";
private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions();
private static final CreateBatchOption... |
Is there absolutely no way for cassandra.start()/cluster.connect() to throw an exception? | public static void closeCassandra() {
session.close();
Cluster cluster = session.getCluster();
if (cluster != null) {
cluster.close();
}
if (cassandra != null) {
cassandra.stop();
}
} | session.close(); | public static void closeCassandra() {
if (session != null) {
session.close();
}
if (cluster != null) {
cluster.close();
}
CASSANDRA_CONTAINER.stop();
} | class CassandraConnectorITCase
extends WriteAheadSinkTestBase<
Tuple3<String, Integer, Integer>,
CassandraTupleWriteAheadSink<Tuple3<String, Integer, Integer>>> {
private static final String IMAGE_TAG = "3.0";
@ClassRule public static CassandraContainer cassandra = crea... | class CassandraConnectorITCase
extends WriteAheadSinkTestBase<
Tuple3<String, Integer, Integer>,
CassandraTupleWriteAheadSink<Tuple3<String, Integer, Integer>>> {
@ClassRule
public static final CassandraContainer CASSANDRA_CONTAINER = createCassandraContainer();
pri... |
I see. We rearrange the node in the binding pattern scenario anyway. e.g. a `SimpleNameReferenceNode` will be converted to a `CaptureBindingPatternNode`. Therefore shall add the `MemberTypeDescriptorNode` conversion at the same place? https://github.com/ballerina-platform/ballerina-lang/blob/31e1d2c7b78e23ab880f1665... | private boolean isServiceDeclStart(ParserRuleContext currentContext, int lookahead) {
switch (peek(lookahead + 1).kind) {
case IDENTIFIER_TOKEN:
SyntaxKind tokenAfterIdentifier = peek(lookahead + 2).kind;
switch (tokenAfterIdentifier) {
ca... | return parseAsTupleTypeDesc(annots, openBracket, memberList, member, isRoot); | 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... |
The setup and execution is identical to that used in testIntHash(), except the data type and field name. Consider refactor into a helper function. As it stands I think it is harder to read as I was looking for differences between the two tests. | public void testLongHash() throws ParseException {
var expression = Expression.fromString("input myText | hash | attribute 'myLong'");
SimpleTestAdapter adapter = new SimpleTestAdapter();
adapter.createField(new Field("myText", DataType.STRING));
var intField = new Field("myLong", DataT... | expression.execute(context); | public void testLongHash() throws ParseException {
var expression = Expression.fromString("input myText | hash | attribute 'myLong'");
SimpleTestAdapter adapter = new SimpleTestAdapter();
adapter.createField(new Field("myText", DataType.STRING));
var intField = new Field("myLong", DataT... | class ScriptTestCase {
private final DocumentType type;
public ScriptTestCase() {
type = new DocumentType("mytype");
type.addField("in-1", DataType.STRING);
type.addField("in-2", DataType.STRING);
type.addField("out-1", DataType.STRING);
type.addField("out-2", DataType.... | class ScriptTestCase {
private final DocumentType type;
public ScriptTestCase() {
type = new DocumentType("mytype");
type.addField("in-1", DataType.STRING);
type.addField("in-2", DataType.STRING);
type.addField("out-1", DataType.STRING);
type.addField("out-2", DataType.... |
Yes, good point, fixed and made sure to actually test both forms | private static ApplicationId fromIdString(String idString, String splitCharacter) {
String[] parts = idString.split(splitCharacter);
String errorMessage = "Application ids must be on the form tenant" +
splitCharacter + "application" + splitCharacter + "instance, but was " + idString;
... | splitCharacter + "application" + splitCharacter + "instance, but was " + idString; | private static ApplicationId fromIdString(String idString, String splitCharacter) {
String[] parts = idString.split(Pattern.quote(splitCharacter));
String errorMessage = "Application ids must be on the form tenant" +
splitCharacter + "application" + splitCharacter + "instance, but was " ... | class ApplicationId implements Comparable<ApplicationId> {
private static final Logger log = Logger.getLogger(ApplicationId.class.getName());
static final Pattern namePattern = Pattern.compile("[a-zA-Z0-9_-]{1,256}");
private static final ApplicationId global = new ApplicationId(TenantName.from("hosted-v... | class ApplicationId implements Comparable<ApplicationId> {
private static final Logger log = Logger.getLogger(ApplicationId.class.getName());
static final Pattern namePattern = Pattern.compile("[a-zA-Z0-9_-]{1,256}");
private static final ApplicationId global = new ApplicationId(TenantName.from("hosted-v... |
The same to [test_split_with_element_allowed_splits](https://github.com/apache/beam/blob/master/sdks/python/apache_beam/runners/worker/bundle_processor_test.py#L81) | public static Iterable<Object[]> data() {
return ImmutableList.<Object[]>builder()
.add(
new Object[] {
channelSplitResult(4L),
16L,
ImmutableList.of("A"),
0.25,
ImmutableList.of(2L, 3L, 4L, 5L)
... | new Object[] { | public static Iterable<Object[]> data() {
return ImmutableList.<Object[]>builder()
.add(new Object[] {channelSplitResult(1L), 0L, 0, 0, 16L})
.add(new Object[] {channelSplitResult(4L), 0L, 0, 0.24, 16L})
.add(new Object[] {channelSplitResult(4L), 0L, 0, 0.25, 16... | class ChannelSplitTest {
@Parameterized.Parameters
@Parameterized.Parameter(0)
public ProcessBundleSplitResponse expectedResponse;
@Parameterized.Parameter(1)
public long inputElements;
@Parameterized.Parameter(2)
public List<String> processedElements;
@Parameterized.Parameter(... | class ChannelSplitTest {
@Parameterized.Parameters
@Parameterized.Parameter(0)
public ProcessBundleSplitResponse expectedResponse;
@Parameterized.Parameter(1)
public long index;
@Parameterized.Parameter(2)
public double elementProgress;
@Parameterized.Parameter(3)
public do... |
After confirming with andrey, we could keep the previous behavior to still ignore `IOException` during close, because we just try best to delete files for releasing resources. If one file was already deleted by other factors before, it is no need to cause unnecessary failover. If we want to refactor this behavior fut... | public void afterTest() throws Exception {
this.ioManager.close();
if (!this.ioManager.isProperlyShutDown()) {
Assert.fail("I/O Manager was not properly shut down.");
}
if (this.memoryManager != null && testSuccess) {
Assert.assertTrue("Memory leak: not all segments have been returned to the memory man... | if (!this.ioManager.isProperlyShutDown()) { | public void afterTest() throws Exception {
this.ioManager.close();
if (this.memoryManager != null && testSuccess) {
Assert.assertTrue("Memory leak: not all segments have been returned to the memory manager.",
this.memoryManager.verifyEmpty());
this.memoryManager.shutdown();
this.memoryManager = nul... | class ExternalSortLargeRecordsITCase extends TestLogger {
private static final int MEMORY_SIZE = 1024 * 1024 * 78;
private final AbstractInvokable parentTask = new DummyInvokable();
private IOManager ioManager;
private MemoryManager memoryManager;
private boolean testSuccess;
@Before
public void befor... | class ExternalSortLargeRecordsITCase extends TestLogger {
private static final int MEMORY_SIZE = 1024 * 1024 * 78;
private final AbstractInvokable parentTask = new DummyInvokable();
private IOManager ioManager;
private MemoryManager memoryManager;
private boolean testSuccess;
@Before
public void befor... |
Is this index calculation correct? What if we are adding the first reporter. Wouldn't the index then be `-1`? | public MetricRegistryImpl(MetricRegistryConfiguration config, Collection<ReporterSetup> reporterConfigurations) {
this.maximumFramesize = config.getQueryServiceMessageSizeLimit();
this.scopeFormats = config.getScopeFormats();
this.globalDelimiter = config.getDelimiter();
this.terminationFuture = new Completable... | reporters.size() - 1, | public MetricRegistryImpl(MetricRegistryConfiguration config, Collection<ReporterSetup> reporterConfigurations) {
this.maximumFramesize = config.getQueryServiceMessageSizeLimit();
this.scopeFormats = config.getScopeFormats();
this.globalDelimiter = config.getDelimiter();
this.terminationFuture = new Completable... | class MetricRegistryImpl implements MetricRegistry {
private static final Logger LOG = LoggerFactory.getLogger(MetricRegistryImpl.class);
private final Object lock = new Object();
private final List<ReporterAndSettings> reporters;
private final ScheduledExecutorService executor;
private final ScopeFormats scope... | class MetricRegistryImpl implements MetricRegistry {
private static final Logger LOG = LoggerFactory.getLogger(MetricRegistryImpl.class);
private final Object lock = new Object();
private final List<ReporterAndSettings> reporters;
private final ScheduledExecutorService executor;
private final ScopeFormats scope... |
yes, that's a common Javadoc that signals the Java version info. | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecogniz... | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecogniz... | class AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
} | class AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
} | |
could set isNull always true in create ArrayType | public Type clickhouseTypeToDoris(JdbcFieldSchema fieldSchema) {
String ckType = fieldSchema.getDataTypeName();
boolean isNull = false;
if (ckType.startsWith("LowCardinality")) {
ckType = ckType.substring(15, ckType.length() - 1);
if (ckType.startsWith("Nullable")) {
... | return ArrayType.create(type, isNull); | public Type clickhouseTypeToDoris(JdbcFieldSchema fieldSchema) {
String ckType = fieldSchema.getDataTypeName();
if (ckType.startsWith("LowCardinality")) {
ckType = ckType.substring(15, ckType.length() - 1);
if (ckType.startsWith("Nullable")) {
ckType = ckType.subs... | class JdbcFieldSchema {
private String columnName;
private int dataType;
private String dataTypeName;
private int columnSize;
private int decimalDigits;
private int numPrecRadix;
private String remarks;
... | class JdbcFieldSchema {
private String columnName;
private int dataType;
private String dataTypeName;
private int columnSize;
private int decimalDigits;
private int numPrecRadix;
private String remarks;
... |
Do we want to install both if we already know one of them is installed? | public void testInstall() {
TaskContext taskContext = mock(TaskContext.class);
TestCommandSupplier commandSupplier = new TestCommandSupplier(taskContext);
commandSupplier.expectCommand("yum list installed package-1", 0, "");
commandSupplier.expectCommand("yum list installed package-2", ... | "yum install --assumeyes --enablerepo=repo-name package-1 package-2", | public void testInstall() {
TaskContext taskContext = mock(TaskContext.class);
TestCommandSupplier commandSupplier = new TestCommandSupplier(taskContext);
commandSupplier.expectCommand("yum list installed package-1", 0, "");
commandSupplier.expectCommand("yum list installed package-2", ... | class YumTest {
@Test
public void testAlreadyInstalled() {
TaskContext taskContext = mock(TaskContext.class);
TestCommandSupplier commandSupplier = new TestCommandSupplier(taskContext);
commandSupplier.expectCommand("yum list installed package-1", 0, "");
commandSupplier.expectC... | class YumTest {
@Test
public void testAlreadyInstalled() {
TaskContext taskContext = mock(TaskContext.class);
TestCommandSupplier commandSupplier = new TestCommandSupplier(taskContext);
commandSupplier.expectCommand("yum list installed package-1", 0, "");
commandSupplier.expectC... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.