comment stringlengths 22 3.02k | method_body stringlengths 46 368k | target_code stringlengths 0 181 | method_body_after stringlengths 12 368k | context_before stringlengths 11 634k | context_after stringlengths 11 632k |
|---|---|---|---|---|---|
Do we already have positive tests for this? | public void setup() {
compileResult = BCompileUtil.compile("test-src/annotations/annot_attachments_negative.bal");
Assert.assertEquals(compileResult.getErrorCount(), 266);
} | Assert.assertEquals(compileResult.getErrorCount(), 266); | public void setup() {
compileResult = BCompileUtil.compile("test-src/annotations/annot_attachments_negative.bal");
Assert.assertEquals(compileResult.getErrorCount(), 266);
} | class AnnotationAttachmentNegativeTest {
private CompileResult compileResult;
@BeforeClass
@Test
public void testInvalidAttachmentOnType() {
int index = 0;
int line = 39;
validateError(compileResult, index++, "annotation 'v2' is not allowed on type", line, 1);
val... | class AnnotationAttachmentNegativeTest {
private CompileResult compileResult;
@BeforeClass
@Test
public void testInvalidAttachmentOnType() {
int index = 0;
int line = 39;
validateError(compileResult, index++, "annotation 'v2' is not allowed on type", line, 1);
val... |
I think this is no longer valid. | private ClassLoader getClassLoader() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = getClass().getClassLoader();
}
if (cl == null) {
cl = Object.class.getClassLoader();
}
... | private ClassLoader getClassLoader() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = getClass().getClassLoader();
}
if (cl == null) {
cl = Object.class.getClassLoader();
}
return cl;
} | class DevClasspathStaticHandler implements Handler<RoutingContext> {
private static final Logger LOG = Logger.getLogger(DevClasspathStaticHandler.class);
private static final Set<HttpMethod> ALLOWED_HTTP_METHODS = Set.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS);
private static final int HTTP_ST... | class DevClasspathStaticHandler implements Handler<RoutingContext> {
private static final Logger LOG = Logger.getLogger(DevClasspathStaticHandler.class);
private static final int HTTP_STATUS_OK = 200;
private static final int HTTP_STATUS_NO_CONTENT = 204;
private static final String ALLOW_HEADER = "All... | |
Okay got it :) So we can remove the check for the os and have only the check for the file name | private static boolean isDirEmpty(final Path directory) throws IOException {
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory)) {
Iterator pathIterator = dirStream.iterator();
if (pathIterator.hasNext()) {
Path path = (Path) pathIte... | !pathIterator.hasNext(); | private static boolean isDirEmpty(final Path directory) throws IOException {
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory)) {
Iterator pathIterator = dirStream.iterator();
if (!pathIterator.hasNext()) {
return true;
}... | class InitCommand implements BLauncherCmd {
public static final String DEFAULT_VERSION = "0.0.1";
private static final String USER_DIR = "user.dir";
private static final PrintStream errStream = System.err;
private final Path homePath = RepoUtils.createAndGetHomeReposPath();
private boolean alreadyI... | class InitCommand implements BLauncherCmd {
public static final String DEFAULT_VERSION = "0.0.1";
private static final String USER_DIR = "user.dir";
private static final PrintStream errStream = System.err;
private final Path homePath = RepoUtils.createAndGetHomeReposPath();
private boolean alreadyI... |
If you need to support functions not in the form of xx(), but fun(A, B) in the future, how do you need to be compatible? | public Expr obtainExpr() {
if (SUPPORTED_DEFAULT_FNS.contains(expr)) {
String functionName = expr.replace("()", "");
FunctionCallExpr functionCallExpr = new FunctionCallExpr(new FunctionName(functionName), Lists.newArrayList());
Function fn = Expr.getBuiltinFunction(functionN... | String functionName = expr.replace("()", ""); | public Expr obtainExpr() {
if (SUPPORTED_DEFAULT_FNS.contains(expr)) {
String functionName = expr.replace("()", "");
FunctionCallExpr functionCallExpr = new FunctionCallExpr(new FunctionName(functionName), Lists.newArrayList());
Function fn = Expr.getBuiltinFunction(functionN... | class DefaultExpr {
public static final Set<String> SUPPORTED_DEFAULT_FNS = ImmutableSet.of("uuid()", "uuid_numeric()");
@SerializedName("expr")
private String expr;
public DefaultExpr(String expr) {
this.expr = expr;
}
public String getExpr() {
return expr;
}
public... | class DefaultExpr {
public static final Set<String> SUPPORTED_DEFAULT_FNS = ImmutableSet.of("uuid()", "uuid_numeric()");
@SerializedName("expr")
private String expr;
public DefaultExpr(String expr) {
this.expr = expr;
}
public String getExpr() {
return expr;
}
public... |
Why are we setting a default page size here? Shouldn't this be handled by the creator of this type? | public ContinuablePagedIterable(ContinuablePagedFlux<C, T, P> pagedFlux, int batchSize) {
super(pagedFlux);
this.pagedFlux = pagedFlux;
this.batchSize = batchSize;
this.defaultPageSize = 1;
this.continuationPredicate = null;
this.syncPageRetrieverProvider = null;
} | this.defaultPageSize = 1; | public ContinuablePagedIterable(ContinuablePagedFlux<C, T, P> pagedFlux, int batchSize) {
super(pagedFlux);
this.pagedFlux = pagedFlux;
this.batchSize = batchSize;
this.defaultPageSize = null;
this.continuationPredicate = null;
this.pageRetrieverSyncProvider = null;
} | class ContinuablePagedIterable<C, T, P extends ContinuablePage<C, T>> extends IterableStream<T> {
private static final ClientLogger LOGGER = new ClientLogger(ContinuablePagedIterable.class);
private final ContinuablePagedFlux<C, T, P> pagedFlux;
private final int batchSize;
private final Supplier<SyncPa... | class ContinuablePagedIterable<C, T, P extends ContinuablePage<C, T>> extends IterableStream<T> {
private static final ClientLogger LOGGER = new ClientLogger(ContinuablePagedIterable.class);
private final ContinuablePagedFlux<C, T, P> pagedFlux;
private final int batchSize;
private final Supplier<PageRe... |
@pubudu538 ATM T1 values are all capital. eg: `ARRAY`. Shall we make it like `Array`? | private String getTypeErrorMessage(Type found) {
Map<String, String> message = this.schema.message();
String typeCustomMessage = message.get(SchemaDeserializer.TYPE);
if (typeCustomMessage == null) {
return String.format("key '%s' expects %s . found %s", this.key, schema.type(), foun... | return String.format("key '%s' expects %s . found %s", this.key, schema.type(), found); | private String getTypeErrorMessage(Type found) {
Map<String, String> message = this.schema.message();
String typeCustomMessage = message.get(SchemaDeserializer.TYPE);
if (typeCustomMessage == null) {
return String.format("incompatible type for key '%s': expected '%s', found '%s'", th... | class SchemaValidator extends TomlNodeVisitor {
private static final String PROPERTY_HOLDER = "${property}";
private AbstractSchema schema;
private String key;
public SchemaValidator(Schema schema) {
this.schema = schema;
}
@Override
public void visit(TomlTableNode tomlTableNode)... | class SchemaValidator extends TomlNodeVisitor {
private static final String PROPERTY_HOLDER = "${property}";
private AbstractSchema schema;
private String key;
private String schemaTitle;
public SchemaValidator(Schema schema) {
this.schema = schema;
this.schemaTitle = schema.title... |
`totalCount` has been removed from accumulator in the latest commit, and will be calculated in `getValue()` once needed. | public Double[] getValue() {
List<Pair<Double, Integer>> sortedPercentages = new ArrayList<>();
for (int index = 0; index < percentages.length; index++) {
sortedPercentages.add(new Pair<>(percentages[index] * (totalCount - 1) + 1, index));
}
... | public Double[] getValue() {
long totalCount = 0L;
List<Map.Entry<Double, Long>> sortedList = new ArrayList<>();
try {
for (Map.Entry<Double, Long> entry : valueCount.entries()) {
sortedList.add(... | class PercentileAccumulator {
public double[] percentages;
public long totalCount;
public MapView<Double, Long> valueCount;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass(... | class PercentileAccumulator {
public double[] percentages;
public MapView<Double, Long> valueCount;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
... | |
Imo it just shouldnt print anythiNg unless debug. Why would we want those behind firewalls to get annoying message on every build? | public void close() {
try {
CompletableFuture.allOf(postFutures.toArray(new CompletableFuture[0])).get(
PropertyUtils.getProperty("quarkus.analytics.timeout", DEFAULT_TIMEOUT),
TimeUnit.MILLISECONDS);
if (log.isDebugEnabled() && !postF... | log.info("[Quarkus build analytics] Failed to send build analytics to Segment. " + | public void close() {
try {
CompletableFuture.allOf(postFutures.toArray(new CompletableFuture[0])).get(
PropertyUtils.getProperty("quarkus.analytics.timeout", DEFAULT_TIMEOUT),
TimeUnit.MILLISECONDS);
if (log.isDebugEnabled() && !postF... | class AnalyticsService implements AutoCloseable {
private final Queue<CompletableFuture<HttpResponse<String>>> postFutures;
final private RestClient restClient;
final private ConfigService config;
final private AnonymousUserId userId;
final private MessageWriter log;
final FileLocations fileLoc... | class AnalyticsService implements AutoCloseable {
private final Queue<CompletableFuture<HttpResponse<String>>> postFutures;
final private RestClient restClient;
final private ConfigService config;
final private AnonymousUserId userId;
final private MessageWriter log;
final FileLocations fileLoc... |
Should we also add this change to the changelog? | Mono<PiiEntityCollection> recognizePiiEntities(String document, String language) {
try {
Objects.requireNonNull(document, "'document' cannot be null.");
return recognizePiiEntitiesBatch(
Collections.singletonList(new TextDocumentInput("0", document).setLanguage(language))... | throw logger.logExceptionAsError(toTextAnalyticsException(entitiesResult.getError())); | Mono<PiiEntityCollection> recognizePiiEntities(String document, String language) {
try {
Objects.requireNonNull(document, "'document' cannot be null.");
return recognizePiiEntitiesBatch(
Collections.singletonList(new TextDocumentInput("0", document).setLanguage(language))... | class RecognizePiiEntityAsyncClient {
private final ClientLogger logger = new ClientLogger(RecognizePiiEntityAsyncClient.class);
private final TextAnalyticsClientImpl service;
/**
* Create a {@link RecognizePiiEntityAsyncClient} that sends requests to the Text Analytics services's
* recognize Per... | class RecognizePiiEntityAsyncClient {
private final ClientLogger logger = new ClientLogger(RecognizePiiEntityAsyncClient.class);
private final TextAnalyticsClientImpl service;
/**
* Create a {@link RecognizePiiEntityAsyncClient} that sends requests to the Text Analytics services's
* recognize Per... |
Let's open a separate issue for that, it's a bigger piece of work | public String getId() {
String id = this.title.toLowerCase().replaceAll(SPACE, DASH);
try {
id = URLEncoder.encode(id, StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
if (!this.isInternal()... | id = URLEncoder.encode(id, StandardCharsets.UTF_8.toString()); | public String getId() {
String id = this.title.toLowerCase().replaceAll(SPACE, DASH);
try {
id = URLEncoder.encode(id, StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
if (!this.isInternal()... | class Page {
private final String icon;
private final String title;
private final String staticLabel;
private final String dynamicLabel;
private final String streamingLabel;
private final String componentName;
private final String componentLink;
private final Map<String, String> ... | class Page {
private final String icon;
private final String title;
private final String staticLabel;
private final String dynamicLabel;
private final String streamingLabel;
private final String componentName;
private final String componentLink;
private final Map<String, String> ... |
Also, if we can, don't forget to update `AtomicCtasITCase`. | protected TableEnvironment getTableEnvironment() {
EnvironmentSettings settings = EnvironmentSettings.newInstance().inStreamingMode().build();
return StreamTableEnvironment.create(
StreamExecutionEnvironment.getExecutionEnvironment(), settings);
} | return StreamTableEnvironment.create( | protected TableEnvironment getTableEnvironment() {
EnvironmentSettings settings = EnvironmentSettings.newInstance().inStreamingMode().build();
return StreamTableEnvironment.create(
StreamExecutionEnvironment.getExecutionEnvironment(), settings);
} | class AtomicRtasITCase extends AtomicRtasITCaseBase {
@Override
} | class AtomicRtasITCase extends AtomicRtasITCaseBase {
@Override
} |
Let's keep this since there are multiple variables assigned inside the logic. | public void visit(TypeDefinitionNode typeDefinitionNode) {
int type = TokenTypes.TYPE.getId();
int modifiers = 0;
int refModifiers = 0;
Node typeDescriptor = typeDefinitionNode.typeDescriptor();
switch (typeDescriptor.kind()) {
case OBJECT_TYPE_DESC:
t... | refModifiers = TokenTypeModifiers.READONLY.getId(); | public void visit(TypeDefinitionNode typeDefinitionNode) {
int type = TokenTypes.TYPE.getId();
int modifiers = 0;
int refModifiers = 0;
Node typeDescriptor = typeDefinitionNode.typeDescriptor();
switch (typeDescriptor.kind()) {
case OBJECT_TYPE_DESC:
t... | class SemanticTokensVisitor extends NodeVisitor {
private final Set<SemanticToken> semanticTokens;
private final SemanticTokensContext semanticTokensContext;
public SemanticTokensVisitor(SemanticTokensContext semanticTokensContext) {
this.semanticTokens = new TreeSet<>(SemanticToken.semanticT... | class SemanticTokensVisitor extends NodeVisitor {
private final Set<SemanticToken> semanticTokens;
private final SemanticTokensContext semanticTokensContext;
public SemanticTokensVisitor(SemanticTokensContext semanticTokensContext) {
this.semanticTokens = new TreeSet<>(SemanticToken.semanticT... |
That's not the most important thing this block is trying to accomplish: It's making sure an up-to-date node is fetched from node repo, mutated, and saved back, all under the application lock. This avoid overwriting fields others may have modified on the node since above. | void retireAllocated() {
List<Node> allNodes = nodeRepository().getNodes(NodeType.tenant);
List<ApplicationId> activeApplications = getActiveApplicationIds(allNodes);
Map<Flavor, Map<Node.State, Long>> numSpareNodesByFlavorByState = getNumberOfNodesByFlavorByNodeState(allNodes);
flavorSp... | void retireAllocated() {
List<Node> allNodes = nodeRepository().getNodes(NodeType.tenant);
List<ApplicationId> activeApplications = getActiveApplicationIds(allNodes);
Map<Flavor, Map<Node.State, Long>> numSpareNodesByFlavorByState = getNumberOfNodesByFlavorByNodeState(allNodes);
flavorSp... | class NodeRetirer extends Maintainer {
public static final FlavorSpareChecker.SpareNodesPolicy SPARE_NODES_POLICY = flavorSpareCount ->
flavorSpareCount.getNumReadyAmongReplacees() > 2;
private static final long MAX_SIMULTANEOUS_RETIRES_PER_APPLICATION = 1;
private static final Logger log = Log... | class NodeRetirer extends Maintainer {
public static final FlavorSpareChecker.SpareNodesPolicy SPARE_NODES_POLICY = flavorSpareCount ->
flavorSpareCount.getNumReadyAmongReplacees() > 2;
private static final long MAX_SIMULTANEOUS_RETIRES_PER_APPLICATION = 1;
private static final Logger log = Log... | |
We can set it, but we don't need to use it. | public List<OptExpression> transform(OptExpression input, OptimizerContext context) {
LogicalScanOperator scanOperator = (LogicalScanOperator) input.getOp();
ColumnRefSet requiredOutputColumns = context.getTaskContext().getRequiredColumns();
Set<ColumnRefOperator> outputColumn... | boolean canUseAnyColumn = false; | public List<OptExpression> transform(OptExpression input, OptimizerContext context) {
LogicalScanOperator scanOperator = (LogicalScanOperator) input.getOp();
ColumnRefSet requiredOutputColumns = context.getTaskContext().getRequiredColumns();
Set<ColumnRefOperator> outputColumn... | class PruneScanColumnRule extends TransformationRule {
public static final PruneScanColumnRule OLAP_SCAN = new PruneScanColumnRule(OperatorType.LOGICAL_OLAP_SCAN);
public static final PruneScanColumnRule SCHEMA_SCAN = new PruneScanColumnRule(OperatorType.LOGICAL_SCHEMA_SCAN);
public static final PruneScanCo... | class PruneScanColumnRule extends TransformationRule {
public static final PruneScanColumnRule OLAP_SCAN = new PruneScanColumnRule(OperatorType.LOGICAL_OLAP_SCAN);
public static final PruneScanColumnRule SCHEMA_SCAN = new PruneScanColumnRule(OperatorType.LOGICAL_SCHEMA_SCAN);
public static final PruneScanCo... |
I initialized vals[1] with an empty by default so that the NPE wouldnt arise. But ideally, the default value provided in the mock annotation should be applied in this case. | public void process(FunctionNode functionNode, List<AnnotationAttachmentNode> annotations) {
parent = (BLangPackage) ((BLangFunction) functionNode).parent;
String packageName = getPackageName(parent);
annotations = annotations.stream().distinct().collect(Collectors.toList());
... | public void process(FunctionNode functionNode, List<AnnotationAttachmentNode> annotations) {
BLangPackage parent = (BLangPackage) ((BLangFunction) functionNode).parent;
String packageName = getPackageName(parent);
annotations = annotations.stream().distinct().collect(Collectors.toList());
... | class MockAnnotationProcessor extends AbstractCompilerPlugin {
private static final String MOCK_ANNOTATION_NAME = "Mock";
private static final String MODULE = "moduleName";
private static final String FUNCTION = "functionName";
private static final String MOCK_ANNOTATION_DELIMITER = "
private static... | class MockAnnotationProcessor extends AbstractCompilerPlugin {
private static final String MOCK_ANNOTATION_NAME = "Mock";
private static final String MODULE = "moduleName";
private static final String FUNCTION = "functionName";
private static final String MOCK_ANNOTATION_DELIMITER = "
private static... | |
@maxandersen No, This PR will affect neither `http://127.0.0.1:8080/q/dev/` nor `0.0.0.0:8080/q/dev/` since DevUI pages are not implemented as SPA using XHR or Fetch scripts, so `Origin` will not be even produced by the browser. For the next version of DevUI the Origin check may need to be adjusted. | public void handle(RoutingContext event) {
HttpServerRequest request = event.request();
HttpServerResponse response = event.response();
String origin = request.getHeader(HttpHeaders.ORIGIN);
if (origin == null) {
event.next();
} else {
if (!origin.contains... | response.end(); | public void handle(RoutingContext event) {
HttpServerRequest request = event.request();
HttpServerResponse response = event.response();
String origin = request.getHeader(HttpHeaders.ORIGIN);
if (origin == null) {
corsFilter().handle(event);
} else {
if (or... | class DevConsoleCORSFilter extends CORSFilter {
private static final String LOCAL_HOST = "localhost";
private static final String HTTP_LOCAL_HOST = "http:
private static final String HTTPS_LOCAL_HOST = "https:
public DevConsoleCORSFilter() {
super(corsConfig());
}
private static CORSC... | class DevConsoleCORSFilter implements Handler<RoutingContext> {
private static final Logger LOG = Logger.getLogger(DevConsoleCORSFilter.class);
private static final String HTTP_PORT_CONFIG_PROP = "quarkus.http.port";
private static final String HTTPS_PORT_CONFIG_PROP = "quarkus.http.ssl-port";
private ... |
Why not simply use an `AsyncCache`? Then you can write this as, ```java boolean[] isCurrentThreadComputation = { false }; var future = cache.get(key, (k, executor) -> { isCurrentThreadComputation[0] = true; return CompletableFuture.supplyAsync(() -> toCacheValue(valueLoader.call()), executor); }); try { Object v... | public Object get(Object key, Callable<Object> valueLoader, long lockTimeout) throws Exception {
if (lockTimeout <= 0) {
return fromCacheValue(cache.get(key, new MappingFunction(valueLoader)));
}
/*
* If the current key is not already associated with a value in th... | return fromCacheValue(cache.get(key, new MappingFunction(valueLoader, isCurrentThreadComputation))); | public Object get(Object key, Callable<Object> valueLoader, long lockTimeout) throws Exception {
if (lockTimeout <= 0) {
return fromCacheValue(cache.synchronous().get(key, k -> new MappingSupplier(valueLoader).get()));
}
/*
* If the current key is not already asso... | class CaffeineCache implements Cache {
private com.github.benmanes.caffeine.cache.Cache<Object, Object> cache;
private String name;
private Integer initialCapacity;
private Long maximumSize;
private Duration expireAfterWrite;
private Duration expireAfterAccess;
public CaffeineCache(Ca... | class CaffeineCache {
private AsyncCache<Object, Object> cache;
private String name;
private Integer initialCapacity;
private Long maximumSize;
private Duration expireAfterWrite;
private Duration expireAfterAccess;
public CaffeineCache(CaffeineCacheInfo cacheInfo) {
this.name ... |
stopServices may throw an exception on failure. But we want to ignore such a failure, I think. @hmusum Do we also want to ignore stopServices() if active? I think so. Taking down the container may be considered equivalent to a reboot of a node, in case stopping the services are first tried, then forced (KILL), as p... | private Optional<Container> removeContainerIfNeeded(ContainerNodeSpec nodeSpec) {
Optional<Container> existingContainer = getContainer();
if (!existingContainer.isPresent()) return Optional.empty();
Optional<String> removeReason = shouldRemoveContainer(nodeSpec, existingContainer.get());
... | stopServices(); | private Optional<Container> removeContainerIfNeeded(ContainerNodeSpec nodeSpec) {
Optional<Container> existingContainer = getContainer();
if (!existingContainer.isPresent()) return Optional.empty();
Optional<String> removeReason = shouldRemoveContainer(nodeSpec, existingContainer.get());
... | class NodeAgentImpl implements NodeAgent {
private final AtomicBoolean terminated = new AtomicBoolean(false);
private boolean isFrozen = true;
private boolean wantFrozen = false;
private boolean workToDoNow = true;
private final Object monitor = new Object();
private final PrefixLogger logger;... | class NodeAgentImpl implements NodeAgent {
private final AtomicBoolean terminated = new AtomicBoolean(false);
private boolean isFrozen = true;
private boolean wantFrozen = false;
private boolean workToDoNow = true;
private final Object monitor = new Object();
private final PrefixLogger logger;... |
this is the most difficult model I have ever seen :laughing: | public JsonWriter toJson(JsonWriter jsonWriter) {
return null;
} | return null; | public JsonWriter toJson(JsonWriter jsonWriter) {
return toJsonInternal(jsonWriter, "foo");
} | class Foo implements JsonCapable<Foo> {
@JsonProperty(value = "properties.bar")
private String bar;
@JsonProperty(value = "properties.props.baz")
private List<String> baz;
@JsonProperty(value = "properties.props.q.qux")
private Map<String, String> qux;
@JsonProperty(value = "properties.more\... | class Foo implements JsonCapable<Foo> {
private String bar;
private List<String> baz;
private Map<String, String> qux;
private String moreProps;
private Integer empty;
private Map<String, Object> additionalProperties;
public String bar() {
return bar;
}
public void bar(Stri... |
I wanted to keep the declaration of a class and its features encapsulated in single class. Agree that this doesn't play well with the rest of the `DoFnSignaturesTest`. But because there is effort in the direction of superseding all this with "pipeline features", I think it is fine to keep is as is for now and drop it a... | public void testAllDoFnFeatures() {
tests.forEach(FeatureTest::test);
} | tests.forEach(FeatureTest::test); | public void testAllDoFnFeatures() {
tests.forEach(FeatureTest::test);
} | class Splittable extends DoFn<KV<String, Long>, String> implements FeatureTest {
@ProcessElement
public void process(ProcessContext c, RestrictionTracker<OffsetRange, ?> tracker) {}
@GetInitialRestriction
public OffsetRange getInitialRange(@Element KV<String, Long> element) {
return new OffsetRan... | class Splittable extends DoFn<KV<String, Long>, String> implements FeatureTest {
@ProcessElement
public void process(ProcessContext c, RestrictionTracker<OffsetRange, ?> tracker) {}
@GetInitialRestriction
public OffsetRange getInitialRange(@Element KV<String, Long> element) {
return new OffsetRan... |
hostNames is supposed to contain parentHostName already (if applicable) | public void suspend(String parentHostName, List<String> hostNames) {
final BatchOperationResult batchOperationResult;
try {
String params = String.join("&hostname=", hostNames);
String url = String.format("%s/%s?hostname=%s", ORCHESTRATOR_PATH_PREFIX_HOST_SUSPENSION_API,
... | String url = String.format("%s/%s?hostname=%s", ORCHESTRATOR_PATH_PREFIX_HOST_SUSPENSION_API, | public void suspend(String parentHostName, List<String> hostNames) {
final BatchOperationResult batchOperationResult;
try {
String params = String.join("&hostname=", hostNames);
String url = String.format("%s/%s?hostname=%s", ORCHESTRATOR_PATH_PREFIX_HOST_SUSPENSION_API,
... | class OrchestratorImpl implements Orchestrator {
private static final String ORCHESTRATOR_PATH_PREFIX = "/orchestrator";
static final String ORCHESTRATOR_PATH_PREFIX_HOST_API
= ORCHESTRATOR_PATH_PREFIX + HostApi.PATH_PREFIX;
static final String ORCHESTRATOR_PATH_PREFIX_HOST_SUSPENSION_API
... | class OrchestratorImpl implements Orchestrator {
private static final String ORCHESTRATOR_PATH_PREFIX = "/orchestrator";
static final String ORCHESTRATOR_PATH_PREFIX_HOST_API
= ORCHESTRATOR_PATH_PREFIX + HostApi.PATH_PREFIX;
static final String ORCHESTRATOR_PATH_PREFIX_HOST_SUSPENSION_API
... |
```suggestion // Java uses BigDecimal so 0.2 * 170 = 63.9... // BigDecimal.longValue() will round down to 63 instead of the expected 64 ``` | public void testTrySplitForProcessSplitOnMiddleWindow() throws Exception {
List<BoundedWindow> windows = ImmutableList.copyOf(currentElement.getWindows());
OffsetRangeTracker tracker = new OffsetRangeTracker(currentRestriction);
tracker.tryClaim(30L);
KV<WindowedSplitResult, Integer> result =
... | createSplitInWindow(new OffsetRange(0, 63), new OffsetRange(63, 100), window2); | public void testTrySplitForProcessSplitOnMiddleWindow() throws Exception {
List<BoundedWindow> windows = ImmutableList.copyOf(currentElement.getWindows());
OffsetRangeTracker tracker = new OffsetRangeTracker(currentRestriction);
tracker.tryClaim(30L);
KV<WindowedSplitResult, Integer> result =
... | class SplitTest {
private IntervalWindow window1;
private IntervalWindow window2;
private IntervalWindow window3;
private WindowedValue<String> currentElement;
private OffsetRange currentRestriction;
private Instant currentWatermarkEstimatorState;
KV<Instant, Instant> watermarkAndState;
... | class SplitTest {
private IntervalWindow window1;
private IntervalWindow window2;
private IntervalWindow window3;
private WindowedValue<String> currentElement;
private OffsetRange currentRestriction;
private Instant currentWatermarkEstimatorState;
KV<Instant, Instant> watermarkAndState;
... |
I'm not 100% why the requirements are being documented in this log. | public void onNext(T value) {
numberOfMessagesBeforeReadyCheck += 1;
if (numberOfMessagesBeforeReadyCheck >= maxMessagesBeforeCheck) {
numberOfMessagesBeforeReadyCheck = 0;
int waitTime = 1;
int totalTimeWaited = 0;
int phase = phaser.getPhase();
while (!outboundObserver.isReady())... | "Output channel stalled for {}s, outbound thread {}. gRPC requires that outbound " | public void onNext(T value) {
numberOfMessagesBeforeReadyCheck += 1;
if (numberOfMessagesBeforeReadyCheck >= maxMessagesBeforeCheck) {
numberOfMessagesBeforeReadyCheck = 0;
int waitTime = 1;
int totalTimeWaited = 0;
int phase = phaser.getPhase();
while (!outboundObserver.isReady())... | class DirectStreamObserver<T> implements StreamObserver<T> {
private static final Logger LOGGER = LoggerFactory.getLogger(DirectStreamObserver.class);
private static final int DEFAULT_MAX_MESSAGES_BEFORE_CHECK = 100;
private final Phaser phaser;
private final CallStreamObserver<T> outboundObserver;
private f... | class DirectStreamObserver<T> implements StreamObserver<T> {
private static final Logger LOGGER = LoggerFactory.getLogger(DirectStreamObserver.class);
private static final int DEFAULT_MAX_MESSAGES_BEFORE_CHECK = 100;
private final Phaser phaser;
private final CallStreamObserver<T> outboundObserver;
private f... |
Consider rewriting this using `Files` instead of `/bin/ln` | private void createSymlinkToCurrentFile() {
if (symlinkName == null) return;
File f = new File(fileName);
File f2 = new File(f.getParent(), symlinkName);
String[] cmd = new String[]{"/bin/ln", "-sf", f.getName(), f2.getPath()};
try {
int retval... | int retval = new ProcessExecuter().exec(cmd).getFirst(); | private void createSymlinkToCurrentFile() {
if (symlinkName == null) return;
File f = new File(fileName);
File f2 = new File(f.getParent(), symlinkName);
String[] cmd = new String[]{"/bin/ln", "-sf", f.getName(), f2.getPath()};
try {
int retval... | class LogThread<LOGTYPE> extends Thread {
long lastFlush = 0;
private FileOutputStream currentOutputStream = null;
private long nextRotationTime = 0;
private final String filePattern;
private String fileName;
private long lastDropPosition = 0;
private final LogW... | class LogThread<LOGTYPE> extends Thread {
private final Pollable<LOGTYPE> operationProvider;
long lastFlush = 0;
private FileOutputStream currentOutputStream = null;
private long nextRotationTime = 0;
private final String filePattern;
private volatile String fileName;
... |
Done, if the user limits the count. Otherwise I don't have access to the file path or size and can't infer it. I will file an issue in vert.x. | public void writeResponse(AsyncFile file, Type genericType, ServerRequestContext context) throws WebApplicationException {
ResteasyReactiveRequestContext ctx = ((ResteasyReactiveRequestContext) context);
ctx.suspend();
ServerHttpResponse response = context.serverResponse();
response.setC... | response.setChunked(true); | public void writeResponse(AsyncFile file, Type genericType, ServerRequestContext context) throws WebApplicationException {
ResteasyReactiveRequestContext ctx = ((ResteasyReactiveRequestContext) context);
ctx.suspend();
ServerHttpResponse response = context.serverResponse();
if (... | class ServerVertxAsyncFileMessageBodyWriter extends VertxAsyncFileMessageBodyWriter
implements ServerMessageBodyWriter<AsyncFile> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, ResteasyReactiveResourceInfo target, MediaType mediaType) {
return AsyncFile.class.i... | class ServerVertxAsyncFileMessageBodyWriter extends VertxAsyncFileMessageBodyWriter
implements ServerMessageBodyWriter<AsyncFile> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, ResteasyReactiveResourceInfo target, MediaType mediaType) {
return AsyncFile.class.i... |
I think you are right (about the last thing). Fixed. | private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) {
if ( ! application.deploying().isPresent()) return false;
Change change = application.deploying().get();
if (change instanceof Change.VersionChange) {
Version targetVersion = ((Change.V... | return false; | private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) {
if ( ! application.deploying().isPresent()) return false;
if (next == null) return true;
Change change = application.deploying().get();
if (change instanceof Change.VersionChange) {
... | class DeploymentTrigger {
/** The max duration a job may run before we consider it dead/hanging */
private final Duration jobTimeout;
private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName());
private final Controller controller;
private final Clock clock;
private ... | class DeploymentTrigger {
/** The max duration a job may run before we consider it dead/hanging */
private final Duration jobTimeout;
private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName());
private final Controller controller;
private final Clock clock;
private ... |
I see, there are two methods: `aggregateFieldBaseValue` and `aggregateField` | public void testAggregateLogicalValuesGlobally() {
Collection<BasicEnum> elements =
Lists.newArrayList(
BasicEnum.of("a", BasicEnum.Test.ONE), BasicEnum.of("a", BasicEnum.Test.TWO));
SampleAnyCombineFn<EnumerationType.Value> sampleAnyCombineFn = new SampleAnyCombineFn<>(100);
Field aggF... | SampleAnyCombineFn<EnumerationType.Value> sampleAnyCombineFn = new SampleAnyCombineFn<>(100); | public void testAggregateLogicalValuesGlobally() {
Collection<BasicEnum> elements =
Lists.newArrayList(
BasicEnum.of("a", BasicEnum.Test.ONE), BasicEnum.of("a", BasicEnum.Test.TWO));
CombineFn<EnumerationType.Value, ?, Iterable<EnumerationType.Value>> sampleAnyCombineFn =
Sample.any... | class BasicEnum {
enum Test {
ZERO,
ONE,
TWO
};
abstract String getKey();
abstract Test getEnumeration();
static BasicEnum of(String key, Test value) {
return new AutoValue_GroupTest_BasicEnum(key, value);
}
} | class BasicEnum {
enum Test {
ZERO,
ONE,
TWO
};
abstract String getKey();
abstract Test getEnumeration();
static BasicEnum of(String key, Test value) {
return new AutoValue_GroupTest_BasicEnum(key, value);
}
} |
I'm not sure why that was done for methods, I think it could be a different env but still a class env, we can check maybe. But, since we've been defining fields in the proper (or most relevant scope) why would be go back and define it in a less accurate (wider) scope? The issue you are trying to solve only applies to ... | private void analyzeModuleConfigurableAmbiguity(BLangPackage pkgNode) {
if (pkgNode.moduleContextDataHolder == null) {
return;
}
ModuleDescriptor rootModule = pkgNode.moduleContextDataHolder.descriptor();
Set<BVarSymbol> configVars = symResolver.getConfigVarSymbolsIncludingIm... | ModuleDescriptor rootModule = pkgNode.moduleContextDataHolder.descriptor(); | private void analyzeModuleConfigurableAmbiguity(BLangPackage pkgNode) {
if (pkgNode.moduleContextDataHolder == null) {
return;
}
ModuleDescriptor rootModule = pkgNode.moduleContextDataHolder.descriptor();
Set<BVarSymbol> configVars = symResolver.getConfigVarSymbolsIncludingIm... | class representing a service-decl or object-ctor with service prefix
AttachPoint.Point attachedPoint;
Set<Flag> flagSet = classDefinition.flagSet;
if (flagSet.contains(Flag.OBJECT_CTOR) && flagSet.contains(Flag.SERVICE)) {
attachedPoint = AttachPoint.Point.SERVICE;
} | class representing a service-decl or object-ctor with service prefix
AttachPoint.Point attachedPoint;
Set<Flag> flagSet = classDefinition.flagSet;
if (flagSet.contains(Flag.OBJECT_CTOR) && flagSet.contains(Flag.SERVICE)) {
attachedPoint = AttachPoint.Point.SERVICE;
} |
this change should be a separate hotfix | public void testSerializationOfUnknownShuffleDescriptor() throws Exception {
ShuffleDescriptor shuffleDescriptor = new UnknownShuffleDescriptor(resultPartitionID);
ShuffleDescriptor shuffleDescriptorCopy = CommonTestUtils.createCopySerializable(shuffleDescriptor);
assertThat(shuffleDescriptorCopy, instanceOf(Unkn... | assertThat(shuffleDescriptorCopy.getResultPartitionID(), is(resultPartitionID)); | public void testSerializationOfUnknownShuffleDescriptor() throws IOException {
ShuffleDescriptor shuffleDescriptor = new UnknownShuffleDescriptor(resultPartitionID);
ShuffleDescriptor shuffleDescriptorCopy = CommonTestUtils.createCopySerializable(shuffleDescriptor);
assertThat(shuffleDescriptorCopy, instanceOf(Un... | class ResultPartitionDeploymentDescriptorTest extends TestLogger {
private static final IntermediateDataSetID resultId = new IntermediateDataSetID();
private static final IntermediateResultPartitionID partitionId = new IntermediateResultPartitionID();
private static final ExecutionAttemptID producerExecutionId = ne... | class ResultPartitionDeploymentDescriptorTest extends TestLogger {
private static final IntermediateDataSetID resultId = new IntermediateDataSetID();
private static final IntermediateResultPartitionID partitionId = new IntermediateResultPartitionID();
private static final ExecutionAttemptID producerExecutionId = ne... |
I think the comments I left in the other location setting this could apply everywhere | public Response<PathProperties> readToFileWithResponse(ReadToFileOptions options, Duration timeout, Context context) {
Context newContext;
options = options == null ? new ReadToFileOptions() : options;
if (options.isUpn() != null) {
HttpHeaders headers = new HttpHeaders();
... | options = options == null ? new ReadToFileOptions() : options; | public Response<PathProperties> readToFileWithResponse(ReadToFileOptions options, Duration timeout, Context context) {
context = BuilderHelper.addUpnHeader(() -> (options == null) ? null : options.isUpn(), context);
Context finalContext = context;
return DataLakeImplUtils.returnOrConvertExcepti... | class DataLakeFileClient extends DataLakePathClient {
/**
* Indicates the maximum number of bytes that can be sent in a call to upload.
*/
private static final long MAX_APPEND_FILE_BYTES = DataLakeFileAsyncClient.MAX_APPEND_FILE_BYTES;
private static final ClientLogger LOGGER = new ClientLogger(... | class DataLakeFileClient extends DataLakePathClient {
/**
* Indicates the maximum number of bytes that can be sent in a call to upload.
*/
private static final long MAX_APPEND_FILE_BYTES = DataLakeFileAsyncClient.MAX_APPEND_FILE_BYTES;
private static final ClientLogger LOGGER = new ClientLogger(... |
I don't thinnk we _always_ want to mount this. Can you make doing so a job server command line arg and plumb it through? | public RemoteEnvironment createEnvironment(Environment environment) throws Exception {
String workerId = idGenerator.getId();
String containerImage = environment.getUrl();
String loggingEndpoint = loggingServiceServer.getApiServiceDescriptor().getUrl();
String artifactEndpoint = retrieva... | volArg.addAll(gcsCredentialArgs()); | public RemoteEnvironment createEnvironment(Environment environment) throws Exception {
String workerId = idGenerator.getId();
String containerImage = environment.getUrl();
String loggingEndpoint = loggingServiceServer.getApiServiceDescriptor().getUrl();
String artifactEndpoint = retrieva... | class DockerEnvironmentFactory implements EnvironmentFactory {
private static final Logger LOG = LoggerFactory.getLogger(DockerEnvironmentFactory.class);
/**
* Returns a {@link DockerEnvironmentFactory} for the provided {@link GrpcFnServer servers} using
* the default {@link DockerCommand}.
*/
public s... | class DockerEnvironmentFactory implements EnvironmentFactory {
private static final Logger LOG = LoggerFactory.getLogger(DockerEnvironmentFactory.class);
/**
* Returns a {@link DockerEnvironmentFactory} for the provided {@link GrpcFnServer servers} using
* the default {@link DockerCommand}.
*/
public s... |
why are we using containerLink and not containerName? | public String toString() {
if (this.cosmosContainerIdentities == null || cosmosContainerIdentities.isEmpty()) {
return "";
}
return String.format(
"(containers:%s)(pcrc:%d)(awd:%s)",
cosmosContainerIdentities
... | containerIdAccessor.getContainerLink(ci))) | public String toString() {
if (this.cosmosContainerIdentities == null || cosmosContainerIdentities.isEmpty()) {
return "";
}
return String.format(
"(containers:%s)(pcrc:%d)(awd:%s)",
cosmosContainerIdentities
... | class CosmosContainerProactiveInitConfig {
private final static ImplementationBridgeHelpers.CosmosContainerIdentityHelper.CosmosContainerIdentityAccessor
containerIdAccessor = ImplementationBridgeHelpers
.CosmosContainerIdentityHelper
.getCosmosContainerIdentityAccessor();
privat... | class CosmosContainerProactiveInitConfig {
private final static ImplementationBridgeHelpers.CosmosContainerIdentityHelper.CosmosContainerIdentityAccessor
containerIdAccessor = ImplementationBridgeHelpers
.CosmosContainerIdentityHelper
.getCosmosContainerIdentityAccessor();
privat... |
For the code itself, yes, this PR changed the logic. However, for the internal of Flink, we do not change the behavior, and I think current change is the correct thing. After each job finished, Flink will clean up job related data (such as checkpoint id counter) on [Dispatcher#removeJob](https://github.com/apache/flin... | public void internalCleanupJobData(JobID jobID) throws Exception {
kubeClient.deleteConfigMap(getJobSpecificConfigMap(jobID)).get();
} | kubeClient.deleteConfigMap(getJobSpecificConfigMap(jobID)).get(); | public void internalCleanupJobData(JobID jobID) throws Exception {
kubeClient.deleteConfigMap(getJobSpecificConfigMap(jobID)).get();
} | class KubernetesLeaderElectionHaServices extends AbstractHaServices {
private static final Logger LOG =
LoggerFactory.getLogger(KubernetesLeaderElectionHaServices.class);
private final String clusterId;
private final FlinkKubeClient kubeClient;
private final KubernetesConfigMapSharedWatc... | class KubernetesLeaderElectionHaServices extends AbstractHaServices {
private static final Logger LOG =
LoggerFactory.getLogger(KubernetesLeaderElectionHaServices.class);
private final String clusterId;
private final FlinkKubeClient kubeClient;
private final KubernetesConfigMapSharedWatc... |
Shall we order these alphabetically and have the same order as the spec (https://github.com/ballerina-platform/ballerina-spec/commit/158691e90bcc05c2f32137688d7669072fa911c0)? O:) | public void loadPredeclaredModules() {
Map<Name, BPackageSymbol> modules = new HashMap<>();
modules.put(Names.ERROR, this.langErrorModuleSymbol);
modules.put(Names.OBJECT, this.langObjectModuleSymbol);
modules.put(Names.XML, this.langXmlModuleSymbol);
modules.put(Names.INT, this.... | modules.put(Names.TYPEDESC, this.langTypedescModuleSymbol); | public void loadPredeclaredModules() {
Map<Name, BPackageSymbol> modules = new HashMap<>();
modules.put(Names.BOOLEAN, this.langBooleanModuleSymbol);
modules.put(Names.DECIMAL, this.langDecimalModuleSymbol);
modules.put(Names.ERROR, this.langErrorModuleSymbol);
modules.put(Names.... | class SymbolTable {
private static final CompilerContext.Key<SymbolTable> SYM_TABLE_KEY =
new CompilerContext.Key<>();
public static final PackageID TRANSACTION = new PackageID(Names.BUILTIN_ORG, Names.TRANSACTION_PACKAGE,
Names.EMPTY);
public static final Integer BBYTE_MIN_VALUE ... | class SymbolTable {
private static final CompilerContext.Key<SymbolTable> SYM_TABLE_KEY =
new CompilerContext.Key<>();
public static final PackageID TRANSACTION = new PackageID(Names.BUILTIN_ORG, Names.TRANSACTION_PACKAGE,
Names.EMPTY);
public static final Integer BBYTE_MIN_VALUE ... |
the rule only takes effect only when group by keys contain all unique key. If group by key is (colA, colB) but unique key is (colA, colB, colC), we cannot remove the agg. | public boolean check(OptExpression input, OptimizerContext context) {
LogicalAggregationOperator aggOp = input.getOp().cast();
if (aggOp.getGroupingKeys().isEmpty()) {
return false;
}
for (Map.Entry<ColumnRefOperator, CallOperator> entry : aggOp.getAggregations().entrySet())... | if (childOptExpression.getConstraints().getUniqueConstraint(columnRefOperator.getId()) == null) { | public boolean check(OptExpression input, OptimizerContext context) {
LogicalAggregationOperator aggOp = input.getOp().cast();
List<ColumnRefOperator> groupKeys = aggOp.getGroupingKeys();
for (Map.Entry<ColumnRefOperator, CallOperator> entry : aggOp.getAggregations().entrySet()) {
i... | class EliminateAggRule extends TransformationRule {
private EliminateAggRule() {
super(RuleType.TF_ELIMINATE_AGG, Pattern.create(OperatorType.LOGICAL_AGGR)
.addChildren(Pattern.create(OperatorType.PATTERN_LEAF)));
}
public static EliminateAggRule getInstance() {
return INST... | class EliminateAggRule extends TransformationRule {
private EliminateAggRule() {
super(RuleType.TF_ELIMINATE_AGG, Pattern.create(OperatorType.LOGICAL_AGGR)
.addChildren(Pattern.create(OperatorType.PATTERN_LEAF)));
}
public static EliminateAggRule getInstance() {
return INST... |
Out of time for today, but I just noticed this can happen in other tests as well. For example in [this run](https://github.com/apache/beam/pull/13128/checks?check_run_id=1398707923) we see the same flake in `testWhenServerHangsUpEarlyThatClientIsAbleCleanup` Leaving a note here so I remember to fix it later | public void testLogging() throws Exception {
AtomicBoolean clientClosedStream = new AtomicBoolean();
Collection<BeamFnApi.LogEntry> values = new ConcurrentLinkedQueue<>();
AtomicReference<StreamObserver<BeamFnApi.LogControl>> outboundServerObserver =
new AtomicReference<>();
CallStreamObserver<B... | assertTrue(channel.isShutdown()); | public void testLogging() throws Exception {
AtomicBoolean clientClosedStream = new AtomicBoolean();
Collection<BeamFnApi.LogEntry> values = new ConcurrentLinkedQueue<>();
AtomicReference<StreamObserver<BeamFnApi.LogControl>> outboundServerObserver =
new AtomicReference<>();
CallStreamObserver<B... | class BeamFnLoggingClientTest {
private static final LogRecord FILTERED_RECORD;
private static final LogRecord TEST_RECORD;
private static final LogRecord TEST_RECORD_WITH_EXCEPTION;
static {
FILTERED_RECORD = new LogRecord(Level.SEVERE, "FilteredMessage");
TEST_RECORD = new LogRecord(Level.FINE, "Me... | class BeamFnLoggingClientTest {
private static final LogRecord FILTERED_RECORD;
private static final LogRecord TEST_RECORD;
private static final LogRecord TEST_RECORD_WITH_EXCEPTION;
static {
FILTERED_RECORD = new LogRecord(Level.SEVERE, "FilteredMessage");
TEST_RECORD = new LogRecord(Level.FINE, "Me... |
It turned out map initializer literal could contain string keys. Since both map and record literals are the same, we have to check and act accordingly. Specially when `map m = { foo: "value", "foo": "value" }`. Will update the code to handle to handle previous edge case. | public void visit(BLangRecordLiteral recordLiteral) {
List<BLangRecordLiteral.BLangRecordKeyValue> keyValuePairs = recordLiteral.keyValuePairs;
keyValuePairs.forEach(kv -> {
analyzeExpr(kv.valueExpr);
});
Set<String> names = new HashSet<>();
for (BLangRecordLiteral.B... | if (keyExpr.getKind() == NodeKind.SIMPLE_VARIABLE_REF) { | public void visit(BLangRecordLiteral recordLiteral) {
List<BLangRecordLiteral.BLangRecordKeyValue> keyValuePairs = recordLiteral.keyValuePairs;
keyValuePairs.forEach(kv -> {
analyzeExpr(kv.valueExpr);
});
Set<Object> names = new TreeSet<>((l, r) -> l.equals(r) ? 0 : 1);
... | class CodeAnalyzer extends BLangNodeVisitor {
private static final CompilerContext.Key<CodeAnalyzer> CODE_ANALYZER_KEY =
new CompilerContext.Key<>();
private int loopCount;
private int transactionCount;
private boolean statementReturns;
private boolean lastStatement;
private boolea... | class CodeAnalyzer extends BLangNodeVisitor {
private static final CompilerContext.Key<CodeAnalyzer> CODE_ANALYZER_KEY =
new CompilerContext.Key<>();
private int loopCount;
private int transactionCount;
private boolean statementReturns;
private boolean lastStatement;
private boolea... |
An underscore is already included in “label". | public LoadResponse loadBatch(StringBuilder sb, boolean slowLog) {
Calendar calendar = Calendar.getInstance();
String label = String.format("_log_%s%02d%02d_%02d%02d%02d_%s",
calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH),
... | label = "slow" + label; | public LoadResponse loadBatch(StringBuilder sb, boolean slowLog) {
Calendar calendar = Calendar.getInstance();
String label = String.format("_log_%s%02d%02d_%02d%02d%02d_%s",
calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH),
... | class DorisStreamLoader {
private final static Logger LOG = LogManager.getLogger(DorisStreamLoader.class);
private static String loadUrlPattern = "http:
private String hostPort;
private String db;
private String auditLogTbl;
private String slowLogTbl;
private String user;
private String ... | class DorisStreamLoader {
private final static Logger LOG = LogManager.getLogger(DorisStreamLoader.class);
private static String loadUrlPattern = "http:
private String hostPort;
private String db;
private String auditLogTbl;
private String slowLogTbl;
private String user;
private String ... |
``` This is unlikely to work correctly. ``` Are you sure about this? I think it should be possible to run this without a context. Not sure why we had that issue only for MySQL and only on CI. | public HealthCheckResponse call() {
HealthCheckResponseBuilder builder = HealthCheckResponse.named(healthCheckResponseName);
builder.up();
for (Map.Entry<String, Pool> pgPoolEntry : pools.entrySet()) {
final String dataSourceName = pgPoolEntry.getKey();
final Pool pgPool... | log.warn("Vert.x context unavailable to perform healthcheck of reactive datasource `" + dataSourceName + "`. This is unlikely to work correctly."); | public HealthCheckResponse call() {
HealthCheckResponseBuilder builder = HealthCheckResponse.named(healthCheckResponseName);
builder.up();
for (Map.Entry<String, Pool> pgPoolEntry : pools.entrySet()) {
final String dataSourceName = pgPoolEntry.getKey();
final Pool pgPool... | class ReactiveDatasourceHealthCheck implements HealthCheck {
private static final Logger log = Logger.getLogger(ReactiveDatasourceHealthCheck.class);
private final Map<String, Pool> pools = new ConcurrentHashMap<>();
private final String healthCheckResponseName;
private final String healthCheckSQL;
... | class ReactiveDatasourceHealthCheck implements HealthCheck {
private static final Logger log = Logger.getLogger(ReactiveDatasourceHealthCheck.class);
private final Map<String, Pool> pools = new ConcurrentHashMap<>();
private final String healthCheckResponseName;
private final String healthCheckSQL;
... |
Wondering if this should be somehow connected to `TaskManagerServices#LOCAL_STATE_SUB_DIRECTORY_ROOT`. | private WorkingDirectory(File root) throws IOException {
this.root = root;
createDirectory(root);
this.tmp = new File(root, "tmp");
createDirectory(tmp);
FileUtils.cleanDirectory(tmp);
localState = new File(root, "localState");
createDirectory(localState);
} | localState = new File(root, "localState"); | private WorkingDirectory(File root) throws IOException {
this.root = root;
createDirectory(root);
this.tmp = new File(root, "tmp");
createDirectory(tmp);
FileUtils.cleanDirectory(tmp);
localState = new File(root, "localState");
createDirectory(localState);
} | class WorkingDirectory {
private final File root;
private final File tmp;
private final File localState;
private static void createDirectory(File directory) throws IOException {
if (!directory.mkdirs() && !directory.exists()) {
throw new IOException(
String... | class WorkingDirectory {
private final File root;
private final File tmp;
private final File localState;
private static void createDirectory(File directory) throws IOException {
if (!directory.mkdirs() && !directory.exists()) {
throw new IOException(
String... |
we really don't want pretty-printed bodies. Structured logs are exported somewhere where pretty printing is not necessary or, when sent to file or stdout, multi-line prettiness becomes ungreppable and unparseable. | public HttpLoggingPolicy(HttpLogOptions httpLogOptions) {
if (httpLogOptions == null) {
this.httpLogDetailLevel = HttpLogDetailLevel.ENVIRONMENT_HTTP_LOG_DETAIL_LEVEL;
this.allowedHeaderNames = HttpLogOptions.DEFAULT_HEADERS_ALLOWLIST
.stream()
.map(header... | this.prettyPrintBody = false; | public HttpLoggingPolicy(HttpLogOptions httpLogOptions) {
if (httpLogOptions == null) {
this.httpLogDetailLevel = HttpLogDetailLevel.ENVIRONMENT_HTTP_LOG_DETAIL_LEVEL;
this.allowedHeaderNames = HttpLogOptions.DEFAULT_HEADERS_ALLOWLIST
.stream()
.map(header... | class HttpLoggingPolicy implements HttpPipelinePolicy {
private static final ObjectMapperShim PRETTY_PRINTER = ObjectMapperShim.createPrettyPrintMapper();
private static final int MAX_BODY_LOG_SIZE = 1024 * 16;
private static final String REDACTED_PLACEHOLDER = "REDACTED";
... | class HttpLoggingPolicy implements HttpPipelinePolicy {
private static final ObjectMapperShim PRETTY_PRINTER = ObjectMapperShim.createPrettyPrintMapper();
private static final int MAX_BODY_LOG_SIZE = 1024 * 16;
private static final String REDACTED_PLACEHOLDER = "REDACTED";
... |
At some point we should make this a little nice so we can easily add more values. I am thinking of the following HTTP clients that I personally use: `httpie`, `IntelliJ HTTP Client` and `Postman` (although I am not sure what values they use for the header - if any) | static String pickFirstSupportedAndAcceptedContentType(RoutingContext context) {
List<MIMEHeader> acceptableTypes = context.parsedHeaders().accept();
String userAgent = context.request().getHeader("User-Agent");
if (userAgent != null && (userAgent.toLowerCase(Locale.ROOT).startsWith... | || userAgent.toLowerCase(Locale.ROOT).startsWith("curl/"))) { | static String pickFirstSupportedAndAcceptedContentType(RoutingContext context) {
List<MIMEHeader> acceptableTypes = context.parsedHeaders().accept();
String userAgent = context.request().getHeader("User-Agent");
if (userAgent != null && (userAgent.toLowerCase(Locale.ROOT).startsWith... | class ContentTypes {
private ContentTypes() {
}
private static final String APPLICATION_JSON = "application/json";
private static final String TEXT_JSON = "text/json";
private static final String TEXT_HTML = "text/html";
private static final String TEXT_PLAIN = "text/pl... | class ContentTypes {
private ContentTypes() {
}
private static final String APPLICATION_JSON = "application/json";
private static final String TEXT_JSON = "text/json";
private static final String TEXT_HTML = "text/html";
private static final String TEXT_PLAIN = "text/pl... |
Yeah, this can be ignored since we have set the binder name as "kafka" | public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof BindingServiceProperties) {
BindingServiceProperties bindingServiceProperties = (BindingServiceProperties) bean;
if (bindingServiceProperties.getBinders().isEmpty()) {
... | kafkaBinderSourceProperty.setType(KAKFA_BINDER_TYPE); | public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof BindingServiceProperties) {
BindingServiceProperties bindingServiceProperties = (BindingServiceProperties) bean;
if (bindingServiceProperties.getBinders().isEmpty()) {
... | class BindingServicePropertiesBeanPostProcessor implements BeanPostProcessor {
static final String SPRING_MAIN_SOURCES_PROPERTY = "spring.main.sources";
private static final String KAKFA_BINDER_DEFAULT_NAME = "kafka";
private static final String KAKFA_BINDER_TYPE = "kafka";
@Override
private... | class BindingServicePropertiesBeanPostProcessor implements BeanPostProcessor {
static final String SPRING_MAIN_SOURCES_PROPERTY = "spring.main.sources";
private static final String KAKFA_BINDER_DEFAULT_NAME = "kafka";
private static final String KAKFA_BINDER_TYPE = "kafka";
@Override
private... |
why compare row number first then sort key ? | public int compare(CandidateContext context1, CandidateContext context2) {
int ret = Integer.compare(context1.getGroupbyColumnNum(), context2.getGroupbyColumnNum());
if (ret != 0) {
return ret;
}
ret = Double.compare(context1.getM... | public int compare(CandidateContext context1, CandidateContext context2) {
int ret = Integer.compare(context1.getGroupbyColumnNum(), context2.getGroupbyColumnNum());
if (ret != 0) {
return ret;
}
ret = Integer.compare(context2.so... | class CandidateContextComparator implements Comparator<CandidateContext> {
@Override
} | class CandidateContextComparator implements Comparator<CandidateContext> {
@Override
} | |
Ah wait, I see what you done here. The second cast is unused | public Runnable loadRealm(RuntimeValue<SecurityRealm> realm, SecurityUsersConfig propertiesConfig) throws Exception {
return new Runnable() {
@Override
public void run() {
try {
PropertiesRealmConfig config = propertiesConfig.file();
... | if (!(secRealm instanceof LegacyPropertiesSecurityRealm propsRealm)) { | public Runnable loadRealm(RuntimeValue<SecurityRealm> realm, SecurityUsersConfig propertiesConfig) throws Exception {
return new Runnable() {
@Override
public void run() {
try {
PropertiesRealmConfig config = propertiesConfig.file();
... | class ElytronPropertiesFileRecorder {
static final Logger log = Logger.getLogger(ElytronPropertiesFileRecorder.class);
private static final Provider[] PROVIDERS = new Provider[] { new WildFlyElytronPasswordProvider() };
/**
* Load the user.properties and roles.properties files into the {@linkplain Se... | class ElytronPropertiesFileRecorder {
static final Logger log = Logger.getLogger(ElytronPropertiesFileRecorder.class);
private static final Provider[] PROVIDERS = new Provider[] { new WildFlyElytronPasswordProvider() };
/**
* Load the user.properties and roles.properties files into the {@linkplain Se... |
I think we don't need `parseXMLStepExtendList`method at all :) Reason is `.<`, `.` and `[` are already handled by parseExpressionRhs method. So xml-step-expression node always have only `lhsExpr` and `xmlStepStart` | private boolean isServiceDeclStart(ParserRuleContext currentContext, int lookahead) {
switch (peek(lookahead + 1).kind) {
case IDENTIFIER_TOKEN:
SyntaxKind tokenAfterIdentifier = peek(lookahead + 2).kind;
switch (tokenAfterIdentifier) {
ca... | STNode xmlStepExtendList = parseXMLStepExtendList(); | 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 BallerinaParser extends AbstractParser {
private static final OperatorPrecedence DEFAULT_OP_PRECEDENCE = OperatorPrecedence.ACTION;
protected BallerinaParser(AbstractTokenReader tokenReader) {
super(tokenReader, new BallerinaParserErrorHandler(tokenReader));
}
/**
* Start parsing t... | class BallerinaParser extends AbstractParser {
private static final OperatorPrecedence DEFAULT_OP_PRECEDENCE = OperatorPrecedence.ACTION;
protected BallerinaParser(AbstractTokenReader tokenReader) {
super(tokenReader, new BallerinaParserErrorHandler(tokenReader));
}
/**
* Start parsing t... |
There is no such decorator. So, until its implemented we cant use it. | private void applyConfig(Session session, String target, String name, PlatformConfiguration config) {
config.getLabels().entrySet().stream().forEach(e -> {
session.resources().decorate(target, new AddLabelDecorator(new Label(e.getKey(), e.getValue())));
});
config.... | session.resources().decorate(target, new AddSecretVolumeDecorator(SecretVolumeConverter.convert(e))); | private void applyConfig(Session session, String target, String name, PlatformConfiguration config) {
config.getLabels().forEach((key, value) -> {
session.resources().decorate(target, new AddLabelDecorator(new Label(key, value)));
});
config.getAnnotations().forEac... | class KubernetesProcessor {
private static final String PROPERTY_PREFIX = "dekorate.";
private static final Set<String> ALLOWED_GENERATORS = new HashSet(
Arrays.asList("kubernetes", "openshift", "knative", "docker", "s2i"));
private static final Set<String> IMAGE_GENERATORS = new HashSet(Arrays... | class KubernetesProcessor {
private static final String PROPERTY_PREFIX = "dekorate.";
private static final String DOCKER_REGISTRY_PROPERTY = PROPERTY_PREFIX + "docker.registry";
private static final String APP_GROUP_PROPERTY = "app.group";
private static final String OUTPUT_ARTIFACT_FORMAT = "%s%s.jar... |
One already created bean, which generally won't happen until runtime when you actually have vert.x. Currently if you fail in static init then this method is called, but vert.x is not ready yet (as it is a runtime bean), so you get an extra unrelated exception in your logs (and possible unclean shutdown). | void undeployVerticles(@Observes @BeforeDestroyed(ApplicationScoped.class) Object event, BeanManager beanManager) {
Set<Bean<?>> beans = beanManager.getBeans(AbstractVerticle.class, Any.Literal.INSTANCE);
Context applicationContext = beanManager.getContext(ApplicationScoped.class);
for ... | io.vertx.mutiny.core.Vertx mutiny = beanManager.createInstance() | void undeployVerticles(@Observes @BeforeDestroyed(ApplicationScoped.class) Object event, BeanManager beanManager) {
Set<Bean<?>> beans = beanManager.getBeans(AbstractVerticle.class, Any.Literal.INSTANCE);
Context applicationContext = beanManager.getContext(ApplicationScoped.class);
for ... | class VertxProducer {
private static final Logger LOGGER = Logger.getLogger(VertxProducer.class);
@Singleton
@Produces
public EventBus eventbus(Vertx vertx) {
return vertx.eventBus();
}
@Singleton
@Produces
public io.vertx.mutiny.core.Vertx mutiny(Vertx vertx) {
return... | class VertxProducer {
private static final Logger LOGGER = Logger.getLogger(VertxProducer.class);
@Singleton
@Produces
public EventBus eventbus(Vertx vertx) {
return vertx.eventBus();
}
@Singleton
@Produces
public io.vertx.mutiny.core.Vertx mutiny(Vertx vertx) {
return... |
In here the effectiveTypeDescriptor method gives the correct result. We are using that type symbol to get the langlibs. So this is not an issue right? ``` type Type1 object { }; type Type2 readonly & Type1; type Type3 Type2; type Type4 Type3; function name() { Type4 t = object {}; t.<cursor> } ``` I tried wi... | public List<FunctionSymbol> langLibMethods() {
if (this.langLibFunctions == null) {
if (this.effectiveTypeDescriptor().typeKind() == TypeDescKind.OBJECT) {
this.langLibFunctions = this.effectiveTypeDescriptor().langLibMethods();
} else if (this.effectiveTypeDescriptor().t... | TypeReferenceTypeSymbol typeRef = (TypeReferenceTypeSymbol) this.effectiveTypeDescriptor(); | public List<FunctionSymbol> langLibMethods() {
if (this.langLibFunctions == null) {
if (this.effectiveTypeDescriptor().typeKind() == TypeDescKind.OBJECT) {
this.langLibFunctions = this.effectiveTypeDescriptor().langLibMethods();
} else if (this.effectiveTypeDescriptor().t... | class BallerinaIntersectionTypeSymbol extends AbstractTypeSymbol implements IntersectionTypeSymbol {
private List<TypeSymbol> memberTypes;
private TypeSymbol effectiveType;
private String signature;
public BallerinaIntersectionTypeSymbol(CompilerContext context, BIntersectionType intersectionType) {
... | class BallerinaIntersectionTypeSymbol extends AbstractTypeSymbol implements IntersectionTypeSymbol {
private List<TypeSymbol> memberTypes;
private TypeSymbol effectiveType;
private String signature;
public BallerinaIntersectionTypeSymbol(CompilerContext context, BIntersectionType intersectionType) {
... |
AFAIK the generated subclass has a "forward method" for every intercepted method and this method is invoked if you do `IC.proceed()` in the last interceptor from the chain. | void forEachMethod(ClassInfo clazz, Consumer<MethodInfo> action) {
for (MethodInfo method : clazz.methods()) {
if (method.name().startsWith("<")) {
continue;
}
if (Modifier.isPrivate(method.flags())) {
continue... | void forEachMethod(ClassInfo clazz, Consumer<MethodInfo> action) {
for (MethodInfo method : clazz.methods()) {
if (method.name().startsWith("<")) {
continue;
}
if (method.isSynthetic()) {
continue;
... | class FaultToleranceScanner {
private final IndexView index;
private final AnnotationStore annotationStore;
private final AnnotationProxyBuildItem proxy;
private final ClassOutput output;
FaultToleranceScanner(IndexView index, AnnotationStore annotationStore, AnnotationProxyBuildItem proxy,
... | class FaultToleranceScanner {
private final IndexView index;
private final AnnotationStore annotationStore;
private final AnnotationProxyBuildItem proxy;
private final ClassOutput output;
FaultToleranceScanner(IndexView index, AnnotationStore annotationStore, AnnotationProxyBuildItem proxy,
... | |
Not sure why those weren't added before (they also exist prior to 3.0) and I was seeing a (non-blocking?) NPE w.r.t. to `mariadb.properties`, so I added [both](https://github.com/mariadb-corporation/mariadb-connector-j/tree/3.0.3/src/main/resources). | 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(
... |
JDBC maybe does not have these time attributes | public List<String> supportedProperties() {
List<String> properties = new ArrayList<>();
properties.add(CONNECTOR_DRIVER_NAME);
properties.add(CONNECTOR_URL);
properties.add(CONNECTOR_TABLE_NAME);
properties.add(CONNECTOR_USERNAME);
properties.add(CONNECTOR_PASSWORD);
properties.add(CONNECTOR_SCAN... | properties.add(SCHEMA + ". | public List<String> supportedProperties() {
List<String> properties = new ArrayList<>();
properties.add(CONNECTOR_DRIVER);
properties.add(CONNECTOR_URL);
properties.add(CONNECTOR_TABLE);
properties.add(CONNECTOR_USERNAME);
properties.add(CONNECTOR_PASSWORD);
properties.add(CONNECTOR_READ_PARTITION... | class JDBCTableSourceSinkFactory implements
StreamTableSourceFactory<Row>,
StreamTableSinkFactory<Tuple2<Boolean, Row>> {
public static final String CONNECTOR_DRIVER_NAME = "connector.driver.name";
public static final String CONNECTOR_URL = "connector.url";
public static final String CONNECTOR_TABLE_NAME = "conne... | class JDBCTableSourceSinkFactory implements
StreamTableSourceFactory<Row>,
StreamTableSinkFactory<Tuple2<Boolean, Row>> {
@Override
public Map<String, String> requiredContext() {
Map<String, String> context = new HashMap<>();
context.put(CONNECTOR_TYPE, CONNECTOR_TYPE_VALUE_JDBC);
context.put(CONNECTOR_PROP... |
Got two more confirmed. Currently there's some issue with FunctionAppTest for ACA, reported to service team. Already confirmed with Vinay that the related resources has been deleted. Guess it's fine to update recordings afterwards. | private void addSanitizers() {
List<TestProxySanitizer> sanitizers = new ArrayList<>(Arrays.asList(
new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL),
new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxyS... | new TestProxySanitizer("$.properties.WEBSITE_AUTH_ENCRYPTION_KEY", null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY), | private void addSanitizers() {
List<TestProxySanitizer> sanitizers = new ArrayList<>(Arrays.asList(
new TestProxySanitizer("(?<=/subscriptions/)([^/?]+)", ZERO_UUID, TestProxySanitizerType.URL),
new TestProxySanitizer("(?<=%2Fsubscriptions%2F)([^/?]+)", ZERO_UUID, TestProxyS... | class of the manager
* @param httpPipeline the http pipeline
* @param profile the azure profile
* @param <T> the type of the manager
* @return the manager instance
* @throws RuntimeException when field cannot be found or set.
*/
protected <T> T buildManager(Class<T> manager, HttpPipeli... | class of the manager
* @param httpPipeline the http pipeline
* @param profile the azure profile
* @param <T> the type of the manager
* @return the manager instance
* @throws RuntimeException when field cannot be found or set.
*/
protected <T> T buildManager(Class<T> manager, HttpPipeli... |
Yeah verified it in Windows now, seems to be working fine. | void generateJavaBindings() throws BindgenException {
outStream.println("\nResolving maven dependencies...");
resolvePlatformLibraries();
if ((mvnGroupId != null) && (mvnArtifactId != null) && (mvnVersion != null)) {
new BindgenMvnResolver(outStream, env).... | outStream.println("\nResolving maven dependencies..."); | void generateJavaBindings() throws BindgenException {
outStream.println("\nResolving maven dependencies...");
resolvePlatformLibraries();
if ((mvnGroupId != null) && (mvnArtifactId != null) && (mvnVersion != null)) {
new BindgenMvnResolver(outStream, env).... | class BindingsGenerator {
private final BindgenEnv env;
private Path modulePath;
private Path dependenciesPath;
private Path utilsDirPath;
private String mvnGroupId;
private String mvnArtifactId;
private String mvnVersion;
private PrintStream errStream;
private PrintStream outStrea... | class BindingsGenerator {
private final BindgenEnv env;
private Path modulePath;
private Path dependenciesPath;
private Path utilsDirPath;
private String mvnGroupId;
private String mvnArtifactId;
private String mvnVersion;
private PrintStream errStream;
private PrintStream outStrea... |
+1 , i'll make that change across all the commands. | public void execute() {
if (this.helpFlag) {
String commandUsageInfo = BLauncherCmd.getCommandUsageInfo(Constants.RUN_COMMAND);
this.errStream.println(commandUsageInfo);
return;
}
if (this.argList == null || this.argList.size() == 0) {
CommandUtil... | "invalid Ballerina source path, it should either be a module name in a Ballerina project, a " + | public void execute() {
if (this.helpFlag) {
String commandUsageInfo = BLauncherCmd.getCommandUsageInfo(Constants.RUN_COMMAND);
this.errStream.println(commandUsageInfo);
return;
}
if (this.argList == null || this.argList.size() == 0) {
CommandUtil... | class RunCommand implements BLauncherCmd {
private final PrintStream outStream;
private final PrintStream errStream;
@CommandLine.Parameters(description = "Program arguments")
private List<String> argList;
@CommandLine.Option(names = {"--sourceroot"},
description = "Path to the di... | class RunCommand implements BLauncherCmd {
private final PrintStream outStream;
private final PrintStream errStream;
@CommandLine.Parameters(description = "Program arguments")
private List<String> argList;
@CommandLine.Option(names = {"--sourceroot"},
description = "Path to the di... |
> Ah! Not sure if inferring makes the code more readable here though. I can see why it is confusing - I had the type here explicitly but IDEA told me it isn't needed. Let me add it back :) | 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
} |
> Perhaps we should worry more about how many tasks can concurrently access HMS, than how often they access. Maybe we need introduce a new mechanism the source can notify the all join subtask when to update in Flink SQL | private void validateLookupConfigurations() {
String partitionInclude = configuration.get(STREAMING_SOURCE_PARTITION_INCLUDE);
if (isStreamingSource()) {
Preconditions.checkArgument(
!configuration.contains(STREAMING_SOURCE_CONSUME_START_OFFSET),
String.format(
"The '%s' is not supported when se... | "Currently the recommended value of '%s' is bigger than default value '%s' " + | private void validateLookupConfigurations() {
String partitionInclude = configuration.get(STREAMING_SOURCE_PARTITION_INCLUDE);
if (isStreamingSource()) {
Preconditions.checkArgument(
!configuration.contains(STREAMING_SOURCE_CONSUME_START_OFFSET),
String.format(
"The '%s' is not supported when se... | class HiveLookupTableSource extends HiveTableSource implements LookupTableSource {
private static final Logger LOG = LoggerFactory.getLogger(HiveLookupTableSource.class);
private static final Duration DEFAULT_LOOKUP_MONITOR_INTERVAL = Duration.ofHours(1L);
private final Configuration configuration;
private Duratio... | class HiveLookupTableSource extends HiveTableSource implements LookupTableSource {
private static final Logger LOG = LoggerFactory.getLogger(HiveLookupTableSource.class);
private static final Duration DEFAULT_LOOKUP_MONITOR_INTERVAL = Duration.ofHours(1L);
private final Configuration configuration;
private Duratio... |
Let's invert this case and just have if -> throw and everything else outside of an if/else block | private void unpackAndValidateId(String keyId) {
if (keyId != null && keyId.length() > 0) {
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.le... | if (keyId != null && keyId.length() > 0) { | private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw new IllegalArgumentException("Key Id is invalid");
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getP... | class CryptographyAsyncClient {
private JsonWebKey key;
private CryptographyService service;
private String version;
private EcKeyCryptographyClient ecKeyCryptographyClient;
private RsaKeyCryptographyClient rsaKeyCryptographyClient;
private CryptographyServiceClient cryptographyServiceClient;
... | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
private JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientL... |
I'm curious why there isn't any sort of TokenCredential or AzureSasCredential policy here. Does this service not have any sort of authentication? I can't find it in the .NET repo either | public ModelsRepositoryAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.getGlobalConfiguration().clone()... | Objects.requireNonNull(endpoint, "'endpoint' cannot be null"); | public ModelsRepositoryAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.getGlobalConfiguration().clone()... | class ModelsRepositoryClientBuilder {
private static final String MODELS_REPOSITORY_PROPERTIES = "azure-iot-modelsrepository.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final List<HttpPipelinePolicy> additionalPolic... | class ModelsRepositoryClientBuilder {
private static final String MODELS_REPOSITORY_PROPERTIES = "azure-iot-modelsrepository.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final List<HttpPipelinePolicy> additionalPolic... |
I think this will be best left for the user, as latency can change and the limit can be changed by GCP project owners. | public void processElement(ProcessContext context) {
Iterable<AnnotateImageRequest> value = context.element().getValue();
ArrayList<AnnotateImageRequest> annotateImageRequests = new ArrayList<>();
value.forEach(annotateImageRequests::add);
context.output(annotateImageRequests);
} | ArrayList<AnnotateImageRequest> annotateImageRequests = new ArrayList<>(); | public void processElement(ProcessContext context) {
context.output(getResponse(Objects.requireNonNull(context.element().getValue())));
} | class PerformImageAnnotation
extends DoFn<List<AnnotateImageRequest>, List<AnnotateImageResponse>> {
private ImageAnnotatorClient imageAnnotatorClient;
public PerformImageAnnotation() {}
/**
* Parametrized constructor to make mock injection easier in testing.
*
* @param imageAnnotato... | class PerformImageAnnotation
extends DoFn<KV<Integer, Iterable<AnnotateImageRequest>>, List<AnnotateImageResponse>> {
private transient ImageAnnotatorClient imageAnnotatorClient;
public PerformImageAnnotation() {}
/**
* Parametrized constructor to make mock injection easier in testing.
*
... |
Since the default limit is 30QPS but the latency will depend a lot on the size of the input let's be cautious, assume smaller sized input data, and use something small like 5 keys. We should make this choice clear in the documentation of the class, constructor with the default, and recommend that a user updates this to... | public void processElement(ProcessContext context) {
Iterable<AnnotateImageRequest> value = context.element().getValue();
ArrayList<AnnotateImageRequest> annotateImageRequests = new ArrayList<>();
value.forEach(annotateImageRequests::add);
context.output(annotateImageRequests);
} | ArrayList<AnnotateImageRequest> annotateImageRequests = new ArrayList<>(); | public void processElement(ProcessContext context) {
context.output(getResponse(Objects.requireNonNull(context.element().getValue())));
} | class PerformImageAnnotation
extends DoFn<List<AnnotateImageRequest>, List<AnnotateImageResponse>> {
private ImageAnnotatorClient imageAnnotatorClient;
public PerformImageAnnotation() {}
/**
* Parametrized constructor to make mock injection easier in testing.
*
* @param imageAnnotato... | class PerformImageAnnotation
extends DoFn<KV<Integer, Iterable<AnnotateImageRequest>>, List<AnnotateImageResponse>> {
private transient ImageAnnotatorClient imageAnnotatorClient;
public PerformImageAnnotation() {}
/**
* Parametrized constructor to make mock injection easier in testing.
*
... |
@fndejong OK, looks good then. We need tests though: could you try to add some integration tests in the undertow/deployment module? There are already a couple of integration tests there. You can use REST assured to test things, no need for curl. I'm also wondering if you would be interesting in writing some documentat... | public SSLContext toSSLContext() throws GeneralSecurityException, IOException {
Logger log = Logger.getLogger("io.quarkus.configuration.ssl");
final Optional<Path> certFile = certificate.file;
final Optional<Path> keyFile = certificate.keyFile;
final Optional<Path> keyStoreFile ... | new KeyStore.PasswordProtection(keystorePassword.toCharArray())); | public SSLContext toSSLContext() throws GeneralSecurityException, IOException {
Logger log = Logger.getLogger("io.quarkus.configuration.ssl");
final Optional<Path> certFile = certificate.file;
final Optional<Path> keyFile = certificate.keyFile;
final Optional<Path> keyStoreFile ... | class ServerSslConfig {
/**
* The server certificate configuration.
*/
public CertificateConfig certificate;
/**
* The cipher suites to use. If none is given, a reasonable default is selected.
*/
@ConfigItem
public Optional<CipherSuiteSelector> cipherSuites;
/**
* The ... | class ServerSslConfig {
/**
* The server certificate configuration.
*/
public CertificateConfig certificate;
/**
* The cipher suites to use. If none is given, a reasonable default is selected.
*/
@ConfigItem
public Optional<CipherSuiteSelector> cipherSuites;
/**
* The ... |
ok, done (and there goes the 2-line patch :( ) | public void requestPartitions() throws IOException, InterruptedException {
if (!requestedPartitionsFlag) {
synchronized (requestLock) {
if (isReleased) {
throw new IllegalStateException("Already released.");
}
if (numberOfInputChannels != inputChannels.size()) {
throw new IllegalStateEx... | if (!requestedPartitionsFlag) { | public void requestPartitions() throws IOException, InterruptedException {
if (requestedPartitionsFlag) {
return;
}
synchronized (requestLock) {
if (isReleased) {
throw new IllegalStateException("Already released.");
}
if (numberOfInputChannels != inputChannels.size()) {
throw new Illega... | class SingleInputGate implements InputGate {
private static final Logger LOG = LoggerFactory.getLogger(SingleInputGate.class);
/** Lock object to guard partition requests and runtime channel updates. */
private final Object requestLock = new Object();
/** The name of the owning task, for logging purposes. */
pr... | class SingleInputGate implements InputGate {
private static final Logger LOG = LoggerFactory.getLogger(SingleInputGate.class);
/** Lock object to guard partition requests and runtime channel updates. */
private final Object requestLock = new Object();
/** The name of the owning task, for logging purposes. */
pr... |
Hmm ... so should we try to set a compile version for non-java projects as well, then? Assign the controller version at the time of submission, or use the one from deployment.xml if set? | private void validateDeprecatedElements(ApplicationPackage applicationPackage) {
for (var deprecatedElement : applicationPackage.deploymentSpec().deprecatedElements()) {
if (applicationPackage.compileVersion().isEmpty()) continue;
if (deprecatedElement.majorVersion() >= applicationPackag... | if (applicationPackage.compileVersion().isEmpty()) continue; | private void validateDeprecatedElements(ApplicationPackage applicationPackage) {
int wantedMajor = applicationPackage.compileVersion().map(Version::getMajor)
.or(() -> applicationPackage.deploymentSpec().majorVersion())
.or(... | class ApplicationPackageValidator {
private final Controller controller;
private final ListFlag<String> cloudAccountsFlag;
public ApplicationPackageValidator(Controller controller) {
this.controller = Objects.requireNonNull(controller, "controller must be non-null");
this.cloudAccountsFlag... | class ApplicationPackageValidator {
private final Controller controller;
private final ListFlag<String> cloudAccountsFlag;
public ApplicationPackageValidator(Controller controller) {
this.controller = Objects.requireNonNull(controller, "controller must be non-null");
this.cloudAccountsFlag... |
Looks to me there is not need to have the process to allocate slot1, offer slot and release it. The slot offering only would be enough to add a free slot. I think we can simplify it, maybe in a separate commit. | public void testAllocateWithFreeSlot() throws Exception {
final CompletableFuture<SlotRequest> slotRequestFuture = new CompletableFuture<>();
resourceManagerGateway.setRequestSlotConsumer(slotRequestFuture::complete);
try (SlotPoolImpl slotPool = createAndSetUpSlotPool()) {
slotPool.registerTaskManager(taskMa... | slotPool.releaseSlot(requestId1, null); | public void testAllocateWithFreeSlot() throws Exception {
final CompletableFuture<SlotRequest> slotRequestFuture = new CompletableFuture<>();
resourceManagerGateway.setRequestSlotConsumer(slotRequestFuture::complete);
try (SlotPoolImpl slotPool = createAndSetUpSlotPool(resourceManagerGateway)) {
final Alloca... | class SlotPoolImplTest extends TestLogger {
private final Time timeout = Time.seconds(10L);
private JobID jobId;
private TaskManagerLocation taskManagerLocation;
private SimpleAckingTaskManagerGateway taskManagerGateway;
private TestingResourceManagerGateway resourceManagerGateway;
private ComponentMainThre... | class SlotPoolImplTest extends TestLogger {
private static final Time TIMEOUT = SlotPoolUtils.TIMEOUT;
private TaskManagerLocation taskManagerLocation;
private SimpleAckingTaskManagerGateway taskManagerGateway;
private TestingResourceManagerGateway resourceManagerGateway;
private static final ComponentMainThr... |
It's better to just let the `SecretNotFoundException` be thrown as it's more descriptive than `orElseThrow()`. | private static TlsCredentials latestValidCredentials(SecretStore secretStore, TlsConfig tlsConfig) {
int version = latestVersionInSecretStore(secretStore, tlsConfig).orElseThrow();
return new TlsCredentials(certificates(secretStore, tlsConfig, version), privateKey(secretStore, tlsConfig, version));
... | int version = latestVersionInSecretStore(secretStore, tlsConfig).orElseThrow(); | private static TlsCredentials latestValidCredentials(SecretStore secretStore, TlsConfig tlsConfig) {
int version = latestVersionInSecretStore(secretStore, tlsConfig);
return new TlsCredentials(certificates(secretStore, tlsConfig, version), privateKey(secretStore, tlsConfig, version));
} | class ControllerSslContextFactoryProvider extends TlsContextBasedProvider {
private final KeyStore truststore;
private final KeyStore keystore;
private final Map<Integer, TlsContext> tlsContextMap = new ConcurrentHashMap<>();
@Inject
public ControllerSslContextFactoryProvider(SecretStore secretSto... | class ControllerSslContextFactoryProvider extends TlsContextBasedProvider {
private final KeyStore truststore;
private final KeyStore keystore;
private final Map<Integer, TlsContext> tlsContextMap = new ConcurrentHashMap<>();
@Inject
public ControllerSslContextFactoryProvider(SecretStore secretSto... |
Possibly double that as we do prepare, then prepareWithLocks. | public boolean canAllocateTenantNodeTo(Node host, boolean dynamicProvisioning) {
if ( ! host.type().canRun(NodeType.tenant)) return false;
if (host.status().wantToRetire()) return false;
if (host.allocation().map(alloc -> alloc.membership().retired()).orElse(false)) return false;
if (sus... | if (suspended(host)) return false; | public boolean canAllocateTenantNodeTo(Node host, boolean dynamicProvisioning) {
if ( ! host.type().canRun(NodeType.tenant)) return false;
if (host.status().wantToRetire()) return false;
if (host.allocation().map(alloc -> alloc.membership().retired()).orElse(false)) return false;
if (sus... | class Nodes {
private static final Logger log = Logger.getLogger(Nodes.class.getName());
private final CuratorDatabaseClient db;
private final Zone zone;
private final Clock clock;
private final Orchestrator orchestrator;
public Nodes(CuratorDatabaseClient db, Zone zone, Clock clock, Orchestr... | class Nodes {
private static final Logger log = Logger.getLogger(Nodes.class.getName());
private final CuratorDatabaseClient db;
private final Zone zone;
private final Clock clock;
private final Orchestrator orchestrator;
public Nodes(CuratorDatabaseClient db, Zone zone, Clock clock, Orchestr... |
instead of `break`, can we return `value` here? I think it will make things more clear. We can add a `else` block at the end, and just return `value` from else condition. | static Object getValue(JsonNode value) {
if (value.isValueNode()) {
switch (value.getNodeType()) {
case BOOLEAN:
return value.asBoolean();
case NUMBER:
if (value.isInt()) {
return value.asInt();
... | break; | static Object getValue(JsonNode value) {
if (value.isValueNode()) {
switch (value.getNodeType()) {
case BOOLEAN:
return value.asBoolean();
case NUMBER:
if (value.isInt()) {
return value.asInt();
... | class JsonSerializable {
private static final ObjectMapper OBJECT_MAPPER = Utils.getSimpleObjectMapper();
private final static Logger logger = LoggerFactory.getLogger(JsonSerializable.class);
transient ObjectNode propertyBag = null;
private ObjectMapper om;
protected JsonSerializable() {
th... | class JsonSerializable {
private static final ObjectMapper OBJECT_MAPPER = Utils.getSimpleObjectMapper();
private final static Logger logger = LoggerFactory.getLogger(JsonSerializable.class);
transient ObjectNode propertyBag = null;
private ObjectMapper om;
protected JsonSerializable() {
th... |
Revert this part back to line 144. It will minimize changes. | public boolean start() throws IOException {
final int defaultPartitionInitTimeout = 60 * 1000;
final int kafkaRequestTimeoutMultiple = 2;
Read<K, V> spec = source.getSpec();
consumer = spec.getConsumerFactoryFn().apply(spec.getConsumerConfig());
consumerSpEL.evaluateAssign(consumer, spec.getTopicPa... | Object groupId = spec.getConsumerConfig().get(ConsumerConfig.GROUP_ID_CONFIG); | public boolean start() throws IOException {
final int defaultPartitionInitTimeout = 60 * 1000;
final int kafkaRequestTimeoutMultiple = 2;
Read<K, V> spec = source.getSpec();
consumer = spec.getConsumerFactoryFn().apply(spec.getConsumerConfig());
consumerSpEL.evaluateAssign(consumer, spec.getTopicPa... | class KafkaUnboundedReader<K, V> extends UnboundedReader<KafkaRecord<K, V>> {
@SuppressWarnings("FutureReturnValueIgnored")
@Override
@Override
public boolean advance() throws IOException {
/* Read first record (if any). we need to loop here because :
* - (a) some records initially need to be ... | class KafkaUnboundedReader<K, V> extends UnboundedReader<KafkaRecord<K, V>> {
@SuppressWarnings("FutureReturnValueIgnored")
@Override
@Override
public boolean advance() throws IOException {
/* Read first record (if any). we need to loop here because :
* - (a) some records initially need to be ... |
Unrelated but useful: always move away "unlikely" paths ie cold ones out of the "main" method logic: it would increase chances to inline it (see http://normanmaurer.me/blog_in_progress/2013/11/07/Inline-all-the-Things/ that's still very actual and these things hasn't changed across JDK versions, really). Most inlining ... | public void activate(ContextState initialState) {
if (LOG.isTraceEnabled()) {
String stack = Arrays.stream(Thread.currentThread().getStackTrace())
.skip(2)
.limit(7)
.map(se -> "\n\t" + se.toString())
.collect(Collectors... | String stack = Arrays.stream(Thread.currentThread().getStackTrace()) | public void activate(ContextState initialState) {
if (LOG.isTraceEnabled()) {
String stack = Arrays.stream(Thread.currentThread().getStackTrace())
.skip(2)
.limit(7)
.map(se -> "\n\t" + se.toString())
.collect(Collectors... | class RequestContext implements ManagedContext {
private static final Logger LOG = Logger.getLogger("io.quarkus.arc.requestContext");
private final CurrentContext<RequestContextState> currentContext;
private final LazyValue<Notifier<Object>> initializedNotifier;
private final LazyValue<Notifier<Objec... | class RequestContext implements ManagedContext {
private static final Logger LOG = Logger.getLogger("io.quarkus.arc.requestContext");
private final CurrentContext<RequestContextState> currentContext;
private final LazyValue<Notifier<Object>> initializedNotifier;
private final LazyValue<Notifier<Objec... |
Isn't it better if we move this logic to the function definition node's overridden method itself? As the return type of a function represents the particular function, I feel that this logic does not belong here. | public void visit(ReturnStatementNode returnStatementNode) {
this.semanticModel.typeOf(returnStatementNode).ifPresent(this::checkAndSetTypeResult);
if (resultFound) {
return;
}
returnStatementNode.parent().accept(this);
if (resultFound && returnTypeSymbol.ty... | functionTypeSymbol.returnTypeDescriptor().ifPresentOrElse(this::checkAndSetTypeResult, this::resetResult); | public void visit(ReturnStatementNode returnStatementNode) {
this.semanticModel.typeOf(returnStatementNode).ifPresent(this::checkAndSetTypeResult);
if (resultFound) {
return;
}
returnStatementNode.parent().accept(this);
if (resultFound && returnTypeSymbol.ty... | class FunctionCallExpressionTypeFinder extends NodeVisitor {
private final SemanticModel semanticModel;
private TypeSymbol returnTypeSymbol;
private TypeDescKind returnTypeDescKind;
private boolean resultFound = false;
public FunctionCallExpressionTypeFinder(SemanticModel semanticModel) {
... | class FunctionCallExpressionTypeFinder extends NodeVisitor {
private final SemanticModel semanticModel;
private TypeSymbol returnTypeSymbol;
private TypeDescKind returnTypeDescKind;
private boolean resultFound = false;
public FunctionCallExpressionTypeFinder(SemanticModel semanticModel) {
... |
I think this block should be the `finally` block of the `try { test.run() } finally { ... }` | protected void runTest(RunnableWithException test) {
Throwable testFailure = null;
try {
test.run();
} catch (Throwable t) {
testFailure = t;
}
try {
Deadline deadline = Deadline.now().plus(Duration.ofSeconds(10));
boolean isAnyJobRunning = yarnClient.getApplications().stream()
.anyMatch(Yar... | try { | protected void runTest(RunnableWithException test) throws Exception {
try (final CleanupYarnApplication ignored = new CleanupYarnApplication()) {
test.run();
}
} | class YarnTestBase extends TestLogger {
private static final Logger LOG = LoggerFactory.getLogger(YarnTestBase.class);
protected static final PrintStream ORIGINAL_STDOUT = System.out;
protected static final PrintStream ORIGINAL_STDERR = System.err;
private static final InputStream ORIGINAL_STDIN = System.in;
pro... | class YarnTestBase extends TestLogger {
private static final Logger LOG = LoggerFactory.getLogger(YarnTestBase.class);
protected static final PrintStream ORIGINAL_STDOUT = System.out;
protected static final PrintStream ORIGINAL_STDERR = System.err;
private static final InputStream ORIGINAL_STDIN = System.in;
pro... |
Can we add some documentation to type desc as an expression | private boolean isServiceDeclStart(ParserRuleContext currentContext, int lookahead) {
switch (peek(lookahead + 1).kind) {
case IDENTIFIER_TOKEN:
SyntaxKind tokenAfterIdentifier = peek(lookahead + 2).kind;
switch (tokenAfterIdentifier) {
ca... | private boolean isSimpleTypeInExpression(SyntaxKind nodeKind) { | 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... |
Is this time out for PLAYBACK only, or time out for both? If PLAYBACK only, use `@DoNotRecord(skipInPlayback = true)` (`@LiveOnly` won't run in record mode) | public void canCreateVirtualMachineWithLMSIAndEMSI() {
rgName = generateRandomResourceName("java-emsi-c-rg", 15);
String identityName1 = generateRandomResourceName("msi-id", 15);
String networkName = generateRandomResourceName("nw", 10);
ResourceGroup resource... | public void canCreateVirtualMachineWithLMSIAndEMSI() {
rgName = generateRandomResourceName("java-emsi-c-rg", 15);
String identityName1 = generateRandomResourceName("msi-id", 15);
String networkName = generateRandomResourceName("nw", 10);
ResourceGroup resource... | class VirtualMachineEMSILMSIOperationsTests extends ComputeManagementTest {
private String rgName = "";
private Region region = Region.US_WEST_CENTRAL;
private final String vmName = "javavm";
@Override
protected void cleanUpResources() {
this.resourceManager.resourceGroups().beginDelet... | class VirtualMachineEMSILMSIOperationsTests extends ComputeManagementTest {
private String rgName = "";
private Region region = Region.US_WEST2;
private final String vmName = "javavm";
@Override
protected void cleanUpResources() {
this.resourceManager.resourceGroups().beginDeleteByName... | |
Replace `System.out` with log statement | InstanceIdentity sendInstanceRegisterRequest(InstanceRegisterInformation instanceRegisterInformation, String athenzUrl) {
try(CloseableHttpClient client = HttpClientBuilder.create().build()) {
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsStr... | System.out.println(objectMapper.writeValueAsString(instanceRegisterInformation)); | InstanceIdentity sendInstanceRegisterRequest(InstanceRegisterInformation instanceRegisterInformation, String athenzUrl) {
try(CloseableHttpClient client = HttpClientBuilder.create().build()) {
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsStr... | class AthenzService {
/**
* Send instance register request to ZTS, get InstanceIdentity
*
* @param instanceRegisterInformation
*/
} | class AthenzService {
/**
* Send instance register request to ZTS, get InstanceIdentity
*
* @param instanceRegisterInformation
*/
} |
Extracting `0` to channelId would make the test a bit more readable. | public void testSnapshotAfterEndOfPartition() throws Exception {
VerifyRecordsDataOutput<Long> output = new VerifyRecordsDataOutput<>();
LongSerializer inSerializer = LongSerializer.INSTANCE;
int numInputChannels = 1;
StreamTestSingleInputGate<Long> inputGate = new StreamTestSingleInputGate<>(numInputChannels, ... | assertNull(deserializers[0]); | public void testSnapshotAfterEndOfPartition() throws Exception {
int numInputChannels = 1;
int channelId = 0;
int checkpointId = 0;
VerifyRecordsDataOutput<Long> output = new VerifyRecordsDataOutput<>();
LongSerializer inSerializer = LongSerializer.INSTANCE;
StreamTestSingleInputGate<Long> inputGate = new ... | class StreamTaskNetworkInputTest {
private static final int PAGE_SIZE = 1000;
private final IOManager ioManager = new IOManagerAsync();
@After
public void tearDown() throws Exception {
ioManager.close();
}
@Test
public void testIsAvailableWithBufferedDataInDeserializer() throws Exception {
List<BufferOrE... | class StreamTaskNetworkInputTest {
private static final int PAGE_SIZE = 1000;
private final IOManager ioManager = new IOManagerAsync();
@After
public void tearDown() throws Exception {
ioManager.close();
}
@Test
public void testIsAvailableWithBufferedDataInDeserializer() throws Exception {
List<BufferOrE... |
Inverted. I left it out initially since 2 vs 3 lines of code doesn't matter that much and I was just moving this code and too many modifications while moving the code can also be confusing :) | private Optional<BufferOrEvent> handleEmptyBuffer() throws Exception {
if (!inputGate.isFinished()) {
return Optional.empty();
}
if (!endOfStream) {
endOfStream = true;
releaseBlocksAndResetBarriers();
return pollNext();
}
else {
isFinished = true;
return Optional.empty();
}
} | if (!endOfStream) { | private Optional<BufferOrEvent> handleEmptyBuffer() throws Exception {
if (!inputGate.isFinished()) {
return Optional.empty();
}
if (endOfStream) {
isFinished = true;
return Optional.empty();
} else {
endOfStream = true;
releaseBlocksAndResetBarriers();
return pollNext();
}
} | class BarrierBuffer implements CheckpointBarrierHandler {
private static final Logger LOG = LoggerFactory.getLogger(BarrierBuffer.class);
/** The gate that the buffer draws its input from. */
private final InputGate inputGate;
/** Flags that indicate whether a channel is currently blocked/buffered. */
private f... | class BarrierBuffer implements CheckpointBarrierHandler {
private static final Logger LOG = LoggerFactory.getLogger(BarrierBuffer.class);
/** The gate that the buffer draws its input from. */
private final InputGate inputGate;
/** Flags that indicate whether a channel is currently blocked/buffered. */
private f... |
dont we need orgname and modulename here? | private static CompileResult compileOnJBallerina(String sourceFilePath) {
Path sourcePath = Paths.get(sourceFilePath);
String packageName = sourcePath.getFileName().toString();
Path sourceRoot = resourceDir.resolve(sourcePath.getParent());
CompilerContext context = new CompilerContext()... | String funcName = "__init_"; | private static CompileResult compileOnJBallerina(String sourceFilePath) {
Path sourcePath = Paths.get(sourceFilePath);
String packageName = sourcePath.getFileName().toString();
Path sourceRoot = resourceDir.resolve(sourcePath.getParent());
CompilerContext context = new CompilerContext()... | class BCompileUtil {
private static Path resourceDir = Paths.get("src/test/resources").toAbsolutePath();
private static final JBallerinaInMemoryClassLoader classLoader = new JBallerinaInMemoryClassLoader();
/**
* Compile and return the semantic errors. Error scenarios cannot use this method.
*
... | class BCompileUtil {
private static Path resourceDir = Paths.get("src/test/resources").toAbsolutePath();
private static final String MODULE_INIT_SUFFIX = "__init_";
/**
* Compile and return the semantic errors. Error scenarios cannot use this method.
*
* @param sourceFilePath Path to source... |
can array_generate accept only one argument? if not so, node.getChildren().size() < 2 | public Void visitFunctionCall(FunctionCallExpr node, Scope scope) {
Type[] argumentTypes = node.getChildren().stream().map(Expr::getType).toArray(Type[]::new);
if (node.isNondeterministicBuiltinFnName()) {
ExprId exprId = analyzeState.getNextNondeterministicId();
... | if (node.getChildren().size() < 1 || node.getChildren().size() > 3) { | public Void visitFunctionCall(FunctionCallExpr node, Scope scope) {
Type[] argumentTypes = node.getChildren().stream().map(Expr::getType).toArray(Type[]::new);
if (node.isNondeterministicBuiltinFnName()) {
ExprId exprId = analyzeState.getNextNondeterministicId();
... | class Visitor extends AstVisitor<Void, Scope> {
private static final List<String> ADD_DATE_FUNCTIONS = Lists.newArrayList(FunctionSet.DATE_ADD,
FunctionSet.ADDDATE, FunctionSet.DAYS_ADD, FunctionSet.TIMESTAMPADD);
private static final List<String> SUB_DATE_FUNCTIONS =
Lis... | class Visitor extends AstVisitor<Void, Scope> {
private static final List<String> ADD_DATE_FUNCTIONS = Lists.newArrayList(FunctionSet.DATE_ADD,
FunctionSet.ADDDATE, FunctionSet.DAYS_ADD, FunctionSet.TIMESTAMPADD);
private static final List<String> SUB_DATE_FUNCTIONS =
Lis... |
Oh, I see, sorry I thought it's part of the generated code | public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) {
if (identifier == null) {
return null;
}
assertSingleType(identifier);
String rawId = identifier.getRawId();
CommunicationIdentifierModelKind kind = identifier.getKind();
... | CommunicationIdentifierModelKind kind = identifier.getKind(); | public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) {
if (identifier == null) {
return null;
}
assertSingleType(identifier);
String rawId = identifier.getRawId();
CommunicationIdentifierModelKind kind = (identifier.getKind() != null... | class CommunicationIdentifierConverter {
/**
* Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}.
*/
/**
* Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}.
*/
public static CommunicationIdentifierModel convert(Commu... | class CommunicationIdentifierConverter {
/**
* Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}.
*/
/**
* Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}.
*/
public static CommunicationIdentifierModel convert(Commu... |
But you're sure that all the response handlers we added earlier are always executed on the right thread at the right time? That's what gets me a bit worried. Note that I have no idea how this all works so I'm asking naive questions. | public void handle(final RoutingContext ctx) {
ctx.response()
.endHandler(currentManagedContextTerminationHandler)
.exceptionHandler(currentManagedContextTerminationHandler)
.closeHandler(currentManagedContextTerminationHandler);
if (!currentManagedContex... | currentManagedContext.deactivate(); | public void handle(final RoutingContext ctx) {
ctx.response()
.endHandler(currentManagedContextTerminationHandler)
.exceptionHandler(currentManagedContextTerminationHandler)
.closeHandler(currentManagedContextTerminationHandler);
if (!currentManagedContex... | class SmallRyeGraphQLAbstractHandler implements Handler<RoutingContext> {
private final CurrentIdentityAssociation currentIdentityAssociation;
private final CurrentVertxRequest currentVertxRequest;
private final ManagedContext currentManagedContext;
private final Handler currentManagedContextTerminatio... | class SmallRyeGraphQLAbstractHandler implements Handler<RoutingContext> {
private final CurrentIdentityAssociation currentIdentityAssociation;
private final CurrentVertxRequest currentVertxRequest;
private final ManagedContext currentManagedContext;
private final Handler currentManagedContextTerminatio... |
```suggestion new String[] {"info name", "info value"}, ``` | public TableResultInternal execute(Context ctx) {
CatalogDescriptor catalogDescriptor =
ctx.getCatalogManager()
.getCatalogDescriptor(catalogName)
.orElseThrow(
() ->
new Valid... | Arrays.asList("info name", "info value").toArray(new String[0]), | public TableResultInternal execute(Context ctx) {
CatalogDescriptor catalogDescriptor =
ctx.getCatalogManager()
.getCatalogDescriptor(catalogName)
.orElseThrow(
() ->
new Valid... | class DescribeCatalogOperation implements Operation, ExecutableOperation {
private final String catalogName;
private final boolean isExtended;
public DescribeCatalogOperation(String catalogName, boolean isExtended) {
this.catalogName = catalogName;
this.isExtended = isExtended;
}
... | class DescribeCatalogOperation implements Operation, ExecutableOperation {
private final String catalogName;
private final boolean isExtended;
public DescribeCatalogOperation(String catalogName, boolean isExtended) {
this.catalogName = catalogName;
this.isExtended = isExtended;
}
... |
good to narrow down exception ! thanks | public boolean start() throws IOException {
restClient = source.spec.getConnectionConfiguration().createClient();
String query = source.spec.getQuery();
if (query == null) {
query = "{\"query\": { \"match_all\": {} }}";
}
if (source.backendVersion == 5 && source.numSlices != null ... | return backendVersion; | public boolean start() throws IOException {
restClient = source.spec.getConnectionConfiguration().createClient();
String query = source.spec.getQuery();
if (query == null) {
query = "{\"query\": { \"match_all\": {} }}";
}
if (source.backendVersion == 5 && source.numSlices != null ... | class BoundedElasticsearchReader extends BoundedSource.BoundedReader<String> {
private final BoundedElasticsearchSource source;
private RestClient restClient;
private String current;
private String scrollId;
private ListIterator<String> batchIterator;
private BoundedElasticsearchReader(Bounde... | class BoundedElasticsearchReader extends BoundedSource.BoundedReader<String> {
private final BoundedElasticsearchSource source;
private RestClient restClient;
private String current;
private String scrollId;
private ListIterator<String> batchIterator;
private BoundedElasticsearchReader(Bounde... |
I agree that current implementation might be safer but seems like it significantly limits the usability of RestrictionTrackers as well. I think source authors are advanced users. So it might be OK to stay in the side of usability in some cases over safety. But this is debatable. Another option might be to add a method... | public void makeProgress() throws Exception {
progress += approximateRecordSize;
if (progress > totalWork) {
throw new IOException("Making progress out of range");
}
} | progress += approximateRecordSize; | public void makeProgress() throws Exception {
progress += approximateRecordSize;
if (progress > totalWork) {
throw new IOException("Making progress out of range");
}
} | class BlockTracker extends OffsetRangeTracker {
private long totalWork;
private long progress;
private long approximateRecordSize;
public BlockTracker(OffsetRange range, long totalByteSize, long recordCount) {
super(range);
if (recordCount != 0) {
this.approximateRecor... | class BlockTracker extends OffsetRangeTracker {
private long totalWork;
private long progress;
private long approximateRecordSize;
public BlockTracker(OffsetRange range, long totalByteSize, long recordCount) {
super(range);
if (recordCount != 0) {
this.approximateRecor... |
```suggestion throw ErrorCreator.createError(StringUtils.fromString("ballerina: error occurred while waiting for " + ``` This might be better | public void stop() {
if (!moduleInitialized) {
throw ErrorHelper.getRuntimeException(ErrorCodes.INVALID_FUNCTION_INVOCATION_BEFORE_MODULE_INIT, "stop");
}
if (moduleStopped) {
throw ErrorHelper.getRuntimeException(ErrorCodes.FUNCTION_ALREADY_CALLED, "stop");
}
... | throw ErrorCreator.createError(StringUtils.fromString("ballerina: error occurred in while waiting for " + | public void stop() {
if (!moduleInitialized) {
throw ErrorHelper.getRuntimeException(ErrorCodes.INVALID_FUNCTION_INVOCATION_BEFORE_MODULE_INIT, "stop");
}
if (moduleStopped) {
throw ErrorHelper.getRuntimeException(ErrorCodes.FUNCTION_ALREADY_CALLED, "stop");
}
... | class BalRuntime extends Runtime {
private final Scheduler scheduler;
private final Module module;
private boolean moduleInitialized = false;
private boolean moduleStarted = false;
private boolean moduleStopped = false;
private Thread schedulerThread = null;
public BalRuntime(Scheduler sch... | class BalRuntime extends Runtime {
private final Scheduler scheduler;
private final Module module;
private boolean moduleInitialized = false;
private boolean moduleStarted = false;
private boolean moduleStopped = false;
private Thread schedulerThread = null;
public BalRuntime(Scheduler sch... |
That should be in `KeycloakRealmResourceManager` ? I see, please introduce a dedicated client id, same as I did for the jwt. though it has not been merget yet :-) | public void testRPInitiatedLogout() throws IOException, InterruptedException {
Keycloak keycloak = KeycloakRealmResourceManager.createKeycloakClient();
RealmResource realm = keycloak.realm(KeycloakRealmResourceManager.KEYCLOAK_REALM);
RealmRepresentation representation = realm
.... | Keycloak keycloak = KeycloakRealmResourceManager.createKeycloakClient(); | public void testRPInitiatedLogout() throws IOException {
try (final WebClient webClient = createWebClient()) {
HtmlPage page = webClient.getPage("http:
assertEquals("Log in to logout-realm", page.getTitleText());
HtmlForm loginForm = page.getForms().get(0);
loginF... | class CodeFlowTest {
@Test
public void testCodeFlowNoConsent() throws IOException {
try (final WebClient webClient = createWebClient()) {
webClient.getOptions().setRedirectEnabled(false);
WebResponse webResponse = webClient
.loadWebResponse(new WebRequest(URI... | class CodeFlowTest {
@Test
public void testCodeFlowNoConsent() throws IOException {
try (final WebClient webClient = createWebClient()) {
webClient.getOptions().setRedirectEnabled(false);
WebResponse webResponse = webClient
.loadWebResponse(new WebRequest(URI... |
What is the argument for changing the default approach for a more knob based one ? Maybe is better to preserve the default and only overwrite it if this is parametrized. | public Partition[] getPartitions() {
try {
List<? extends Source<T>> partitionedSources = source.split(bundleSize, options.get());
Partition[] partitions = new SourcePartition[partitionedSources.size()];
for (int i = 0; i < partitionedSources.size(); i++) {
partitions[i] = new So... | List<? extends Source<T>> partitionedSources = source.split(bundleSize, options.get()); | public Partition[] getPartitions() {
try {
List<? extends Source<T>> partitionedSources;
if (bundleSize > 0) {
partitionedSources = source.split(bundleSize, options.get());
} else {
long desiredSizeBytes = DEFAULT_BUNDLE_SIZE;
try {
desiredSizeByte... | class Bounded<T> extends RDD<WindowedValue<T>> {
private static final Logger LOG = LoggerFactory.getLogger(SourceRDD.Bounded.class);
private final BoundedSource<T> source;
private final SerializablePipelineOptions options;
private final long bundleSize;
private final String stepName;
private fi... | class Bounded<T> extends RDD<WindowedValue<T>> {
private static final Logger LOG = LoggerFactory.getLogger(SourceRDD.Bounded.class);
private final BoundedSource<T> source;
private final SerializablePipelineOptions options;
private final int numPartitions;
private final long bundleSize;
private ... |
Perspectives: 1. Bug risks: - In the revised code, there are no apparent bug risks. 2. Naming: - The method `getPartitionKeysByValue` can be renamed to something more descriptive, such as `fetchPartitionsByValues`. 3. Code style and best practices: - The import statements at the top of the file could be org... | public Partition getPartition(String dbName, String tblName, List<String> partitionValues) {
StorageDescriptor sd;
Map<String, String> params;
if (partitionValues.size() > 0) {
org.apache.hadoop.hive.metastore.api.Partition partition =
client.getPartition(dbName, ... | Map<String, String> params; | public Partition getPartition(String dbName, String tblName, List<String> partitionValues) {
StorageDescriptor sd;
Map<String, String> params;
if (partitionValues.size() > 0) {
org.apache.hadoop.hive.metastore.api.Partition partition =
client.getPartition(dbName, ... | class HiveMetastore implements IHiveMetastore {
private static final Logger LOG = LogManager.getLogger(CachingHiveMetastore.class);
private final HiveMetaClient client;
private final String catalogName;
public HiveMetastore(HiveMetaClient client, String catalogName) {
this.client = client;
... | class HiveMetastore implements IHiveMetastore {
private static final Logger LOG = LogManager.getLogger(CachingHiveMetastore.class);
private final HiveMetaClient client;
private final String catalogName;
private final MetastoreType metastoreType;
public HiveMetastore(HiveMetaClient client, String c... |
@tiagobento could you please explain this one. `ignoreAvailability` is `true`. Is it availability of artifacts that should be ignored? | public void testValidTailFromRemoteIgnoringAvailabilityViaSystemPropBlank() throws Exception {
setSystemProp("maven.repo.local.tail.ignoreAvailability", " ");
final BootstrapMavenContext mvn = bootstrapMavenContextForProject("workspace-with-local-repo-tail",
BootstrapMavenContext.config... | assertNotNull(resolveOrgAcmeFooJar001(mvn)); | public void testValidTailFromRemoteIgnoringAvailabilityViaSystemPropBlank() throws Exception {
setSystemProp("maven.repo.local.tail.ignoreAvailability", " ");
final BootstrapMavenContext mvn = bootstrapMavenContextForProject("workspace-with-local-repo-tail",
BootstrapMavenContext.config... | class ChainedLocalRepositoryManagerTest extends BootstrapMavenContextTestBase {
private static final String M2_LOCAL_1;
private static final String M2_LOCAL_2;
private static final String M2_FROM_REMOTE;
static {
final String projectLocation;
try {
projectLocation = getProj... | class ChainedLocalRepositoryManagerTest extends BootstrapMavenContextTestBase {
private static final String M2_LOCAL_1;
private static final String M2_LOCAL_2;
private static final String M2_FROM_REMOTE;
static {
final String projectLocation;
try {
projectLocation = getProj... |
missing a check for it failing if only the port is set. | public void testConnectToPushGatewayThrowsExceptionWithoutHostInformation() {
PrometheusPushGatewayReporterFactory factory = new PrometheusPushGatewayReporterFactory();
MetricConfig metricConfig = new MetricConfig();
Assert.assertThrows(
IllegalArgumentException.class, () -> fact... | IllegalArgumentException.class, () -> factory.createMetricReporter(metricConfig)); | public void testConnectToPushGatewayThrowsExceptionWithoutHostInformation() {
PrometheusPushGatewayReporterFactory factory = new PrometheusPushGatewayReporterFactory();
MetricConfig metricConfig = new MetricConfig();
Assert.assertThrows(
IllegalArgumentException.class, () -> fact... | class PrometheusPushGatewayReporterTest extends TestLogger {
@Test
public void testParseGroupingKey() {
Map<String, String> groupingKey =
PrometheusPushGatewayReporterFactory.parseGroupingKey("k1=v1;k2=v2");
Assert.assertNotNull(groupingKey);
Assert.assertEquals("v1", gr... | class PrometheusPushGatewayReporterTest extends TestLogger {
@Test
public void testParseGroupingKey() {
Map<String, String> groupingKey =
PrometheusPushGatewayReporterFactory.parseGroupingKey("k1=v1;k2=v2");
Assert.assertNotNull(groupingKey);
Assert.assertEquals("v1", gr... |
I added more test, and discover a missing check so worth it ;) | private void testRange(PanacheQuery<Person> query) {
List<Person> persons = query.range(0, 2).list();
Assertions.assertEquals(3, persons.size());
Assertions.assertEquals("stef0", persons.get(0).name);
Assertions.assertEquals("stef1", persons.get(1).name);
Assertions.assertEquals(... | query.range(0, 2).nextPage(); | private void testRange(PanacheQuery<Person> query) {
List<Person> persons = query.range(0, 2).list();
Assertions.assertEquals(3, persons.size());
Assertions.assertEquals("stef0", persons.get(0).name);
Assertions.assertEquals("stef1", persons.get(1).name);
Assertions.assertEquals(... | class TestEndpoint {
@GET
@Path("model")
@Transactional
public String testModel() {
List<Person> persons = Person.findAll().list();
Assertions.assertEquals(0, persons.size());
persons = Person.listAll();
Assertions.assertEquals(0, persons.size());
Stream<Person... | class TestEndpoint {
@GET
@Path("model")
@Transactional
public String testModel() {
List<Person> persons = Person.findAll().list();
Assertions.assertEquals(0, persons.size());
persons = Person.listAll();
Assertions.assertEquals(0, persons.size());
Stream<Person... |
I am a little confused, should the concept consistent no matter it is a shared nothing mode or shared data mode. so what's the following three concepts mapping to filestore? * volume id -> uuid * svKey -> ?? * svName -> ?? | public static void beforeClass() throws Exception {
UtFrameUtils.createMinStarRocksCluster();
connectContext = UtFrameUtils.createDefaultCtx();
String createDbStmtStr = "create database test;";
String createTableStr = "create table test.tbl1(d1 date, k1 int, k2 bigint)... | public StorageVolume getStorageVolumeByName(String svKey) throws AnalysisException { | public static void beforeClass() throws Exception {
UtFrameUtils.createMinStarRocksCluster();
connectContext = UtFrameUtils.createDefaultCtx();
String createDbStmtStr = "create database test;";
String createTableStr = "create table test.tbl1(d1 date, k1 int, k2 bigint)... | class DropPartitionTest {
private static ConnectContext connectContext;
@BeforeClass
private static void createDb(String sql) throws Exception {
CreateDbStmt createDbStmt = (CreateDbStmt) UtFrameUtils.parseStmtWithNewParser(sql, connectContext);
GlobalStateMgr.getCurrentState().getMet... | class DropPartitionTest {
private static ConnectContext connectContext;
@BeforeClass
private static void createDb(String sql) throws Exception {
CreateDbStmt createDbStmt = (CreateDbStmt) UtFrameUtils.parseStmtWithNewParser(sql, connectContext);
GlobalStateMgr.getCurrentState().getMet... |
I agree. I think we can change the error msg like: ``` data cannot be inserted into table with emtpy partition... Use `SHOW PARTITIONS FROM tbl` to see the currenty partitions of this table. ``` And also change the msg in error code `ERR_EMPTY_PARTITION_IN_TABLE` | private List<Long> getAllPartitionIds() throws LoadException, MetaNotFoundException {
Set<Long> partitionIds = Sets.newHashSet();
for (BrokerFileGroup brokerFileGroup : fileGroups) {
if (brokerFileGroup.getPartitionIds() != null) {
partitionIds.addAll(brokerFileGroup.getParti... | throw new LoadException("data cannot be inserted into table with emtpy partition. " + | private List<Long> getAllPartitionIds() throws LoadException, MetaNotFoundException {
Set<Long> partitionIds = Sets.newHashSet();
for (BrokerFileGroup brokerFileGroup : fileGroups) {
if (brokerFileGroup.getPartitionIds() != null) {
partitionIds.addAll(brokerFileGroup.getParti... | class LoadingTaskPlanner {
private static final Logger LOG = LogManager.getLogger(LoadingTaskPlanner.class);
private final long loadJobId;
private final long txnId;
private final long dbId;
private final OlapTable table;
private final BrokerDesc brokerDesc;
private final List<BrokerFil... | class LoadingTaskPlanner {
private static final Logger LOG = LogManager.getLogger(LoadingTaskPlanner.class);
private final long loadJobId;
private final long txnId;
private final long dbId;
private final OlapTable table;
private final BrokerDesc brokerDesc;
private final List<BrokerFil... |
The request will likely fail (usually nothing is running on 8080), but the result is ignored, so it won't affect the test. | public void testInterruptsNotCached() throws Exception {
ConnectionID connectionId = new ConnectionID(new InetSocketAddress(InetAddress.getLocalHost(), 8080), 0);
AwaitingNettyClient nettyClient = new AwaitingNettyClient();
PartitionRequestClientFactory factory = new PartitionRequestClientFactory(nettyClient, 0);... | ConnectionID connectionId = new ConnectionID(new InetSocketAddress(InetAddress.getLocalHost(), 8080), 0); | public void testInterruptsNotCached() throws Exception {
ConnectionID connectionId = new ConnectionID(new InetSocketAddress(InetAddress.getLocalHost(), 8080), 0);
try (AwaitingNettyClient nettyClient = new AwaitingNettyClient()) {
PartitionRequestClientFactory factory = new PartitionRequestClientFactory(nettyCli... | class PartitionRequestClientFactoryTest {
private static final int SERVER_PORT = NetUtils.getAvailablePort();
@Test
private void connectAndInterrupt(PartitionRequestClientFactory factory, ConnectionID connectionId) throws Exception {
CompletableFuture<Void> started = new CompletableFuture<>();
CompletableFu... | class PartitionRequestClientFactoryTest {
private static final int SERVER_PORT = NetUtils.getAvailablePort();
@Test
private void connectAndInterrupt(PartitionRequestClientFactory factory, ConnectionID connectionId) throws Exception {
CompletableFuture<Void> started = new CompletableFuture<>();
CompletableFu... |
Unfortunately, we cannot directly obtain the information about whether slot desc is nullable or not from Expr. | public TupleDescriptor createTupleDescriptor(Analyzer analyzer) throws AnalysisException {
int numColLabels = getColLabels().size();
Preconditions.checkState(numColLabels > 0);
Set<String> columnSet = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
List<Column> columnList = List... | columnList.add(new Column(colAlias, selectItemExpr.getType().getPrimitiveType(), true)); | public TupleDescriptor createTupleDescriptor(Analyzer analyzer) throws AnalysisException {
int numColLabels = getColLabels().size();
Preconditions.checkState(numColLabels > 0);
Set<String> columnSet = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
List<Column> columnList = List... | class InlineViewRef extends TableRef {
private static final Logger LOG = LogManager.getLogger(InlineViewRef.class);
private final View view;
private List<String> explicitColLabels;
private QueryStmt queryStmt;
private Analyzer inlineViewAnalyzer... | class InlineViewRef extends TableRef {
private static final Logger LOG = LogManager.getLogger(InlineViewRef.class);
private final View view;
private List<String> explicitColLabels;
private QueryStmt queryStmt;
private Analyzer inlineViewAnalyzer... |
```suggestion // Only tests in packages are executed so that the default packages (i.e. single BAL files), which have the package name ``` | 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
} | |
u r right, UT and regression test not be processed now | public static LogicalPlanAdapter of(Plan plan) {
return new LogicalPlanAdapter((LogicalPlan) plan, null);
} | return new LogicalPlanAdapter((LogicalPlan) plan, null); | public static LogicalPlanAdapter of(Plan plan) {
return new LogicalPlanAdapter((LogicalPlan) plan, null);
} | class LogicalPlanAdapter extends StatementBase implements Queriable {
private final StatementContext statementContext;
private final LogicalPlan logicalPlan;
private List<Expr> resultExprs;
private ArrayList<String> colLabels;
public LogicalPlanAdapter(LogicalPlan logicalPlan, StatementContext sta... | class LogicalPlanAdapter extends StatementBase implements Queriable {
private final StatementContext statementContext;
private final LogicalPlan logicalPlan;
private List<Expr> resultExprs;
private ArrayList<String> colLabels;
public LogicalPlanAdapter(LogicalPlan logicalPlan, StatementContext sta... |
Let's trying to using the `org.hamcrest.MatcherAssert.assertThat` in the new introduced test. | public void testServiceClassify() {
Assert.assertEquals(
KubernetesConfigOptions.ServiceExposedType.ClusterIP,
ServiceType.classify(buildExternalServiceWithClusterIP()));
Assert.assertEquals(
KubernetesConfigOptions.ServiceExposedType.Headless_ClusterIP,
... | Assert.assertEquals( | public void testServiceClassify() {
assertThat(
ServiceType.classify(buildExternalServiceWithClusterIP()),
is(KubernetesConfigOptions.ServiceExposedType.ClusterIP));
assertThat(
ServiceType.classify(buildExternalServiceWithHeadlessClusterIP()),
... | class ServiceTypeTest extends KubernetesClientTestBase {
@Test
} | class ServiceTypeTest extends KubernetesClientTestBase {
@Test
} |
Code coverage is actually not supported for single files. I checked. I will remove this TODO comment | private void createReport(final IBundleCoverage bundleCoverage) {
boolean containsSourceFiles = true;
for (IPackageCoverage packageCoverage : bundleCoverage.getPackages()) {
if (TesterinaConstants.DOT.equals(moduleName)) {
containsSourceFiles = packageCoverage.g... | private void createReport(final IBundleCoverage bundleCoverage) {
boolean containsSourceFiles = true;
for (IPackageCoverage packageCoverage : bundleCoverage.getPackages()) {
if (TesterinaConstants.DOT.equals(moduleName)) {
containsSourceFiles = packageCoverage.getName().isEm... | class per module
CodeCoverageUtils.unzipCompiledSource(moduleJarPath, projectDir, orgName, moduleName, version);
} catch (NoSuchFileException e) {
return;
} | class per module
CodeCoverageUtils.unzipCompiledSource(moduleJarPath, projectDir, orgName, moduleName, version);
} catch (NoSuchFileException e) {
return;
} | |
Should we add a more descriptive log message here? There is no `toString` implementation for `DefaultMultipleComponentLeaderElectionService` for now. Or is the memory address of the instance good enough? 🤔 | public void close() throws Exception {
synchronized (lock) {
if (!running) {
return;
}
running = false;
LOG.info("Closing {}.", this);
ExecutorUtils.gracefulShutdown(10L, TimeUnit.SECONDS, leadershipOperationExecutor);
Ex... | LOG.info("Closing {}.", this); | public void close() throws Exception {
synchronized (lock) {
if (!running) {
return;
}
running = false;
LOG.info("Closing {}.", this.getClass().getSimpleName());
ExecutorUtils.gracefulShutdown(10L, TimeUnit.SECONDS, leadershipOperatio... | class DefaultMultipleComponentLeaderElectionService
implements MultipleComponentLeaderElectionService,
MultipleComponentLeaderElectionDriver.Listener {
private static final Logger LOG =
LoggerFactory.getLogger(DefaultMultipleComponentLeaderElectionService.class);
private fin... | class DefaultMultipleComponentLeaderElectionService
implements MultipleComponentLeaderElectionService,
MultipleComponentLeaderElectionDriver.Listener {
private static final Logger LOG =
LoggerFactory.getLogger(DefaultMultipleComponentLeaderElectionService.class);
private fin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.