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 |
|---|---|---|---|---|---|
The base class' ChangeFeedStartFromInternal.populatePropertyBag is a no-op as is its baseclass JsonSerializable's populatePropertyBag method. | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.NOW);
}
} | super.populatePropertyBag(); | public void populatePropertyBag() {
super.populatePropertyBag();
synchronized(this) {
setProperty(
this,
Constants.Properties.CHANGE_FEED_START_FROM_TYPE,
ChangeFeedStartFromTypes.NOW);
}
} | class ChangeFeedStartFromNowImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromNowImpl() {
super();
}
@Override
@Override
public boolean supportsFullFidelityRetention() {
return true;
}
@Override
public void populateRequest(RxDocumentServiceReque... | class ChangeFeedStartFromNowImpl extends ChangeFeedStartFromInternal {
public ChangeFeedStartFromNowImpl() {
super();
}
@Override
@Override
public boolean supportsFullFidelityRetention() {
return true;
}
@Override
public void populateRequest(RxDocumentServiceReque... |
please update the `convertToRowData` method based on the values of `remainingPartitions` | public ChangelogMode getChangelogMode(ChangelogMode requestedMode) {
if (isInsertOnly) {
return ChangelogMode.insertOnly();
} else {
ChangelogMode.Builder builder = ChangelogMode.newBuilder();
if (schema.getPrimaryKey().isPresent()) {
for (RowKind kind : requestedMode.getContainedKinds()) {... | builder.addContainedKind(kind); | public ChangelogMode getChangelogMode(ChangelogMode requestedMode) {
if (isInsertOnly) {
return ChangelogMode.insertOnly();
} else {
ChangelogMode.Builder builder = ChangelogMode.newBuilder();
if (schema.getPrimaryKey().isPresent()) {
for (RowKind kind : requestedMode.getContainedKinds()) {... | class TestValuesTableSink implements DynamicTableSink {
private final TableSchema schema;
private final String tableName;
private final boolean isInsertOnly;
private final String runtimeSink;
private final int expectedNum;
private TestValuesTableSink(
TableSchema schema,
String tableName,
bool... | class TestValuesTableSink implements DynamicTableSink {
private final TableSchema schema;
private final String tableName;
private final boolean isInsertOnly;
private final String runtimeSink;
private final int expectedNum;
private TestValuesTableSink(
TableSchema schema,
String tableName,
bool... |
In the mv rewrite case, there are only join and scan operator. | private OptExpression pushdownPredicatesForJoin(OptExpression optExpression, ScalarOperator predicate) {
if (!(optExpression.getOp() instanceof LogicalJoinOperator)) {
if (predicate != null) {
Operator.Builder builder = OperatorBuilderFactory.build(optExpression.getO... | if (optExpression.inputAt(i).getOp() instanceof LogicalJoinOperator) { | private OptExpression pushdownPredicatesForJoin(OptExpression optExpression, ScalarOperator predicate) {
if (!(optExpression.getOp() instanceof LogicalJoinOperator)) {
if (predicate != null) {
Operator.Builder builder = OperatorBuilderFactory.build(optExpression.getO... | class scalar operators may generate the same rewritten conjunct.
.collect(Collectors.toList());
if (rewrittenConjuncts.isEmpty()) {
return null;
} | class scalar operators may generate the same rewritten conjunct.
.collect(Collectors.toList());
if (rewrittenConjuncts.isEmpty()) {
return null;
} |
I think that this implies that we have to take better care of allowed lateness here. Elements that are more late than allowed lateness are dropped by any stateful dofn, this is no new behavior. | private boolean isLate(BoundedWindow window) {
Instant gcTime = LateDataUtils.garbageCollectionTime(window, windowingStrategy);
Instant inputWM = stepContext.timerInternals().currentInputWatermarkTime();
return gcTime.isBefore(inputWM);
} | return gcTime.isBefore(inputWM); | private boolean isLate(BoundedWindow window) {
Instant gcTime = LateDataUtils.garbageCollectionTime(window, windowingStrategy);
Instant inputWM = stepContext.timerInternals().currentInputWatermarkTime();
return gcTime.isBefore(inputWM);
} | class StatefulDoFnRunner<InputT, OutputT, W extends BoundedWindow>
implements DoFnRunner<InputT, OutputT> {
public static final String DROPPED_DUE_TO_LATENESS_COUNTER = "StatefulParDoDropped";
private static final String SORT_BUFFER_STATE = "sortBuffer";
private static final String SORT_BUFFER_MIN_STAMP = "s... | class StatefulDoFnRunner<InputT, OutputT, W extends BoundedWindow>
implements DoFnRunner<InputT, OutputT> {
public static final String DROPPED_DUE_TO_LATENESS_COUNTER = "StatefulParDoDropped";
private static final String SORT_BUFFER_STATE = "sortBuffer";
private static final String SORT_BUFFER_MIN_STAMP = "s... |
Since we only create a new strand when we hit a worker or start, enough to check the current parent. | public boolean lockedBySameContext(Strand ctx) {
return this.current.getLast() == ctx;
} | return this.current.getLast() == ctx; | public boolean lockedBySameContext(Strand ctx) {
return this.current.getLast() == ctx;
} | class BLock {
private ArrayDeque<Strand> current;
private ArrayDeque<Strand> waitingForLock;
public BLock() {
this.current = new ArrayDeque<>();
this.waitingForLock = new ArrayDeque<>();
}
public synchronized boolean lock(Strand strand) {
if (isLockFree() || lockedBySameC... | class BLock {
private ArrayDeque<Strand> current;
private ArrayDeque<Strand> waitingForLock;
public BLock() {
this.current = new ArrayDeque<>();
this.waitingForLock = new ArrayDeque<>();
}
public synchronized boolean lock(Strand strand) {
if (isLockFree() || lockedBySameC... |
> It also doesn't really make sense for the maxParallelism to only be settable if it was previously autoConfigured by the system. 👍🏼 I was able to remove the concept of "auto-configured" into SchedulerBase, the only place it makes sense. | public void setMaxParallelism(int maxParallelism) {
Preconditions.checkState(
isMaxParallelismAutoConfigured(),
"Attempt to override a configured max parallelism. Configured: "
+ this.maxParallelism
+ ", argument: "
... | isMaxParallelismAutoConfigured(), | public void setMaxParallelism(int maxParallelism) {
parallelismInfo.setMaxParallelism(maxParallelism);
} | class ExecutionJobVertex
implements AccessExecutionJobVertex, Archiveable<ArchivedExecutionJobVertex> {
/** Use the same log for all ExecutionGraph classes. */
private static final Logger LOG = DefaultExecutionGraph.LOG;
private final Object stateMonitor = new Object();
private final Internal... | class ExecutionJobVertex
implements AccessExecutionJobVertex, Archiveable<ArchivedExecutionJobVertex> {
/** Use the same log for all ExecutionGraph classes. */
private static final Logger LOG = DefaultExecutionGraph.LOG;
private final Object stateMonitor = new Object();
private final Internal... |
Sorry to ask this, but can we change this one to be the same format (ie. using ifPresent lambda) so the code is all consistent. | private ConfigurationBuilder builderFromProperties(Properties properties) {
ConfigurationBuilder builder = new ConfigurationBuilder();
Object marshallerInstance = properties.remove(ConfigurationProperties.MARSHALLER);
if (marshallerInstance != null) {
if (marshallerInstance ... | Optional<String> runtimeServerList = infinispanClientRuntimeConfig.serverList; | private ConfigurationBuilder builderFromProperties(Properties properties) {
ConfigurationBuilder builder = new ConfigurationBuilder();
Object marshallerInstance = properties.remove(ConfigurationProperties.MARSHALLER);
if (marshallerInstance != null) {
if (marshallerInstance ... | class path to read contents of
* @return string containing the contents of the file
*/
private static String getContents(String fileName) {
InputStream stream = InfinispanClientProducer.class.getResourceAsStream(fileName);
try (Scanner scanner = new Scanner(stream, "UTF-8")) {
... | class path to read contents of
* @return string containing the contents of the file
*/
private static String getContents(String fileName) {
InputStream stream = InfinispanClientProducer.class.getResourceAsStream(fileName);
try (Scanner scanner = new Scanner(stream, "UTF-8")) {
... |
As before I would create the method `restoreDefaultConfig` and also call it here. | protected void after() {
try {
stopFlinkCluster();
} catch (IOException e) {
LOG.error("Failure while shutting down Flink cluster.", e);
}
final Path originalConfig = conf.resolve(FLINK_CONF_YAML);
final Path backupConfig = conf.resolve(FLINK_CONF_YAML_BACKUP);
try {
Files.move(backupConfig, orig... | final Path originalConfig = conf.resolve(FLINK_CONF_YAML); | protected void after() {
try {
stopFlinkCluster();
} catch (IOException e) {
LOG.error("Failure while shutting down Flink cluster.", e);
}
final Path originalConfig = conf.resolve(FLINK_CONF_YAML);
final Path backupConfig = conf.resolve(FLINK_CONF_YAML_BACKUP);
try {
Files.move(backupConfig, orig... | class FlinkDistribution extends ExternalResource {
private static final Logger LOG = LoggerFactory.getLogger(FlinkDistribution.class);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final List<AutoClosablePath> filesToDelete = new ArrayList<>(4);
private static final Path FLINK_CO... | class FlinkDistribution extends ExternalResource {
private static final Logger LOG = LoggerFactory.getLogger(FlinkDistribution.class);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final Path FLINK_CONF_YAML = Paths.get("flink-conf.yaml");
private static final Path FLINK_CO... |
Actually, it was wrong. The async connection must happen during the actual subscription and not during the initialization. So during the initialization, the connector should not do anything "network related". The code changed in SmallRye Reactive Messaging. | void onApplicationStart(@Observes StartupEvent event) {
try {
mediatorManager.initializeAndRun();
} catch (Exception e) {
throw new RuntimeException(e);
}
} | throw new RuntimeException(e); | void onApplicationStart(@Observes StartupEvent event) {
try {
mediatorManager.initializeAndRun();
} catch (Exception e) {
throw new RuntimeException(e);
}
} | class SmallRyeReactiveMessagingLifecycle {
@Inject
MediatorManager mediatorManager;
} | class SmallRyeReactiveMessagingLifecycle {
@Inject
MediatorManager mediatorManager;
} |
Should be better for perf since we don't create new flux every iteration. | public Mono<Void> runAsync() {
return blobAsyncClient.upload(randomByteBufferFlux, null, true).then();
} | return blobAsyncClient.upload(randomByteBufferFlux, null, true).then(); | public Mono<Void> runAsync() {
return blobAsyncClient.upload(randomByteBufferFlux, null, true).then();
} | class UploadBlobTest extends BlobTestBase<PerfStressOptions> {
private final Flux<ByteBuffer> randomByteBufferFlux;
public UploadBlobTest(PerfStressOptions options) {
super(options);
this.randomByteBufferFlux = createRandomByteBufferFlux(options.getSize());
}
@Override
public void... | class UploadBlobTest extends BlobTestBase<PerfStressOptions> {
private final Flux<ByteBuffer> randomByteBufferFlux;
public UploadBlobTest(PerfStressOptions options) {
super(options);
this.randomByteBufferFlux = createRandomByteBufferFlux(options.getSize());
}
@Override
public void... |
My understanding is that the boolean expression for `COUNTIF` aggregate will be computed in a precursory `Project`. As of right now list of supported aggregate functions is limited to: https://github.com/apache/beam/blob/659d84b4be5bdd36b408359a8c69f4eb12771180/sdks/java/extensions/sql/zetasql/src/main/java/org/apache/... | public RelNode convert(ResolvedAggregateScan zetaNode, List<RelNode> inputs) {
RelNode input = convertAggregateScanInputScanToLogicalProject(zetaNode, inputs.get(0));
int groupFieldsListSize = zetaNode.getGroupByList().size();
ImmutableBitSet groupSet;
if (groupFieldsListSize != 0) {
groupSe... | columnRefoff++; | public RelNode convert(ResolvedAggregateScan zetaNode, List<RelNode> inputs) {
RelNode input = convertAggregateScanInputScanToLogicalProject(zetaNode, inputs.get(0));
int groupFieldsListSize = zetaNode.getGroupByList().size();
ImmutableBitSet groupSet;
if (groupFieldsListSize != 0) {
groupSe... | class AggregateScanConverter extends RelConverter<ResolvedAggregateScan> {
private static final String AVG_ILLEGAL_LONG_INPUT_TYPE =
"AVG(LONG) is not supported. You might want to use AVG(CAST(expression AS DOUBLE).";
AggregateScanConverter(ConversionContext context) {
super(context);
}
@Override
... | class AggregateScanConverter extends RelConverter<ResolvedAggregateScan> {
private static final String AVG_ILLEGAL_LONG_INPUT_TYPE =
"AVG(LONG) is not supported. You might want to use AVG(CAST(expression AS DOUBLE).";
AggregateScanConverter(ConversionContext context) {
super(context);
}
@Override
... |
@cescoffier thanks for the review. > Same comments: > > * how to handle when there are several Pools In the meantime multiple reactive datasources are not handled, once added we will for sure need to handle them the same way we have handled them for the Agroal connection healthcheck. > * you need to be sure to not... | public HealthCheckResponse call() {
HealthCheckResponseBuilder builder = HealthCheckResponse.named("Reactive PostgreSQL connection health check").up();
try {
CompletableFuture<Void> databaseConnectionAttempt = new CompletableFuture<>();
pgPool.query("SELECT 1", ar -> {
... | databaseConnectionAttempt.join(); | public HealthCheckResponse call() {
HealthCheckResponseBuilder builder = HealthCheckResponse.named("Reactive PostgreSQL connection health check").up();
try {
CompletableFuture<Void> databaseConnectionAttempt = new CompletableFuture<>();
pgPool.query("SELECT 1")
... | class ReactivePgDataSourceHealthCheck implements HealthCheck {
private PgPool pgPool;
@PostConstruct
protected void init() {
pgPool = Arc.container().instance(PgPool.class).get();
}
@Override
} | class ReactivePgDataSourceHealthCheck implements HealthCheck {
private PgPool pgPool;
@PostConstruct
protected void init() {
pgPool = Arc.container().instance(PgPool.class).get();
}
@Override
} |
Noting that the return value is not `@Nullable`. Suggest re-enabling nullness checking here since it would have caught this. (you could perhaps suppress it for other parts of the file you don't want to fix. | public Progress getProgress() {
if (currentReader == null) {
return null;
}
Double consumedFraction = currentReader.getFractionConsumed();
if (consumedFraction == null) {
return null;
}
return RestrictionTracker.Progress.from(
consumedFract... | return null; | public Progress getProgress() {
if (currentReader == null) {
return Progress.NONE;
}
Double consumedFraction = currentReader.getFractionConsumed();
if (consumedFraction == null) {
return Progress.NONE;
}
return Progress.from(consumedFraction, ... | class BoundedSourceAsSDFRestrictionTracker<
BoundedSourceT extends BoundedSource<T>, T>
extends RestrictionTracker<BoundedSourceT, TimestampedValue<T>[]> implements HasProgress {
private final BoundedSourceT initialRestriction;
private final PipelineOptions pipelineOptions;
private... | class BoundedSourceAsSDFRestrictionTracker<
BoundedSourceT extends BoundedSource<T>, T>
extends RestrictionTracker<BoundedSourceT, TimestampedValue<T>[]> implements HasProgress {
private final BoundedSourceT initialRestriction;
private final PipelineOptions pipelineOptions;
private... |
Is this ability to add filters documented somewhere? | public void init(@Observes Filters filters) {
filters.register(rc -> {
rc.response().putHeader("X-Header", "AAAA");
rc.next();
}, 100);
} | filters.register(rc -> { | public void init(@Observes Filters filters) {
filters.register(rc -> {
rc.response().putHeader("X-Header", "AAAA");
rc.next();
}, 100);
} | class DevFilter {
} | class DevFilter {
} |
Do we need to allow this? The debug port won't be reachable in any case. | public void requireThatJvmOptionsAreLogged() throws IOException, SAXException {
verifyLoggingOfJvmOptions(true,
"options",
"-Xms2G foo bar",
"foo", "bar");
verifyLoggingOfJvmOptions(true,
... | verifyLoggingOfJvmOptions(true, "options", "-Djava.library.path=/opt/vespa/lib64:/home/y/lib64 -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005"); | public void requireThatJvmOptionsAreLogged() throws IOException, SAXException {
verifyLoggingOfJvmOptions(true,
"options",
"-Xms2G foo bar",
"foo", "bar");
verifyLoggingOfJvmOptions(true,
... | class JvmOptionsTest extends ContainerModelBuilderTestBase {
@Test
public void verify_jvm_tag_with_attributes() throws IOException, SAXException {
String servicesXml =
"<container version='1.0'>" +
" <search/>" +
" <nodes>" +
... | class JvmOptionsTest extends ContainerModelBuilderTestBase {
@Test
public void verify_jvm_tag_with_attributes() throws IOException, SAXException {
String servicesXml =
"<container version='1.0'>" +
" <search/>" +
" <nodes>" +
... |
Sounds like a pragmatic solution to me | private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version targetPlatform = controller.jobController().run(id).get().versions().targetPlatform();
final Version platform = targetPlatform.equals(Version.fromString("7.220.14"))
? targetPlatform
... | final Version platform = targetPlatform.equals(Version.fromString("7.220.14")) | private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version targetPlatform = controller.jobController().run(id).get().versions().targetPlatform();
final Version platform = targetPlatform.equals(Version.fromString("7.220.14"))
? targetPlatform
... | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
static final NodeResources ... | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
static final NodeResources ... |
Why sleep here or how can be know how long to sleep? | private TaskDeploymentDescriptor createReceiver(NettyShuffleDescriptor shuffleDescriptor) throws IOException {
InputGateDeploymentDescriptor inputGateDeploymentDescriptor = new InputGateDeploymentDescriptor(
new IntermediateDataSetID(),
ResultPartitionType.PIPELINED,
0,
new ShuffleDescriptor[] {shuffleDes... | ResultPartitionType.PIPELINED, | private TaskDeploymentDescriptor createReceiver(NettyShuffleDescriptor shuffleDescriptor) throws IOException {
InputGateDeploymentDescriptor inputGateDeploymentDescriptor = new InputGateDeploymentDescriptor(
new IntermediateDataSetID(),
ResultPartitionType.PIPELINED,
0,
new ShuffleDescriptor[] {shuffleDes... | class TaskExecutorSubmissionTest extends TestLogger {
@Rule
public final TestName testName = new TestName();
private static final Time timeout = Time.milliseconds(10000L);
private JobID jobId = new JobID();
/**
* Tests that we can submit a task to the TaskManager given that we've allocated a slot there.
*/... | class TaskExecutorSubmissionTest extends TestLogger {
@Rule
public final TestName testName = new TestName();
private static final Time timeout = Time.milliseconds(10000L);
private JobID jobId = new JobID();
private MetricRegistryImpl metricRegistry;
private TestingRpcService rpcService;
private String metr... |
Removes the use of a Supplier function to store the TableSchema and simply uses a class property to hold the TableSchema. | public T read(T reuse, Decoder in) throws IOException {
GenericRecord record = (GenericRecord) this.reader.read(reuse, in);
return parseFn.apply(new SchemaAndRecord(record, this.tableSchema));
} | return parseFn.apply(new SchemaAndRecord(record, this.tableSchema)); | public T read(T reuse, Decoder in) throws IOException {
GenericRecord record = (GenericRecord) this.reader.read(reuse, in);
return parseFn.apply(new SchemaAndRecord(record, this.tableSchema));
} | class GenericDatumTransformer<T> implements DatumReader<T> {
private final SerializableFunction<SchemaAndRecord, T> parseFn;
private final TableSchema tableSchema;
private GenericDatumReader<T> reader;
private org.apache.avro.Schema writerSchema;
public GenericDatumTransformer(
Serializable... | class GenericDatumTransformer<T> implements DatumReader<T> {
private final SerializableFunction<SchemaAndRecord, T> parseFn;
private final TableSchema tableSchema;
private GenericDatumReader<T> reader;
private org.apache.avro.Schema writerSchema;
public GenericDatumTransformer(
Serializable... |
This is just a comment, it won't hurt to change it now. | public A build(ClassOutput classOutput) {
generatedLiterals.computeIfAbsent(annotationLiteral, generatedName -> {
String name = annotationInstance.name().toString();
String signature = String.format("L%1$s<L%2$s;>;L%2$s;",
... | public A build(ClassOutput classOutput) {
generatedLiterals.computeIfAbsent(annotationLiteral, generatedName -> {
String name = annotationInstance.name().toString();
String signature = String.format("L%1$s<L%2$s;>;L%2$s;",
... | class AnnotationProxyBuilder<A> {
private final ClassInfo annotationClass;
private final String annotationLiteral;
private final AnnotationInstance annotationInstance;
private final Class<A> annotationType;
private final Map<String, Object> defaultValues = new HashMap<>();
... | class AnnotationProxyBuilder<A> {
private final ClassInfo annotationClass;
private final String annotationLiteral;
private final AnnotationInstance annotationInstance;
private final Class<A> annotationType;
private final Map<String, Object> defaultValues = new HashMap<>();
... | |
I didn't get it... for the case of one array `arrays.length == 1` and it will not enter this `if`. Also having just one array is ok, in that case we can just return it back. Why are we talking about `"need at least two arrays"` ? | private InType[] convertToArrays(InType[] arrays) {
if (arrays == null || arrays.length < 1) {
throw new ValidationException("need at least two arrays");
}
int numberOfNull = 0;
InType notNullArray = null;
for (int i = 0; i < arrays.length; ++i) {
if (arra... | throw new ValidationException("need at least two arrays"); | private InType[] convertToArrays(InType[] arrays) {
if (arrays == null || arrays.length == 0) {
return arrays;
}
InType notNullArray = null;
for (int i = 0; i < arrays.length; ++i) {
if (arrays[i] != null) {
notNullArray = arrays[i];
}
... | class BaseExpressions<InType, OutType> {
protected abstract Expression toExpr();
protected abstract OutType toApiSpecificExpression(Expression expression);
/**
* Specifies a name for an expression i.e. a field.
*
* @param name name for one field
* @param extraNames additional names if ... | class BaseExpressions<InType, OutType> {
protected abstract Expression toExpr();
protected abstract OutType toApiSpecificExpression(Expression expression);
/**
* Specifies a name for an expression i.e. a field.
*
* @param name name for one field
* @param extraNames additional names if ... |
Also make sure to rename the `Build` variable to `build` to follow the Java coding guidelines for variables :wink: | public void testAddAndRemoveExtension() throws IOException, URISyntaxException, InterruptedException {
final File projectDir = getProjectDir("add-remove-extension-single-module");
runGradleWrapper(projectDir, ":addExtension", "--extensions=hibernate-orm");
final Path Build = projectDir.toPath... | assertThat(Files.readString(Build)).contains("implementation 'io.quarkus:quarkus-hibernate-orm'"); | public void testAddAndRemoveExtension() throws IOException, URISyntaxException, InterruptedException {
final File projectDir = getProjectDir("add-remove-extension-single-module");
runGradleWrapper(projectDir, ":addExtension", "--extensions=hibernate-orm");
final Path build = projectDir.toPath... | class AddExtensionToSingleModuleProjectTest extends QuarkusGradleWrapperTestBase {
@Test
@Test
public void testRemoveNonExistentExtension() throws IOException, URISyntaxException, InterruptedException {
final File projectDir = getProjectDir("add-remove-extension-single-module");
run... | class AddExtensionToSingleModuleProjectTest extends QuarkusGradleWrapperTestBase {
@Test
@Test
public void testRemoveNonExistentExtension() throws IOException, URISyntaxException, InterruptedException {
final File projectDir = getProjectDir("add-remove-extension-single-module");
run... |
Actually, that's not the same thing due to the behavior of `NodeFilter#nextMatches`. Your suggestion would be fine if `NodeFilter#nextMatches` method didn't return `true` for the last filter in the chain. I think the intention is that filters should match a given node if no filters in the chain actively reject it (a b... | public boolean matches(Node node) {
if (!version.isEmpty() && !node.status().osVersion().filter(v -> v.equals(version)).isPresent()) {
return false;
}
return nextMatches(node);
} | if (!version.isEmpty() && !node.status().osVersion().filter(v -> v.equals(version)).isPresent()) { | public boolean matches(Node node) {
if (!version.isEmpty() && !node.status().osVersion().filter(v -> v.equals(version)).isPresent()) {
return false;
}
return nextMatches(node);
} | class NodeOsVersionFilter extends NodeFilter {
private final Version version;
private NodeOsVersionFilter(Version version, NodeFilter next) {
super(next);
this.version = Objects.requireNonNull(version, "version cannot be null");
}
@Override
public static NodeOsVersionFilter ... | class NodeOsVersionFilter extends NodeFilter {
private final Version version;
private NodeOsVersionFilter(Version version, NodeFilter next) {
super(next);
this.version = Objects.requireNonNull(version, "version cannot be null");
}
@Override
public static NodeOsVersionFilter ... |
@srnagar `String eventHubName()` is not renamed. | private static String getExpression(EventPosition eventPosition) {
final String isInclusiveFlag = eventPosition.isInclusive() ? "=" : "";
if (eventPosition.getOffset() != null) {
return String.format(
AmqpConstants.AMQP_ANNOTATION_FORMAT, OFFSET_ANNOTATION_NAME.getV... | ms = Long.toString(Long.MAX_VALUE); | private static String getExpression(EventPosition eventPosition) {
final String isInclusiveFlag = eventPosition.isInclusive() ? "=" : "";
if (eventPosition.getOffset() != null) {
return String.format(
AmqpConstants.AMQP_ANNOTATION_FORMAT, OFFSET_ANNOTATION_NAME.getV... | class EventHubAsyncClient implements Closeable {
/**
* The name of the default consumer group in the Event Hubs service.
*/
public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default";
private static final String RECEIVER_ENTITY_PATH_FORMAT = "%s/ConsumerGroups/%s/Partitions/%s";
priv... | class EventHubAsyncClient implements Closeable {
/**
* The name of the default consumer group in the Event Hubs service.
*/
public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default";
private static final String RECEIVER_ENTITY_PATH_FORMAT = "%s/ConsumerGroups/%s/Partitions/%s";
priv... |
Need to keep jvmTarget option since we have some tool-integration test on running a jar which by default use ballerina-tools distribution. We can do some modifications in integration test utils to run jvm integration tests on jballerina distribution. hence keep this for moment. | public void execute() {
if (helpFlag) {
String commandUsageInfo = BLauncherCmd.getCommandUsageInfo(BUILD_COMMAND);
outStream.println(commandUsageInfo);
return;
}
if (argList != null && argList.size() > 1) {
throw LauncherUtils.createUsageException... | if (jvmTarget || JVM_TARGET.equals(System.getProperty(BALLERINA_TARGET))) { | public void execute() {
if (helpFlag) {
String commandUsageInfo = BLauncherCmd.getCommandUsageInfo(BUILD_COMMAND);
outStream.println(commandUsageInfo);
return;
}
if (argList != null && argList.size() > 1) {
throw LauncherUtils.createUsageException... | class BuildCommand implements BLauncherCmd {
private static final String USER_DIR = "user.dir";
private static PrintStream outStream = System.err;
@CommandLine.Option(names = {"-c"}, description = "build a compiled module")
private boolean buildCompiledPkg;
@CommandLine.Option(names = {"-o"}, desc... | class BuildCommand implements BLauncherCmd {
private static final String USER_DIR = "user.dir";
private static PrintStream outStream = System.err;
@CommandLine.Option(names = {"-c"}, description = "build a compiled module")
private boolean buildCompiledPkg;
@CommandLine.Option(names = {"-o"}, desc... |
Why do you close again if the session is already closed? Shouldn't the condition be negation? | public static void closeIfAnonymousSession(BMap<String, BValue> obj) throws ActiveMQException {
boolean anonymousSession = ((BBoolean) obj.get("anonymousSession")).booleanValue();
if (anonymousSession) {
ClientSession session = ArtemisUtils.getClientSessionFromBMap(obj);
if (sess... | if (session.isClosed()) { | public static void closeIfAnonymousSession(BMap<String, BValue> obj) throws ActiveMQException {
boolean anonymousSession = ((BBoolean) obj.get("anonymousSession")).booleanValue();
if (anonymousSession) {
ClientSession session = ArtemisUtils.getClientSessionFromBMap(obj);
if (!ses... | class ArtemisUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(ArtemisUtils.class);
public static void throwBallerinaException(String message, Context context, Throwable throwable) {
LOGGER.error(message, throwable);
throw new BallerinaException(message, throwable, context);
... | class ArtemisUtils {
/**
* Util function to throw a {@link BallerinaException}.
*
* @param message the error message
* @param context the Ballerina context
* @param exception the exception to be propagated
* @param logger the logger to log errors
*/
public static void thr... |
Seems `tryLock`'s parameter `lockName` is still handled as `schemaName` in `ShardingSphereDistributeGlobalLock.innerTryLock`. `LockContext` is just designed for schema lock for now. Could we use `PipelineSimpleLock` to implement it? | private void prepareTarget(final JobConfiguration jobConfig, final PipelineDataSourceManager dataSourceManager) {
DataSourcePreparer dataSourcePreparer = EnvironmentCheckerFactory.getDataSourcePreparer(jobConfig.getHandleConfig().getTargetDatabaseType());
if (null == dataSourcePreparer) {
lo... | boolean skipPrepare = !lock.tryLock("prepareTargetTablesLock", 100); | private void prepareTarget(final JobConfiguration jobConfig, final PipelineDataSourceManager dataSourceManager) {
DataSourcePreparer dataSourcePreparer = EnvironmentCheckerFactory.getDataSourcePreparer(jobConfig.getHandleConfig().getTargetDatabaseType());
if (null == dataSourcePreparer) {
lo... | class RuleAlteredJobPreparer {
static {
ShardingSphereServiceLoader.register(DataSourceChecker.class);
}
private final InventoryTaskSplitter inventoryTaskSplitter = new InventoryTaskSplitter();
/**
* Do prepare work for scaling job.
*
* @param jobContext job context... | class RuleAlteredJobPreparer {
static {
ShardingSphereServiceLoader.register(DataSourceChecker.class);
}
private final InventoryTaskSplitter inventoryTaskSplitter = new InventoryTaskSplitter();
/**
* Do prepare work for scaling job.
*
* @param jobContext job context... |
Please remove this useless blank line. | public void assertNewInstanceForSQLServer() {
SQLStatement statement = new SQLServerDropSchemaStatement();
Optional<SingleTableMetadataValidator> actual = SingleTableMetadataValidatorFactory.newInstance(statement);
assertTrue(actual.isPresent());
} | public void assertNewInstanceForSQLServer() {
SQLStatement statement = new SQLServerDropSchemaStatement();
Optional<SingleTableMetadataValidator> actual = SingleTableMetadataValidatorFactory.newInstance(statement);
assertTrue(actual.isPresent());
} | class SingleTableMetadataValidatorFactoryTest {
@Test
@SuppressWarnings("rawtypes")
public void assertNewInstanceForPostgreSQL() {
SQLStatement statement = new PostgreSQLDropSchemaStatement();
Optional<SingleTableMetadataValidator> actual = SingleTableMetadataValidatorFactory.n... | class SingleTableMetadataValidatorFactoryTest {
@Test
@SuppressWarnings("rawtypes")
public void assertNewInstanceForPostgreSQL() {
SQLStatement statement = new PostgreSQLDropSchemaStatement();
Optional<SingleTableMetadataValidator> actual = SingleTableMetadataValidatorFactory.newInstanc... | |
Do we need a separate param for useSeparateMetadataDb? We could just check if (isRbac) here. Right? | protected void before() throws Throwable {
final ChangeStreamTestPipelineOptions options =
IOITHelper.readIOTestPipelineOptions(ChangeStreamTestPipelineOptions.class);
projectId =
Optional.ofNullable(options.getProjectId())
.orElseGet(() -> options.as(GcpOptions.class).getProject())... | if (useSeparateMetadataDb) { | protected void before() throws Throwable {
final ChangeStreamTestPipelineOptions options =
IOITHelper.readIOTestPipelineOptions(ChangeStreamTestPipelineOptions.class);
projectId =
Optional.ofNullable(options.getProjectId())
.orElseGet(() -> options.as(GcpOptions.class).getProject())... | class IntegrationTestEnv extends ExternalResource {
private static final Logger LOG = LoggerFactory.getLogger(IntegrationTestEnv.class);
private static final int TIMEOUT_MINUTES = 10;
private static final int MAX_POSTGRES_TABLE_NAME_LENGTH = 63;
private static final int MAX_CHANGE_STREAM_NAME_LENGTH = 30;
pr... | class IntegrationTestEnv extends ExternalResource {
private static final Logger LOG = LoggerFactory.getLogger(IntegrationTestEnv.class);
private static final int TIMEOUT_MINUTES = 10;
private static final int MAX_POSTGRES_TABLE_NAME_LENGTH = 63;
private static final int MAX_CHANGE_STREAM_NAME_LENGTH = 30;
pr... |
I have created the retryClient as per the offline discussion. | public static void initEndpoint(ObjectValue webSocketClient) {
@SuppressWarnings(WebSocketConstants.UNCHECKED)
MapValue<String, Object> clientEndpointConfig = (MapValue<String, Object>) webSocketClient.getMapValue(
HttpConstants.CLIENT_ENDPOINT_CONFIG);
Strand strand = Scheduler.... | new ClientConnectorListener())); | public static void initEndpoint(ObjectValue webSocketClient) {
@SuppressWarnings(WebSocketConstants.UNCHECKED)
MapValue<String, Object> clientEndpointConfig = (MapValue<String, Object>) webSocketClient.getMapValue(
WebSocketConstants.CLIENT_ENDPOINT_CONFIG);
Strand strand = Sched... | class InitEndpoint {
private static final Logger logger = LoggerFactory.getLogger(InitEndpoint.class);
private static final String INTERVAL_IN_MILLIS = "intervalInMillis";
private static final String MAX_WAIT_INTERVAL = "maxWaitIntervalInMillis";
private static final String MAX_COUNT = "maxCount";
... | class InitEndpoint {
private InitEndpoint() {
}
} |
try best to cancel sc job even there is a RPC error | protected void onCancel() {
List<Long> rollupIndexList = new ArrayList<Long>();
rollupIndexList.add(rollupIndexId);
long tryTimes = 1;
while (true) {
try {
((CloudInternalCatalog) Env.getCurrentInternalCatalog())
.dropMaterializedIndex(tabl... | partitionId, baseTabletId, rollupTabletId); | protected void onCancel() {
List<Long> rollupIndexList = new ArrayList<Long>();
rollupIndexList.add(rollupIndexId);
long tryTimes = 1;
while (true) {
try {
((CloudInternalCatalog) Env.getCurrentInternalCatalog())
.dropMaterializedIndex(tabl... | class CloudRollupJobV2 extends RollupJobV2 {
private static final Logger LOG = LogManager.getLogger(CloudRollupJobV2.class);
public static AlterJobV2 buildCloudRollupJobV2(RollupJobV2 job) throws IllegalAccessException, AnalysisException {
CloudRollupJobV2 ret = new CloudRollupJobV2();
List<Fie... | class CloudRollupJobV2 extends RollupJobV2 {
private static final Logger LOG = LogManager.getLogger(CloudRollupJobV2.class);
public static AlterJobV2 buildCloudRollupJobV2(RollupJobV2 job) throws IllegalAccessException, AnalysisException {
CloudRollupJobV2 ret = new CloudRollupJobV2();
List<Fie... |
Fighting against the IDE, sure I will! | public AgroalDataSource doCreateDataSource(String dataSourceName) {
if (!dataSourceSupport.entries.containsKey(dataSourceName)) {
throw new IllegalArgumentException("No datasource named '" + dataSourceName + "' exists");
}
DataSourceJdbcBuildTimeConfig dataSourceJdbcBuildTimeConfig ... | dataSourceName)); | public AgroalDataSource doCreateDataSource(String dataSourceName) {
if (!dataSourceSupport.entries.containsKey(dataSourceName)) {
throw new IllegalArgumentException("No datasource named '" + dataSourceName + "' exists");
}
DataSourceJdbcBuildTimeConfig dataSourceJdbcBuildTimeConfig ... | class DataSources {
private static final Logger log = Logger.getLogger(DataSources.class.getName());
public static final String DEPRECATED_URL_PROPERTY_NAME_ERROR_MESSAGE_FORMAT = "`quarkus.datasource.%s.url` is deprecated and will be removed in a future version - it is "
+
"recommended... | class DataSources {
private static final Logger log = Logger.getLogger(DataSources.class.getName());
private final DataSourcesBuildTimeConfig dataSourcesBuildTimeConfig;
private final DataSourcesRuntimeConfig dataSourcesRuntimeConfig;
private final DataSourcesJdbcBuildTimeConfig dataSourcesJdbcBuildTi... |
Probably not because for `Cache#get()` we only wrap the checked exceptions. | public CompletableFuture<Object> apply(Object key) {
return (CompletableFuture<Object>) valueLoader.apply((K) key)
.map(i -> NullValueConverter.toCacheValue(i))
.subscribeAsCompletionStage();
} | return (CompletableFuture<Object>) valueLoader.apply((K) key) | public CompletableFuture<Object> apply(Object key) {
return valueLoader.apply((K) key)
.map(TO_CACHE_VALUE)
.subscribeAsCompletionStage();
} | class CaffeineCacheImpl extends AbstractCache implements CaffeineCache {
private static final Logger LOGGER = Logger.getLogger(CaffeineCacheImpl.class);
final AsyncCache<Object, Object> cache;
private final CaffeineCacheInfo cacheInfo;
private final StatsCounter statsCounter;
public CaffeineCach... | class CaffeineCacheImpl extends AbstractCache implements CaffeineCache {
private static final Logger LOGGER = Logger.getLogger(CaffeineCacheImpl.class);
final AsyncCache<Object, Object> cache;
private final CaffeineCacheInfo cacheInfo;
private final StatsCounter statsCounter;
private final boolea... |
That is correct. But we don't need the `RuntimeException` anymore. We can just use `FutureUtils.completeExceptionally(e)` with the `InterruptedException` here | public void testJobBeingMarkedAsDirtyBeforeCleanup() throws Exception {
final OneShotLatch markAsDirtyLatch = new OneShotLatch();
final TestingDispatcher.Builder dispatcherBuilder =
createTestingDispatcherBuilder()
.setJobResultStore(
... | new RuntimeException(e)); | public void testJobBeingMarkedAsDirtyBeforeCleanup() throws Exception {
final OneShotLatch markAsDirtyLatch = new OneShotLatch();
final TestingDispatcher.Builder dispatcherBuilder =
createTestingDispatcherBuilder()
.setJobResultStore(
... | class DispatcherResourceCleanupTest extends TestLogger {
@ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule public ExpectedException expectedException = ExpectedException.none();
@Rule
public final TestingFatalErrorHandlerResource testingFatalErrorHandlerResource ... | class DispatcherResourceCleanupTest extends TestLogger {
@ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule public ExpectedException expectedException = ExpectedException.none();
@Rule
public final TestingFatalErrorHandlerResource testingFatalErrorHandlerResource ... |
Improve the code a bit: ```java final TableColumn tableColumn = tableSchema.getTableColumns().get(i); final String fieldName = tableColumn.getName(); final DataType fieldType = tableColumn.getType(); final boolean isGeneratedColumn = tableColumn.isGenerated(); ``` We do know it's safe to call `tableSchema.getTableColu... | public static TableSchema deriveTableSinkSchema(DescriptorProperties properties) {
TableSchema.Builder builder = TableSchema.builder();
TableSchema tableSchema = properties.getTableSchema(SCHEMA);
for (int i = 0; i < tableSchema.getFieldCount(); i++) {
TypeInformation t = tableSchema.getFieldTypes()[i];
Str... | boolean isGeneratedColumn = tableColumn.isPresent() && tableColumn.get().isGenerated(); | public static TableSchema deriveTableSinkSchema(DescriptorProperties properties) {
TableSchema.Builder builder = TableSchema.builder();
TableSchema tableSchema = properties.getTableSchema(SCHEMA);
for (int i = 0; i < tableSchema.getFieldCount(); i++) {
final TableColumn tableColumn = tableSchema.getTableColumn... | class SchemaValidator implements DescriptorValidator {
private final boolean isStreamEnvironment;
private final boolean supportsSourceTimestamps;
private final boolean supportsSourceWatermarks;
public SchemaValidator(boolean isStreamEnvironment, boolean supportsSourceTimestamps,
boolean supportsSourceWatermark... | class SchemaValidator implements DescriptorValidator {
private final boolean isStreamEnvironment;
private final boolean supportsSourceTimestamps;
private final boolean supportsSourceWatermarks;
public SchemaValidator(boolean isStreamEnvironment, boolean supportsSourceTimestamps,
boolean supportsSourceWatermark... |
It would be nice if this were another constant. We could have `DEFAULT_GROUPING_FACTOR_BOUNDED` and `DEFAULT_GROUPING_FACTOR_UNBOUNDED`. It doesn't need to be done here, could be in a follow-up PR. | public SpannerWriteResult expand(PCollection<MutationGroup> input) {
PCollection<Void> schemaSeed =
input.getPipeline().apply("Create Seed", Create.of((Void) null));
if (spec.getSchemaReadySignal() != null) {
schemaSeed = schemaSeed.apply("Wait for schema", Wait.on(spec.ge... | : 1), | public SpannerWriteResult expand(PCollection<MutationGroup> input) {
PCollection<Void> schemaSeed =
input.getPipeline().apply("Create Seed", Create.of((Void) null));
if (spec.getSchemaReadySignal() != null) {
schemaSeed = schemaSeed.apply("Wait for schema", Wait.on(spec.ge... | class WriteGrouped
extends PTransform<PCollection<MutationGroup>, SpannerWriteResult> {
private final Write spec;
private static final TupleTag<MutationGroup> BATCHABLE_MUTATIONS_TAG =
new TupleTag<MutationGroup>("batchableMutations") {};
private static final TupleTag<Iterable<MutationGroup>> ... | class WriteGrouped
extends PTransform<PCollection<MutationGroup>, SpannerWriteResult> {
private final Write spec;
private static final TupleTag<MutationGroup> BATCHABLE_MUTATIONS_TAG =
new TupleTag<MutationGroup>("batchableMutations") {};
private static final TupleTag<Iterable<MutationGroup>> ... |
I don't have context about the current design choice of propagating the error to the session processor, may be inherited from the legacy library. | Mono<ServiceBusReceiveLink> getActiveLink() {
if (this.receiveLink != null) {
return Mono.just(this.receiveLink);
}
return Mono.defer(() -> createSessionReceiveLink()
.flatMap(link -> link.getEndpointStates()
.filter(e -> e == AmqpEndpointState.ACTIVE)
... | && ((AmqpException) failure).isTransient()) { | Mono<ServiceBusReceiveLink> getActiveLink() {
if (this.receiveLink != null) {
return Mono.just(this.receiveLink);
}
return Mono.defer(() -> createSessionReceiveLink()
.flatMap(link -> link.getEndpointStates()
.filter(e -> e == AmqpEndpointState.ACTIVE)
... | class ServiceBusSessionManager implements AutoCloseable {
private static final Duration SLEEP_DURATION_ON_ACCEPT_SESSION_EXCEPTION = Duration.ofMinutes(1);
private static final ClientLogger LOGGER = new ClientLogger(ServiceBusSessionManager.class);
private final String entityPath;
private final Me... | class ServiceBusSessionManager implements AutoCloseable {
private static final Duration SLEEP_DURATION_ON_ACCEPT_SESSION_EXCEPTION = Duration.ofMinutes(1);
private static final String TRACKING_ID_KEY = "trackingId";
private static final ClientLogger LOGGER = new ClientLogger(ServiceBusSessionManager.c... |
```suggestion Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); ``` | public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) {
if (identifier == null) {
return null;
}
assertSingleType(identifier);
String rawId = identifier.getRawId();
CommunicationIdentifierModelKind kind = (identifier.getKind() != null... | Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); | 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... |
not really, the destination is an address. It can be seen as a _classic_ queue or topic depending on the method used (send / request vs. publish) | protected String destinationKind(final Message message) {
return "topic";
} | return "topic"; | protected String destinationKind(final Message message) {
return message.isSend() ? "queue" : "topic";
} | class EventBusAttributesExtractor extends MessagingAttributesExtractor<Message, Message> {
private final MessageOperation operation;
public EventBusAttributesExtractor(final MessageOperation operation) {
this.operation = operation;
}
@Override
public MessageOperatio... | class EventBusAttributesExtractor extends MessagingAttributesExtractor<Message, Message> {
private final MessageOperation operation;
public EventBusAttributesExtractor(final MessageOperation operation) {
this.operation = operation;
}
@Override
public MessageOperatio... |
@pedroigor @boosey Hi. I think there should be some code followed by a custom header indicating it is to do with the XHR. Otherwise SPA will try to reload even if it is a genuine `401` (whenever we decide to return `401`, example, we return `401` in case the code flow fails to complete). To be honest I'm not sure it s... | public AuthenticationRedirectException(Boolean autoRedirect, String redirectUri) {
this(autoRedirect ? 302 : 444, redirectUri);
} | this(autoRedirect ? 302 : 444, redirectUri); | public AuthenticationRedirectException(Boolean autoRedirect, String redirectUri) {
this(autoRedirect ? 302 : 444, redirectUri);
} | class AuthenticationRedirectException extends RuntimeException {
int code;
String redirectUri;
public AuthenticationRedirectException(String redirectUri) {
this(302, redirectUri);
}
public AuthenticationRedirectException(int code, String redirectUri) {
this.code = code;
th... | class AuthenticationRedirectException extends RuntimeException {
int code;
String redirectUri;
public AuthenticationRedirectException(String redirectUri) {
this(302, redirectUri);
}
public AuthenticationRedirectException(int code, String redirectUri) {
this.code = code;
th... |
@challengeof Can we rename `c` to `firstChar`? And put constant on the left condition? | private static Object convertBooleanValue(final Object value) {
if (value instanceof Boolean) {
return value;
}
String stringVal = value.toString();
if (stringVal.length() > 0) {
int c = Character.toLowerCase(stringVal.charAt(0));
return c == 't' || c ... | return c == 't' || c == 'y' || c == '1' || "-1".equals(stringVal); | private static Object convertBooleanValue(final Object value) {
if (value instanceof Boolean) {
return value;
}
String stringVal = value.toString();
if (stringVal.length() > 0) {
int firstChar = Character.toLowerCase(stringVal.charAt(0));
return 't' ==... | class == value.getClass()) {
return adjustBigDecimalResult((BigDecimal) value, needScale, scale);
} | class == value.getClass()) {
return adjustBigDecimalResult((BigDecimal) value, needScale, scale);
} |
If we consider security best practices, is it ok to have the `keyPassword` in error message and logs? @ldclakmal | public static Object decodePrivateKey(Object keyStoreValue, String keyAlias, String keyPassword) {
MapValue<String, Object> keyStore = (MapValue<String, Object>) keyStoreValue;
PrivateKey privateKey;
File keyStoreFile = new File(CryptoUtils.substituteVariables(
keyStore.get(Con... | "] and key password: [" + keyPassword + "]"); | public static Object decodePrivateKey(Object keyStoreValue, String keyAlias, String keyPassword) {
MapValue<String, Object> keyStore = (MapValue<String, Object>) keyStoreValue;
PrivateKey privateKey;
File keyStoreFile = new File(CryptoUtils.substituteVariables(
keyStore.get(Con... | class Decode {
@SuppressWarnings("unchecked")
@SuppressWarnings("unchecked")
public static Object decodePublicKey(Object keyStoreValue, String keyAlias) {
MapValue<String, Object> keyStore = (MapValue<String, Object>) keyStoreValue;
File keyStoreFile = new File(
Crypt... | class Decode {
@SuppressWarnings("unchecked")
@SuppressWarnings("unchecked")
public static Object decodePublicKey(Object keyStoreValue, String keyAlias) {
MapValue<String, Object> keyStore = (MapValue<String, Object>) keyStoreValue;
File keyStoreFile = new File(
Crypt... |
Can this method call the method on L204 | public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(String id) {
return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(id), null, context));
} | return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(id), null, context)); | public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(String id) {
return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(id), null, context));
} | class CosmosAsyncClient implements Closeable {
private final Configs configs;
private final AsyncDocumentClient asyncDocumentClient;
private final String serviceEndpoint;
private final String keyOrResourceToken;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLeve... | class CosmosAsyncClient implements Closeable {
private final Configs configs;
private final AsyncDocumentClient asyncDocumentClient;
private final String serviceEndpoint;
private final String keyOrResourceToken;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLeve... |
Should we use `@RepeatedTest(100)` instead? | void testPost() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; ++i) {
given()
.header("Authorization", "Basic am9objpqb2hu")
.body("Bill")
.contentType(ContentType.TEXT)
... | void testPost() {
given()
.header("Authorization", "Basic am9objpqb2hu")
.body("Bill")
.contentType(ContentType.TEXT)
.when()
.post("/foo/")
.then()
.statusCode(200)
... | class BaseAuthTest {
@Test
@Test
void testGet() {
given()
.header("Authorization", "Basic am9objpqb2hu")
.when()
.get("/foo/")
.then()
.statusCode(200)
.body(is("hello"));
}
} | class BaseAuthTest {
@Test
@RepeatedTest(100)
@Test
void testGet() {
given()
.header("Authorization", "Basic am9objpqb2hu")
.when()
.get("/foo/")
.then()
.statusCode(200)
.body(is("hello"));
... | |
is ctx.getText() giving the orginal string value. ? ```suggestion ctx.getText()); ``` | public void exitSimpleLiteral(BallerinaParser.SimpleLiteralContext ctx) {
if (ctx.exception != null) {
return;
}
TerminalNode node;
DiagnosticPos pos = getCurrentPos(ctx);
Set<Whitespace> ws = getWS(ctx);
Object value;
BallerinaParser.IntegerLiteralCo... | getOriginalIntegerValue(integerLiteralContext)); | public void exitSimpleLiteral(BallerinaParser.SimpleLiteralContext ctx) {
if (ctx.exception != null) {
return;
}
TerminalNode node;
DiagnosticPos pos = getCurrentPos(ctx);
Set<Whitespace> ws = getWS(ctx);
Object value;
BallerinaParser.IntegerLiteralCo... | class BLangParserListener extends BallerinaParserBaseListener {
private static final String KEYWORD_PUBLIC = "public";
private static final String KEYWORD_EXTERN = "extern";
private BLangPackageBuilder pkgBuilder;
private BDiagnosticSource diagnosticSrc;
private BLangDiagnosticLog dlog;
privat... | class BLangParserListener extends BallerinaParserBaseListener {
private static final String KEYWORD_PUBLIC = "public";
private static final String KEYWORD_EXTERN = "extern";
private BLangPackageBuilder pkgBuilder;
private BDiagnosticSource diagnosticSrc;
private BLangDiagnosticLog dlog;
privat... |
Please use `null == name` and `0 == name.length()` | public ShardingSphereSavepoint(final String name) throws SQLException {
if (name == null || name.length() == 0) {
throw new SQLException("Savepoint name can not be NULL or empty");
}
this.savepointName = name;
} | if (name == null || name.length() == 0) { | public ShardingSphereSavepoint(final String name) throws SQLException {
if (null == name || 0 == name.length()) {
throw new SQLException("Savepoint name can not be NULL or empty");
}
savepointName = name;
} | class ShardingSphereSavepoint implements Savepoint {
private final String savepointName;
public ShardingSphereSavepoint() {
this.savepointName = getUniqueId();
}
@Override
public int getSavepointId() throws SQLException {
throw new SQLException("Only named sa... | class ShardingSphereSavepoint implements Savepoint {
private final String savepointName;
public ShardingSphereSavepoint() {
savepointName = getUniqueId();
}
@Override
public int getSavepointId() throws SQLException {
throw new SQLException("Only named savepoi... |
De-serialization of polymorphic types are handled using Jackson annotations. See this models https://github.com/Azure/azure-sdk-for-java/blob/e6771250bb50c5b38a301afed06afb88c6737a08/eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/customization/models/ShippingInfo.java#L15 | public EventGridSubscriber() {
this.defaultSerializerAdapter = new AzureJacksonAdapter();
this.eventTypeToEventDataMapping = new HashMap<>();
} | this.defaultSerializerAdapter = new AzureJacksonAdapter(); | public EventGridSubscriber() {
this.defaultSerializerAdapter = new AzureJacksonAdapter();
this.eventTypeToEventDataMapping = new HashMap<>();
} | class EventGridSubscriber {
/**
* The default adapter for to be used for de-serializing the events
*/
private final AzureJacksonAdapter defaultSerializerAdapter;
/**
* The map containing user defined mapping of eventType to Java model type
*/
private Map<String, Type> eventTypeToEven... | class EventGridSubscriber {
/**
* The default adapter to be used for de-serializing the events.
*/
private final AzureJacksonAdapter defaultSerializerAdapter;
/**
* The map containing user defined mapping of eventType to Java model type.
*/
private Map<String, Type> eventTypeToEventD... |
> IOException may contian sensitive message. The old logic seems doesn't want to return it to client. Maybe it's reasonable? got it. make sense | protected void handleQuery() {
MetricRepo.COUNTER_REQUEST_ALL.increase(1L);
ctx.getAuditEventBuilder().reset();
ctx.getAuditEventBuilder()
.setTimestamp(System.currentTimeMillis())
.setClientIp(ctx.getRemoteIP())
.setUser(ctx.getQualifiedUser())
... | ctx.getState().setError("StarRocks process failed"); | protected void handleQuery() {
MetricRepo.COUNTER_REQUEST_ALL.increase(1L);
ctx.getAuditEventBuilder().reset();
ctx.getAuditEventBuilder()
.setTimestamp(System.currentTimeMillis())
.setClientIp(ctx.getRemoteIP())
.setUser(ctx.getQualifiedUser())
... | class HttpConnectProcessor extends ConnectProcessor {
private static final Logger LOG = LogManager.getLogger(HttpConnectProcessor.class);
public HttpConnectProcessor(ConnectContext context) {
super(context);
}
@Override
@Override
public void processOnce() throws IOException {
... | class HttpConnectProcessor extends ConnectProcessor {
private static final Logger LOG = LogManager.getLogger(HttpConnectProcessor.class);
public HttpConnectProcessor(ConnectContext context) {
super(context);
}
@Override
@Override
public void processOnce() throws IOException {
... |
Isn't this null check redundant? There's already one in https://github.com/ballerina-platform/ballerina-lang/pull/36837/files#diff-abafd09e4c17786eb7b550f8eccbeb794ce71bff4e383bdaa9b7ecf203b169aeR1318 | public void visit(BLangWorkerFlushExpr workerFlushExpr) {
if (workerFlushExpr.workerSymbol == null) {
return;
}
addIfSameSymbol(workerFlushExpr.workerSymbol, workerFlushExpr.workerIdentifier.pos);
} | if (workerFlushExpr.workerSymbol == null) { | public void visit(BLangWorkerFlushExpr workerFlushExpr) {
if (workerFlushExpr.workerIdentifier == null) {
return;
}
addIfSameSymbol(workerFlushExpr.workerSymbol, workerFlushExpr.workerIdentifier.pos);
} | class ReferenceFinder extends BaseVisitor {
private final boolean withDefinition;
private List<Location> referenceLocations;
private BSymbol targetSymbol;
public ReferenceFinder(boolean withDefinition) {
this.withDefinition = withDefinition;
}
public List<Location> findReferences(BLan... | class ReferenceFinder extends BaseVisitor {
private final boolean withDefinition;
private List<Location> referenceLocations;
private BSymbol targetSymbol;
public ReferenceFinder(boolean withDefinition) {
this.withDefinition = withDefinition;
}
public List<Location> findReferences(BLan... |
Ok, never mind. I was thinking to avoid copying in and copying out of `memo` multiple times. Let's refactor this when we have more similar cases in the future. | private Memo rewrite(Plan plan) {
Plan normalizedPlan = PlanRewriter.topDownRewrite(plan, new ConnectContext(), new NormalizeExpressions());
return PlanRewriter.topDownRewriteMemo(normalizedPlan, new ConnectContext(), new PushPredicateThroughJoin());
} | Plan normalizedPlan = PlanRewriter.topDownRewrite(plan, new ConnectContext(), new NormalizeExpressions()); | private Memo rewrite(Plan plan) {
Plan normalizedPlan = PlanRewriter.topDownRewrite(plan, new ConnectContext(), new ExpressionNormalization());
return PlanRewriter.topDownRewriteMemo(normalizedPlan, new ConnectContext(), new PushPredicateThroughJoin());
} | class PushDownPredicateTest {
private Table student;
private Table score;
private Table course;
private Plan rStudent;
private Plan rScore;
private Plan rCourse;
/**
* ut before.
*/
@BeforeAll
public final void beforeAll() {
student = new Table(0L, "student", Tab... | class PushDownPredicateTest {
private Table student;
private Table score;
private Table course;
private Plan rStudent;
private Plan rScore;
private Plan rCourse;
/**
* ut before.
*/
@BeforeAll
public final void beforeAll() {
student = new Table(0L, "student", Tab... |
Well, the purpose of the fix was deleting files. As there haven't been any test for that so far I added them to show that now all files are deleted properly with HS cleaning feature enabled. | private void runArchiveExpirationTest(boolean cleanupExpiredJobs) throws Exception {
int numExpiredJobs = cleanupExpiredJobs ? 1 : 0;
int numJobs = 3;
for (int x = 0; x < numJobs; x++) {
runJob();
}
waitForArchivesCreation(numJobs);
CountDownLatch numExpectedArchivedJobs = new CountDownLatch(numJobs);
... | assertHSFilesExistence(jobIdToDelete, !cleanupExpiredJobs); | private void runArchiveExpirationTest(boolean cleanupExpiredJobs) throws Exception {
int numExpiredJobs = cleanupExpiredJobs ? 1 : 0;
int numJobs = 3;
for (int x = 0; x < numJobs; x++) {
runJob();
}
waitForArchivesCreation(numJobs);
CountDownLatch numExpectedArchivedJobs = new CountDownLatch(numJobs);
... | class HistoryServerTest extends TestLogger {
private static final JsonFactory JACKSON_FACTORY = new JsonFactory()
.enable(JsonGenerator.Feature.AUTO_CLOSE_TARGET)
.disable(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.enable(Deserializatio... | class HistoryServerTest extends TestLogger {
private static final JsonFactory JACKSON_FACTORY = new JsonFactory()
.enable(JsonGenerator.Feature.AUTO_CLOSE_TARGET)
.disable(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.enable(Deserializatio... |
shoudl we count to show on status page? | private boolean addCommitToStream(Commit commit, CommitWorkStream commitStream) {
Preconditions.checkNotNull(commit);
if (commit.work().isFailed()) {
return true;
}
final ComputationState state = commit.computationState();
final Windmill.WorkItemCommitRequest request = commit.request();
... | return true; | private boolean addCommitToStream(Commit commit, CommitWorkStream commitStream) {
Preconditions.checkNotNull(commit);
if (commit.work().isFailed()) {
return true;
}
final ComputationState state = commit.computationState();
final Windmill.WorkItemCommitRequest request = commit.request();
... | class with beam_fn_api enabled",
StreamingDataflowWorker.class.getSimpleName());
StreamingDataflowWorker worker =
StreamingDataflowWorker.fromDataflowWorkerHarnessOptions(options);
MetricsEnvironment.setProcessWideContainer(new MetricsLogger(null));
StreamingStepMetricsCont... | class with beam_fn_api enabled",
StreamingDataflowWorker.class.getSimpleName());
StreamingDataflowWorker worker =
StreamingDataflowWorker.fromDataflowWorkerHarnessOptions(options);
MetricsEnvironment.setProcessWideContainer(new MetricsLogger(null));
StreamingStepMetricsCont... |
```suggestion LOG.warn("Keys size is not equal to column size. Error={}", e.getMessage()); ``` | private ArrayList<DropPartitionClause> getDropPartitionClause(OlapTable olapTable, Column partitionColumn, String partitionFormat) {
ArrayList<DropPartitionClause> dropPartitionClauses = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
DynamicPartitionProperty dynamicPartitionPrope... | LOG.warn("Keys size is not equal to column size. Error=" + e.getMessage()); | private ArrayList<DropPartitionClause> getDropPartitionClause(OlapTable olapTable, Column partitionColumn, String partitionFormat) {
ArrayList<DropPartitionClause> dropPartitionClauses = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
DynamicPartitionProperty dynamicPartitionPrope... | class DynamicPartitionScheduler extends MasterDaemon {
private static final Logger LOG = LogManager.getLogger(DynamicPartitionScheduler.class);
public static final String LAST_SCHEDULER_TIME = "lastSchedulerTime";
public static final String LAST_UPDATE_TIME = "lastUpdateTime";
public static final String... | class DynamicPartitionScheduler extends MasterDaemon {
private static final Logger LOG = LogManager.getLogger(DynamicPartitionScheduler.class);
public static final String LAST_SCHEDULER_TIME = "lastSchedulerTime";
public static final String LAST_UPDATE_TIME = "lastUpdateTime";
public static final String... |
Shall we combine the above two lines? | public void onMessage(HTTPCarbonMessage inboundMessage) {
try {
HttpResource httpResource;
if (accessed(inboundMessage)) {
if (inboundMessage.getProperty(HTTP_RESOURCE) instanceof String) {
if (inboundMessage.getProperty(HTTP_RESOURCE).equals(
... | WebSubSubscriberConstants.ANNOTATED_TOPIC)) { | public void onMessage(HTTPCarbonMessage inboundMessage) {
try {
HttpResource httpResource;
if (accessed(inboundMessage)) {
if (inboundMessage.getProperty(HTTP_RESOURCE) instanceof String) {
if (inboundMessage.getProperty(HTTP_RESOURCE).equals(ANNOTATED... | class BallerinaWebSubConnectionListener extends BallerinaHTTPConnectorListener {
private static final Logger log = LoggerFactory.getLogger(BallerinaWebSubConnectionListener.class);
private WebSubServicesRegistry webSubServicesRegistry;
private PrintStream console = System.out;
public BallerinaWebSubCo... | class BallerinaWebSubConnectionListener extends BallerinaHTTPConnectorListener {
private static final Logger log = LoggerFactory.getLogger(BallerinaWebSubConnectionListener.class);
private WebSubServicesRegistry webSubServicesRegistry;
private PrintStream console = System.out;
public BallerinaWebSubCo... |
Here you can easily use TypeTags for type comparisons. | private static void checkRetryStmtValidity(RetryStmt stmt) {
StatementKind parentStmtType = stmt.getParent().getKind();
if (StatementKind.FAILED_BLOCK != parentStmtType) {
BLangExceptionHelper.throwSemanticError(stmt, SemanticErrors.INVALID_RETRY_STMT_LOCATION);
}
... | if (TypeConstants.INT_TNAME.equals(((BasicLiteral) retryCountExpr).getTypeName().getName())) { | private static void checkRetryStmtValidity(RetryStmt stmt) {
StatementKind parentStmtType = stmt.getParent().getKind();
if (StatementKind.FAILED_BLOCK != parentStmtType) {
BLangExceptionHelper.throwSemanticError(stmt, SemanticErrors.INVALID_RETRY_STMT_LOCATION);
}
... | class SemanticAnalyzer implements NodeVisitor {
private static final String ERRORS_PACKAGE = "ballerina.lang.errors";
private static final String BALLERINA_CAST_ERROR = "TypeCastError";
private static final String BALLERINA_CONVERSION_ERROR = "TypeConversionError";
private static final String BALLERINA_... | class SemanticAnalyzer implements NodeVisitor {
private static final String ERRORS_PACKAGE = "ballerina.lang.errors";
private static final String BALLERINA_CAST_ERROR = "TypeCastError";
private static final String BALLERINA_CONVERSION_ERROR = "TypeConversionError";
private static final String BALLERINA_... |
adaptive scheduler -> dynamic graph This is more accurate. | public boolean canBeReleased() {
if (releasedPartitionGroups.size()
!= edgeManager.getNumberOfConsumedPartitionGroupsById(partitionId)) {
return false;
}
for (JobVertexID jobVertexID : consumerVertices) {
if (!producer.getExecutio... | public boolean canBeReleased() {
if (releasablePartitionGroups.size()
!= edgeManager.getNumberOfConsumedPartitionGroupsById(partitionId)) {
return false;
}
for (JobVertexID jobVertexId : totalResult.getConsumerVertices()) {
if (!p... | class IntermediateResultPartition {
private static final int UNKNOWN = -1;
private final IntermediateResult totalResult;
private final ExecutionVertex producer;
private final IntermediateResultPartitionID partitionId;
private final EdgeManager edgeManager;
/** Number of subpartitions. Init... | class IntermediateResultPartition {
private static final int UNKNOWN = -1;
private final IntermediateResult totalResult;
private final ExecutionVertex producer;
private final IntermediateResultPartitionID partitionId;
private final EdgeManager edgeManager;
/** Number of subpartitions. Init... | |
No? The only thing I can find that calls this code is ONNX-models, but they also explicitly throw if the type is URI ... | public FileReference addUri(String uri, Path path) {
throw new UnsupportedOperationException("URI type is not supported");
/* TODO: this needs to be super-restricted if the config server should ever do this.
try (TmpDir tmp = new TmpDir()) {
return addFile(download(uri, tmp.dir, path... | throw new UnsupportedOperationException("URI type is not supported"); | public FileReference addUri(String uri, Path path) {
throw new UnsupportedOperationException("URI type is not supported");
/* TODO: this needs to be super-restricted if the config server should ever do this.
try (TmpDir tmp = new TmpDir()) {
return addFile(download(uri, tmp.dir, path... | class ApplicationFileManager implements AddFileInterface {
private final File applicationDir;
private final FileDirectory fileDirectory;
ApplicationFileManager(File applicationDir, FileDirectory fileDirectory) {
this.applicationDir = applicationDir;
this.fileDirectory = fileDirectory;
... | class ApplicationFileManager implements AddFileInterface {
private final File applicationDir;
private final FileDirectory fileDirectory;
ApplicationFileManager(File applicationDir, FileDirectory fileDirectory) {
this.applicationDir = applicationDir;
this.fileDirectory = fileDirectory;
... |
Ah. I totally missed the second one was not a `else`. Probably better to initialize that one to `Collections.emptyList()` then. That way, you don't have to special case the null. Sorry about that. | private boolean restJsonSupportNeeded(CombinedIndexBuildItem indexBuildItem, DotName mediaTypeAnnotation) {
for (AnnotationInstance annotationInstance : indexBuildItem.getIndex().getAnnotations(mediaTypeAnnotation)) {
final AnnotationValue annotationValue = annotationInstance.value();
if... | List<String> mediaTypes = null; | private boolean restJsonSupportNeeded(CombinedIndexBuildItem indexBuildItem, DotName mediaTypeAnnotation) {
for (AnnotationInstance annotationInstance : indexBuildItem.getIndex().getAnnotations(mediaTypeAnnotation)) {
final AnnotationValue annotationValue = annotationInstance.value();
if... | class ResteasyCommonConfigGzip {
/**
* If gzip is enabled
*/
@ConfigItem
public boolean enabled;
/**
* Maximum deflated file bytes size
* <p>
* If the limit is exceeded, Resteasy will return Response
* with status 413("Request Entity ... | class ResteasyCommonConfigGzip {
/**
* If gzip is enabled
*/
@ConfigItem
public boolean enabled;
/**
* Maximum deflated file bytes size
* <p>
* If the limit is exceeded, Resteasy will return Response
* with status 413("Request Entity ... |
nit: We should not strictly cast it to ArrayList<String> here, instead keep it open to generic `List<String>` here. ``` List<String> expandParam = ((Collection<?>) parameters[paramIndex]).stream().map(Object::toString).collect(Collectors.toList()); ``` | public Object execute(final Object[] parameters) {
final CosmosParameterAccessor accessor = new CosmosParameterParameterAccessor(getQueryMethod(), parameters);
final ResultProcessor processor = getQueryMethod().getResultProcessor().withDynamicProjection(accessor);
String expandedQuery = query;
... | ArrayList<String> expandParam = (ArrayList<String>) ((Collection<?>) parameters[paramIndex]).stream() | public Object execute(final Object[] parameters) {
final CosmosParameterAccessor accessor = new CosmosParameterParameterAccessor(getQueryMethod(), parameters);
final ResultProcessor processor = getQueryMethod().getResultProcessor().withDynamicProjection(accessor);
String expandedQuery = query;
... | class StringBasedCosmosQuery extends AbstractCosmosQuery {
private static final Pattern COUNT_QUERY_PATTERN = Pattern.compile("^\\s*select\\s+value\\s+count.*", Pattern.CASE_INSENSITIVE);
private final String query;
/**
* Constructor
* @param queryMethod the CosmosQueryMethod
* @param dbOpe... | class StringBasedCosmosQuery extends AbstractCosmosQuery {
private static final Pattern COUNT_QUERY_PATTERN = Pattern.compile("^\\s*select\\s+value\\s+count.*", Pattern.CASE_INSENSITIVE);
private final String query;
/**
* Constructor
* @param queryMethod the CosmosQueryMethod
* @param dbOpe... |
I'm not sure we should use Optional here if we pass the null further to Options() anyway. Notice that in case when optional is empty the defaultValue is assigned to null anyway | private static List<Option> extractOptions(boolean isPython) {
List<Option> options = new ArrayList<>();
for (Method method : FlinkPipelineOptions.class.getDeclaredMethods()) {
String name;
String description;
String defaultValue = null;
name = method.getName();
if (name.matches("^... | Optional<String> defaultValueFromAnnotation = getDefaultValueFromAnnotation(method); | private static List<Option> extractOptions(boolean isPython) {
List<Option> options = new ArrayList<>();
for (Method method : FlinkPipelineOptions.class.getDeclaredMethods()) {
String name;
String description;
String defaultValue = null;
name = method.getName();
if (name.matches("^... | class methods.
*/ | class methods.
*/ |
This PR now looks great, after we fix this one, it is time to merge it, I suppose. | public static List<SqlNode> convertOrderByItems(final Collection<OrderByItemSegment> orderByItems) {
List<SqlNode> sqlNodes = Lists.newArrayList();
for (OrderByItemSegment orderByItemSegment : orderByItems) {
Optional<SqlNode> optional = Optional.empty();
if (orderByItemSegment i... | List<SqlNode> sqlNodes = Lists.newArrayList(); | public static List<SqlNode> convertOrderByItems(final Collection<OrderByItemSegment> orderByItems) {
List<SqlNode> sqlNodes = Lists.newArrayList();
for (OrderByItemSegment orderByItemSegment : orderByItems) {
Optional<SqlNode> optional = Optional.empty();
if (orderByItemSegment i... | class SqlNodeConverterUtil {
/**
* Convert order by items.
* @param orderByItems order by item list.
* @return a collection of order by item <code>SqlNode</code>
*/
} | class SqlNodeConverterUtil {
/**
* Convert order by items.
* @param orderByItems order by item list.
* @return a collection of order by item <code>SqlNode</code>
*/
} |
`cost={}s`, same as the info log. | private void schedule() {
for (Iterator<Map.Entry<PartitionIdentifier, CompactionContext>> iterator = runningCompactions.entrySet().iterator();
iterator.hasNext(); ) {
Map.Entry<PartitionIdentifier, CompactionContext> entry = iterator.next();
PartitionIdentifier ... | LOG.debug("Removed published compaction. {} cost={}ms running={}", context.getDebugString(), | private void schedule() {
for (Iterator<Map.Entry<PartitionIdentifier, CompactionContext>> iterator = runningCompactions.entrySet().iterator();
iterator.hasNext(); ) {
Map.Entry<PartitionIdentifier, CompactionContext> entry = iterator.next();
PartitionIdentifier ... | class CompactionScheduler extends Daemon {
private static final Logger LOG = LogManager.getLogger(CompactionScheduler.class);
private static final String HOST_NAME = FrontendOptions.getLocalHostAddress();
private static final long LOOP_INTERVAL_MS = 500L;
private static final long TXN_TIMEOUT_SECOND = 8... | class CompactionScheduler extends Daemon {
private static final Logger LOG = LogManager.getLogger(CompactionScheduler.class);
private static final String HOST_NAME = FrontendOptions.getLocalHostAddress();
private static final long LOOP_INTERVAL_MS = 500L;
private static final long TXN_TIMEOUT_SECOND = 8... |
> Now if this deferred creation actually gained something that would be a different story. But it does not here. That I can see anyway. Please correct me if I missed something | private void setUpDeploymentConfiguration() {
if (project.getConfigurations().findByName(this.deploymentConfigurationName) == null) {
project.getConfigurations().register(this.deploymentConfigurationName, configuration -> {
Configuration enforcedPlatforms = this.getPlatformConfigurat... | project.getConfigurations().register(this.deploymentConfigurationName, configuration -> { | private void setUpDeploymentConfiguration() {
if (project.getConfigurations().findByName(this.deploymentConfigurationName) == null) {
project.getConfigurations().create(this.deploymentConfigurationName, configuration -> {
Configuration enforcedPlatforms = this.getPlatformConfiguratio... | class ApplicationDeploymentClasspathBuilder {
private static String getRuntimeConfigName(LaunchMode mode, boolean base) {
final StringBuilder sb = new StringBuilder();
sb.append("quarkus");
if (mode == LaunchMode.DEVELOPMENT) {
sb.append("Dev");
} else if (mode == Launch... | class ApplicationDeploymentClasspathBuilder {
private static String getRuntimeConfigName(LaunchMode mode, boolean base) {
final StringBuilder sb = new StringBuilder();
sb.append("quarkus");
if (mode == LaunchMode.DEVELOPMENT) {
sb.append("Dev");
} else if (mode == Launch... |
Shall we add a test case for this change? | public void onMessage(HttpCarbonMessage inboundMessage) {
try {
HttpResource httpResource;
if (accessed(inboundMessage)) {
httpResource = (HttpResource) inboundMessage.getProperty(HTTP_RESOURCE);
extractPropertiesAndStartResourceExecution(inboundMessage, h... | inboundMessage.removeInboundContentListener(); | public void onMessage(HttpCarbonMessage inboundMessage) {
try {
HttpResource httpResource;
if (accessed(inboundMessage)) {
httpResource = (HttpResource) inboundMessage.getProperty(HTTP_RESOURCE);
extractPropertiesAndStartResourceExecution(inboundMessage, h... | class BallerinaHTTPConnectorListener implements HttpConnectorListener {
private static final Logger log = LoggerFactory.getLogger(BallerinaHTTPConnectorListener.class);
protected static final String HTTP_RESOURCE = "httpResource";
private final HTTPServicesRegistry httpServicesRegistry;
protected fin... | class BallerinaHTTPConnectorListener implements HttpConnectorListener {
private static final Logger log = LoggerFactory.getLogger(BallerinaHTTPConnectorListener.class);
protected static final String HTTP_RESOURCE = "httpResource";
private final HTTPServicesRegistry httpServicesRegistry;
protected fin... |
Is Funqy layered on top of this? One thing to consider is that Funqy needs to be consistent across all cloud platform on what JSON marshalling layer it uses. We can't use GSON for Funqy GCF and Jackson for Funqy Lambda. | public void accept(String event, Context context) throws Exception {
if (!started) {
throw new IOException(deploymentStatus);
}
if ((delegate == null && rawDelegate == null) || (delegate != null && rawDelegate != null)) {
throw new IOException("We didn't found a... | Object eventObj = mapper.readValue(event, parameterType); | public void accept(String event, Context context) throws Exception {
if (!started) {
throw new IOException(deploymentStatus);
}
if ((delegate == null && rawDelegate == null) || (delegate != null && rawDelegate != null)) {
throw new IOException("We didn't found a... | class QuarkusBackgroundFunction implements RawBackgroundFunction {
protected static final String deploymentStatus;
protected static boolean started = false;
private static volatile BackgroundFunction delegate;
private static volatile Class<?> parameterType;
private static volatile RawBackgroundFun... | class QuarkusBackgroundFunction implements RawBackgroundFunction {
protected static final String deploymentStatus;
protected static boolean started = false;
private static volatile BackgroundFunction delegate;
private static volatile Class<?> parameterType;
private static volatile RawBackgroundFun... |
Yes. I ran the live test to record the response but found it is no longer a valid test. | static AnalyzeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult2() {
TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(156, 1);
final HealthcareEntity healthcareEntity1 = new HealthcareEntity();
HealthcareEntityPropertiesHelper.setText(healthcareEnti... | HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "ST depressions in the anterior lateral leads"); | static AnalyzeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult2() {
TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(156, 1);
final HealthcareEntity healthcareEntity1 = new HealthcareEntity();
HealthcareEntityPropertiesHelper.setText(healthcareEnti... | class TestUtils {
private static final String DEFAULT_MODEL_VERSION = "2019-10-01";
static final OffsetDateTime TIME_NOW = OffsetDateTime.now();
static final String INVALID_URL = "htttttttps:
static final String VALID_HTTPS_LOCALHOST = "https:
static final String FAKE_API_KEY = "1234567890";
st... | class TestUtils {
private static final String DEFAULT_MODEL_VERSION = "2019-10-01";
static final OffsetDateTime TIME_NOW = OffsetDateTime.now();
static final String INVALID_URL = "htttttttps:
static final String VALID_HTTPS_LOCALHOST = "https:
static final String FAKE_API_KEY = "1234567890";
st... |
Don't we need to start context for on fail clause? | 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 typeDescriptorNode = parseTypeDescriptor(ParserRuleContext.TYPE_DESC_IN_TYPE_BINDING_PATTERN, | 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.DEFAULT;
protected BallerinaParser(AbstractTokenReader tokenReader) {
super(tokenReader, new BallerinaParserErrorHandler(tokenReader));
}
/**
* Start parsing ... | 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... |
We should clarify in the comment that this in an optimization which only works for embedded execution or when the user code has been added to the Flink classpath (e.g. via the lib folder). Potentially we also need to invert class loading behavior via the Flink config to ensure that the parent is searched first. | private void scheduleRelease(JobInfo jobInfo) {
WrappedContext wrapper = getCache().get(jobInfo.jobId());
Preconditions.checkState(
wrapper != null, "Releasing context for unknown job: " + jobInfo.jobId());
PipelineOptions pipelineOptions =
PipelineOptionsTranslation.fromProto(jobInfo.pipel... | if (this.getClass().getClassLoader() != ExecutionEnvironment.class.getClassLoader()) { | private void scheduleRelease(JobInfo jobInfo) {
WrappedContext wrapper = getCache().get(jobInfo.jobId());
Preconditions.checkState(
wrapper != null, "Releasing context for unknown job: " + jobInfo.jobId());
PipelineOptions pipelineOptions =
PipelineOptionsTranslation.fromProto(jobInfo.pipel... | class ReferenceCountingFlinkExecutableStageContextFactory
implements FlinkExecutableStageContext.Factory {
private static final Logger LOG =
LoggerFactory.getLogger(ReferenceCountingFlinkExecutableStageContextFactory.class);
private static final int MAX_RETRY = 3;
private final Creator creator;
priva... | class ReferenceCountingFlinkExecutableStageContextFactory
implements FlinkExecutableStageContext.Factory {
private static final Logger LOG =
LoggerFactory.getLogger(ReferenceCountingFlinkExecutableStageContextFactory.class);
private static final int MAX_RETRY = 3;
private final Creator creator;
priva... |
You might use `Strings.isNullOrEmpty` instead of two checks. | public ConnectionConfiguration withApiKey(String apiKey) {
checkArgument(apiKey != null, "apiKey can not be null");
checkArgument(!apiKey.isEmpty(), "apiKey can not be empty");
return builder().setApiKey(apiKey).build();
} | checkArgument(!apiKey.isEmpty(), "apiKey can not be empty"); | public ConnectionConfiguration withApiKey(String apiKey) {
checkArgument(!Strings.isNullOrEmpty(apiKey), "apiKey can not be null or empty");
return builder().setApiKey(apiKey).build();
} | class Builder {
abstract Builder setAddresses(List<String> addresses);
abstract Builder setUsername(String username);
abstract Builder setPassword(String password);
abstract Builder setApiKey(String apiKey);
abstract Builder setBearerToken(String bearerToken);
abstract Builder s... | class Builder {
abstract Builder setAddresses(List<String> addresses);
abstract Builder setUsername(String username);
abstract Builder setPassword(String password);
abstract Builder setApiKey(String apiKey);
abstract Builder setBearerToken(String bearerToken);
abstract Builder s... |
`instanceof` also means that `readTimeout` is not `null` (and IntelliJ hints as much if one tries to add the null check) | public Future<HttpClientRequest> createRequest(RestClientRequestContext state) {
HttpClient httpClient = state.getHttpClient();
URI uri = state.getUri();
boolean isHttps = "https".equals(uri.getScheme());
int port = uri.getPort() != -1 ? uri.getPort() : (isHttps ? 443 : 80);
Requ... | if ((readTimeout instanceof Long)) { | public Future<HttpClientRequest> createRequest(RestClientRequestContext state) {
HttpClient httpClient = state.getHttpClient();
URI uri = state.getUri();
boolean isHttps = "https".equals(uri.getScheme());
int port = uri.getPort() != -1 ? uri.getPort() : (isHttps ? 443 : 80);
Requ... | class ClientSendRequestHandler implements ClientRestHandler {
private final boolean followRedirects;
public ClientSendRequestHandler(boolean followRedirects) {
this.followRedirects = followRedirects;
}
@Override
public void handle(RestClientRequestContext requestContext) {
if (requ... | class ClientSendRequestHandler implements ClientRestHandler {
private final boolean followRedirects;
public ClientSendRequestHandler(boolean followRedirects) {
this.followRedirects = followRedirects;
}
@Override
public void handle(RestClientRequestContext requestContext) {
if (requ... |
I believe the reason behind `set` was this duplicate issue. With this PR, we cannot remove a value anymore or decide when we want a single or multiple values of a header (even if I agree that having multiple values of the same header is rarely used, this PR may introduce that case a lot more). | public static void applyFilters(Map<String, FilterConfig> filtersInConfig, Router httpRouteRouter) {
if (!filtersInConfig.isEmpty()) {
for (var entry : filtersInConfig.entrySet()) {
var filterConfig = entry.getValue();
var matches = filterConfig.matches;
... | event.response().headers().addAll(headers); | public static void applyFilters(Map<String, FilterConfig> filtersInConfig, Router httpRouteRouter) {
if (!filtersInConfig.isEmpty()) {
for (var entry : filtersInConfig.entrySet()) {
var filterConfig = entry.getValue();
var matches = filterConfig.matches;
... | class HttpServerCommonHandlers {
public static void enforceMaxBodySize(ServerLimitsConfig limits, Router httpRouteRouter) {
if (limits.maxBodySize.isPresent()) {
long limit = limits.maxBodySize.get().asLongValue();
Long limitObj = limit;
httpRouteRouter.route().order(Rout... | class HttpServerCommonHandlers {
public static void enforceMaxBodySize(ServerLimitsConfig limits, Router httpRouteRouter) {
if (limits.maxBodySize.isPresent()) {
long limit = limits.maxBodySize.get().asLongValue();
Long limitObj = limit;
httpRouteRouter.route().order(Rout... |
Worked without them. Updated in https://github.com/ballerina-platform/ballerina-lang/pull/34427/commits/df432790bb0b85bdac8fd890f881cf4296966849. | private BLangSimpleVariable createSimpleVariable(BField field) {
BLangSimpleVariable manualField = new BLangSimpleVariable();
BLangIdentifier name = new BLangIdentifier();
name.setValue(field.name.value);
name.pos = field.pos;
manualField.setName(name);
manualField.flag... | manualField.typeNode = userDefinedTypeNode; | private BLangSimpleVariable createSimpleVariable(BField field) {
BLangSimpleVariable manualField = new BLangSimpleVariable();
BLangIdentifier name = new BLangIdentifier();
name.setValue(field.name.value);
name.pos = field.pos;
manualField.setName(name);
manualField.flagS... | class ConstantValueResolver extends BLangNodeVisitor {
private static final CompilerContext.Key<ConstantValueResolver> CONSTANT_VALUE_RESOLVER_KEY =
new CompilerContext.Key<>();
private BConstantSymbol currentConstSymbol;
private BLangConstantValue result;
private BLangDiagnosticLog dlog;
... | class ConstantValueResolver extends BLangNodeVisitor {
private static final CompilerContext.Key<ConstantValueResolver> CONSTANT_VALUE_RESOLVER_KEY =
new CompilerContext.Key<>();
private BConstantSymbol currentConstSymbol;
private BLangConstantValue result;
private BLangDiagnosticLog dlog;
... |
We could also, extend `ObjectOps` class with `CommonOps` similar to other places and get rid of overrides to union, intersect, and diff() here. | private static boolean objectBddIsEmpty(Context cx, Bdd b) {
return bddEveryPositive(cx, b, null, null, MappingOps::mappingFormulaIsEmpty);
} | return bddEveryPositive(cx, b, null, null, MappingOps::mappingFormulaIsEmpty); | private static boolean objectBddIsEmpty(Context cx, Bdd b) {
return bddEveryPositive(cx, b, null, null, MappingOps::mappingFormulaIsEmpty);
} | class ObjectOps implements BasicTypeOps {
@Override
public SubtypeData union(SubtypeData t1, SubtypeData t2) {
return bddSubtypeUnion(t1, t2);
}
@Override
public SubtypeData intersect(SubtypeData t1, SubtypeData t2) {
return bddSubtypeIntersect(t1, t2);
}
@Override
pub... | class ObjectOps extends CommonOps implements BasicTypeOps {
@Override
public SubtypeData complement(SubtypeData t) {
return objectSubTypeComplement(t);
}
@Override
public boolean isEmpty(Context cx, SubtypeData t) {
return objectSubTypeIsEmpty(cx, t);
}
private static bool... |
repeated code with line 360-390 | private ScalarOperator createNewAggFunction(ScalarOperator arg0, ScalarOperator arg1, Type returnType) {
if (arg0.isConstant()) {
AggregateFunction countFunction = AggregateFunction.createBuiltin(
FunctionSet.COUNT, Lists.newArrayList(arg1.getType())... | if (arg1.isColumnRef()) { | private ScalarOperator createNewAggFunction(ScalarOperator arg0, ScalarOperator arg1, Type returnType) {
if (arg0.isConstant()) {
AggregateFunction countFunction = AggregateFunction.createBuiltin(
FunctionSet.COUNT, Lists.newArrayList(arg1.getType())... | class AggFunctionRewriter {
public Map<ColumnRefOperator, CallOperator> oldAggregations;
public Map<ColumnRefOperator, ScalarOperator> oldPreAggProjections;
public ColumnRefFactory columnRefFactory;
public Map<ColumnRefOperator, ScalarOperator> newPostAggProjections;
public Map<C... | class AggFunctionRewriter {
public Map<ColumnRefOperator, CallOperator> oldAggregations;
public Map<ColumnRefOperator, ScalarOperator> oldPreAggProjections;
public ColumnRefFactory columnRefFactory;
public Map<ColumnRefOperator, ScalarOperator> newPostAggProjections;
public Map<C... |
Do we want to keep that? | public void testThatTheKogitoApplicationRuns() throws MavenInvocationException, IOException {
testDir = initProject("projects/simple-kogito", "projects/project-classic-run-kogito");
run("-e");
await()
.pollDelay(1, TimeUnit.SECONDS)
.atMost(1, TimeUnit.MINUTES).u... | run("-e"); | public void testThatTheKogitoApplicationRuns() throws MavenInvocationException, IOException {
testDir = initProject("projects/simple-kogito", "projects/project-classic-run-kogito");
run("-e");
await()
.pollDelay(1, TimeUnit.SECONDS)
.atMost(1, TimeUnit.MINUTES).u... | class KogitoDevModeIT extends RunAndCheckMojoTestBase {
@Test
} | class KogitoDevModeIT extends RunAndCheckMojoTestBase {
@Test
} |
<!--thread_id:cc_182896317_t; commit:1fd121da1417624b3b84f0300648251da64b9cb5; resolved:1--> <!--section:context-quote--> > **jkff** wrote: > Ditto, reference the JIRA here too if any <!--section:body--> Done. | public void testIncomingConnection() throws Exception {
StreamObserver<BeamFnApi.InstructionRequest> requestObserver = mock(StreamObserver.class);
StreamObserver<BeamFnApi.InstructionResponse> responseObserver =
controlService.control(requestObserver);
InstructionRequestHandler client = p... | public void testIncomingConnection() throws Exception {
StreamObserver<BeamFnApi.InstructionRequest> requestObserver = mock(StreamObserver.class);
StreamObserver<BeamFnApi.InstructionResponse> responseObserver =
controlService.control(requestObserver);
InstructionRequestHandler client = pool.g... | class FnApiControlClientPoolServiceTest {
private final ControlClientPool pool = MapControlClientPool.withTimeout(Duration.ofSeconds(10));
private final FnApiControlClientPoolService controlService =
FnApiControlClientPoolService.offeringClientsToPool(
pool.getSink(), GrpcContextHeaderAccesso... | class FnApiControlClientPoolServiceTest {
private final ControlClientPool pool = MapControlClientPool.create();
private final FnApiControlClientPoolService controlService =
FnApiControlClientPoolService.offeringClientsToPool(
pool.getSink(), GrpcContextHeaderAccessorProvider.getHeaderAccessor());
... | |
Right, in the case of more than one session error, if we see multiple entries of the first log and at least one of the second log entries, then it's good. It looks like one of the session errors resulting in the processor restart may cancel the merge operator, which could, in turn, cancel some enqueued errors to bou... | Mono<ServiceBusReceiveLink> getActiveLink() {
if (this.receiveLink != null) {
return Mono.just(this.receiveLink);
}
return Mono.defer(() -> createSessionReceiveLink()
.flatMap(link -> link.getEndpointStates()
.filter(e -> e == AmqpEndpointState.ACTIVE)
... | return Mono.<Long>error(failure).publishOn(Schedulers.boundedElastic()); | Mono<ServiceBusReceiveLink> getActiveLink() {
if (this.receiveLink != null) {
return Mono.just(this.receiveLink);
}
return Mono.defer(() -> createSessionReceiveLink()
.flatMap(link -> link.getEndpointStates()
.filter(e -> e == AmqpEndpointState.ACTIVE)
... | class ServiceBusSessionManager implements AutoCloseable {
private static final Duration SLEEP_DURATION_ON_ACCEPT_SESSION_EXCEPTION = Duration.ofMinutes(1);
private static final ClientLogger LOGGER = new ClientLogger(ServiceBusSessionManager.class);
private final String entityPath;
private final Me... | class ServiceBusSessionManager implements AutoCloseable {
private static final Duration SLEEP_DURATION_ON_ACCEPT_SESSION_EXCEPTION = Duration.ofMinutes(1);
private static final String TRACKING_ID_KEY = "trackingId";
private static final ClientLogger LOGGER = new ClientLogger(ServiceBusSessionManager.c... |
Can we include more information about the construct here? Like a qualified name instead of just the name? e.g., `ballerina/lang.value:isReadOnly` For object methods it may have to be like `Obj.method`. For anonymous object methods we can probably give only the method name though. | public void testDeprecatedWarningForIsReadOnly() {
CompileResult result = BCompileUtil.compile(
"test-src/expressions/builtinoperations/is_readonly_deprecated_warning.bal");
int index = 0;
validateWarning(result, index++, "usage of construct 'isReadOnly' is deprecated", 22, 9);
... | validateWarning(result, index++, "usage of construct 'isReadOnly' is deprecated", 22, 9); | public void testDeprecatedWarningForIsReadOnly() {
CompileResult result = BCompileUtil.compile(
"test-src/expressions/builtinoperations/is_readonly_deprecated_warning.bal");
int index = 0;
validateWarning(result, index++,
"usage of construct 'ballerina/lang.value... | class FreezeAndIsFrozenTest {
private static final String FREEZE_SUCCESSFUL = "freeze successful";
private CompileResult result;
private CompileResult semanticsNegativeResult;
private CompileResult negativeResult;
@BeforeClass
public void setup() {
result = BCompileUtil.compile("test-... | class FreezeAndIsFrozenTest {
private static final String FREEZE_SUCCESSFUL = "freeze successful";
private CompileResult result;
private CompileResult semanticsNegativeResult;
private CompileResult negativeResult;
@BeforeClass
public void setup() {
result = BCompileUtil.compile("test-... |
@StefanRRichter , thanks a lot for your careful review. It is a real bug. I have fixed it. In addition, I have added test cases by making BitSetTest parameterized. So the clear method is tested against different amounts of bits. | public void clear() {
int index = 0;
while (index < byteLength) {
memorySegment.putLong(offset + index, 0L);
index += 8;
}
while (index < byteLength) {
memorySegment.put(offset + index, (byte) 0);
}
} | while (index < byteLength) { | public void clear() {
int index = 0;
while (index + 8 <= byteLength) {
memorySegment.putLong(offset + index, 0L);
index += 8;
}
while (index < byteLength) {
memorySegment.put(offset + index, (byte) 0);
index += 1;
}
} | class BitSet {
private MemorySegment memorySegment;
private int offset;
private int byteLength;
private int bitLength;
private final int BYTE_INDEX_MASK = 0x00000007;
public BitSet(int byteSize) {
Preconditions.checkArgument(byteSize > 0, "bits size should be greater than 0.");
this.byteLength = by... | class BitSet {
private MemorySegment memorySegment;
private int offset;
private int byteLength;
private int bitLength;
private final int BYTE_INDEX_MASK = 0x00000007;
public BitSet(int byteSize) {
Preconditions.checkArgument(byteSize > 0, "bits size should be greater than 0.");
this.byteLength = by... |
@dpcollins-google On this constructor argument change, I replaced the Beam code with the default values by reading the diff in https://github.com/googleapis/java-pubsublite/pull/475/files. But the PartitionCountWatchingPublisher constructor changed its accessor from public to package-default. Do you have a suggestion o... | static Publisher<MessageMetadata> newPublisher(PublisherOptions options) throws ApiException {
SerializableSupplier<Object> supplier = options.publisherSupplier();
if (supplier != null) {
Object supplied = supplier.get();
TypeToken<Publisher<MessageMetadata>> token = new TypeToken<Publisher<MessageM... | return new PartitionCountWatchingPublisher( | static Publisher<MessageMetadata> newPublisher(PublisherOptions options) throws ApiException {
SerializableSupplier<Object> supplier = options.publisherSupplier();
if (supplier != null) {
Object supplied = supplier.get();
TypeToken<Publisher<MessageMetadata>> token = new TypeToken<Publisher<MessageM... | class Publishers {
private static final Framework FRAMEWORK = Framework.of("BEAM");
private Publishers() {}
@SuppressWarnings("unchecked")
} | class Publishers {
private static final Framework FRAMEWORK = Framework.of("BEAM");
private Publishers() {}
@SuppressWarnings("unchecked")
} |
Again, this just makes the code less readable. BAOS.close() doesn't do anything. | public void handleMessage(Object msg) {
try {
if (msg instanceof HttpResponse) {
HttpResponse res = (HttpResponse) msg;
responseBuilder.setStatusCode(res.status().code());
if (request.getRequestSource() == AwsProx... | baos.close(); | public void handleMessage(Object msg) {
try {
if (msg instanceof HttpResponse) {
HttpResponse res = (HttpResponse) msg;
responseBuilder.setStatusCode(res.status().code());
if (request.getRequestSource() == AwsProx... | class NettyResponseHandler implements VirtualResponseHandler {
AwsProxyResponse responseBuilder = new AwsProxyResponse();
ByteArrayOutputStream baos;
WritableByteChannel byteChannel;
final AwsProxyRequest request;
CompletableFuture<AwsProxyResponse> future = new CompletableFuture... | class NettyResponseHandler implements VirtualResponseHandler {
AwsProxyResponse responseBuilder = new AwsProxyResponse();
ByteArrayOutputStream baos;
WritableByteChannel byteChannel;
final AwsProxyRequest request;
CompletableFuture<AwsProxyResponse> future = new CompletableFuture... |
This leaves the reserved node with the application for 20-27 mins (until it is expired by `ReservationExpirer`), this is especially unfortunate in CD when we want to fail integration tests when some node are stuck in a non-active state. We should prepare the application again with the node unmarked as wantToRetire or ... | private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetir... | return false; | private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetir... | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
... | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
... |
not sure we need to be consistent across languages on this condition to set headers, but just want to point it. LGTM otherwise. | private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) {
final List<HttpPipelinePolicy> policies = new ArrayList<>();
if (tokenCredential != null) {
policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE));
} else if ... | || !CoreUtils.isNullOrEmpty(metricsAdvisorKeyCredential.getApiKey())) { | private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) {
final List<HttpPipelinePolicy> policies = new ArrayList<>();
if (tokenCredential != null) {
policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE));
} else if ... | class MetricsAdvisorClientBuilder {
private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id";
private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON;
private static final String ACCEPT_HEADER = "Accept";
private static final String METRICSADVISO... | class MetricsAdvisorClientBuilder {
private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id";
private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON;
private static final String ACCEPT_HEADER = "Accept";
private static final String METRICSADVISO... |
`DescribeStmt` is only for `describe table`. `files()` is a table function table, so i put it here. | public DescribeStmt(Map<String, String> tableFunctionProperties, NodePosition pos) {
super(pos);
this.dbTableName = null;
this.totalRows = new LinkedList<>();
this.isTableFunctionTable = true;
this.tableFunctionProperties = tableFunctionProperties;
} | this.isTableFunctionTable = true; | public DescribeStmt(Map<String, String> tableFunctionProperties, NodePosition pos) {
super(pos);
this.dbTableName = null;
this.totalRows = new LinkedList<>();
this.isTableFunctionTable = true;
this.tableFunctionProperties = tableFunctionProperties;
} | class DescribeStmt extends ShowStmt {
private static final ShowResultSetMetaData DESC_OLAP_TABLE_META_DATA =
ShowResultSetMetaData.builder()
.addColumn(new Column("Field", ScalarType.createVarchar(20)))
.addColumn(new Column("Type", ScalarType.createVarchar(20)))... | class DescribeStmt extends ShowStmt {
private static final ShowResultSetMetaData DESC_OLAP_TABLE_META_DATA =
ShowResultSetMetaData.builder()
.addColumn(new Column("Field", ScalarType.createVarchar(20)))
.addColumn(new Column("Type", ScalarType.createVarchar(20)))... |
Didn't see the purpose of re-wrapping an IOException | public boolean start() throws IOException {
try {
ConnectionHandler connectionHandler = new ConnectionHandler(source.spec.uri());
connectionHandler.start();
Channel channel = connectionHandler.getChannel();
String queueName = source.spec.queue();
if (source.spec.queueDecl... | channel.queueBind(queueName, source.spec.exchange(), source.spec.routingKey()); | public boolean start() throws IOException {
try {
connectionHandler = new ConnectionHandler(source.spec.uri());
connectionHandler.start();
Channel channel = connectionHandler.getChannel();
queueName = source.spec.queue();
if (source.spec.queueDeclare()) {
... | class UnboundedRabbitMqReader
extends UnboundedSource.UnboundedReader<RabbitMqMessage> {
private final RabbitMQSource source;
private RabbitMqMessage current;
private byte[] currentRecordId;
private ConnectionHandler connectionHandler;
private QueueingConsumer consumer;
private Instant cu... | class UnboundedRabbitMqReader
extends UnboundedSource.UnboundedReader<RabbitMqMessage> {
private final RabbitMQSource source;
private RabbitMqMessage current;
private byte[] currentRecordId;
private ConnectionHandler connectionHandler;
private String queueName;
private Instant currentTime... |
How about just removing the shortcut? | public History recordStateTransition(Node.State from, Node.State to, Agent agent, Instant at) {
if (from == to && from != Node.State.reserved) return this;
switch (to) {
case provisioned: return this.with(new Event(Event.Type.provisioned, agent, at));
case ready: r... | public History recordStateTransition(Node.State from, Node.State to, Agent agent, Instant at) {
if (from == to && from != Node.State.reserved) return this;
switch (to) {
case provisioned: return this.with(new Event(Event.Type.provisioned, agent, at));
case ready: r... | class History {
private final ImmutableMap<Event.Type, Event> events;
public History(Collection<Event> events) {
this(toImmutableMap(events));
}
private History(ImmutableMap<Event.Type, Event> events) {
this.events = events;
}
private static ImmutableMap<Event.Type, Event> to... | class History {
private final ImmutableMap<Event.Type, Event> events;
public History(Collection<Event> events) {
this(toImmutableMap(events));
}
private History(ImmutableMap<Event.Type, Event> events) {
this.events = events;
}
private static ImmutableMap<Event.Type, Event> to... | |
Yes, I forgot about that. Excellent catch! | private static void deferConfigChangesForClustersToBeRestarted(List<ConfigChangeAction> actions, VespaModel model) {
Set<ClusterSpec.Id> clustersToBeRestarted = actions.stream()
.filter(action -> action.getType() == ConfigChangeAction.Type.RESTART)
... | var containerCluster = model.getContainerClusters().get(clusterToRestart.value()); | private static void deferConfigChangesForClustersToBeRestarted(List<ConfigChangeAction> actions, VespaModel model) {
Set<ClusterSpec.Id> clustersToBeRestarted = actions.stream()
.filter(action -> action.getType() == ConfigChangeAction.Type.RESTART)
... | class Validation {
/**
* Validates the model supplied, and if there already exists a model for the application validates changes
* between the previous and current model
*
* @return a list of required changes needed to make this configuration live
*/
public static List<ConfigChangeActi... | class Validation {
/**
* Validates the model supplied, and if there already exists a model for the application validates changes
* between the previous and current model
*
* @return a list of required changes needed to make this configuration live
*/
public static List<ConfigChangeActi... |
Does this properly handle multi-catch blocks, ex `catch (IOException | UncheckIOException ex)`? | public void visitToken(DetailAST catchBlockToken) {
final DetailAST catchStatement = catchBlockToken.findFirstToken(TokenTypes.PARAMETER_DEF);
final String caughtExceptionVariableName = catchStatement.findFirstToken(TokenTypes.IDENT).getText();
final List<DetailAST> throwStatements = getThrowSt... | final List<String> wrappedExceptions = | public void visitToken(DetailAST catchBlockToken) {
final DetailAST catchStatement = catchBlockToken.findFirstToken(TokenTypes.PARAMETER_DEF);
final String caughtExceptionVariableName = catchStatement.findFirstToken(TokenTypes.IDENT).getText();
final List<DetailAST> throwState... | class UseCaughtExceptionCauseCheck extends AbstractCheck {
static final String UNUSED_CAUGHT_EXCEPTION_ERROR = "Should use the current exception cause \"%s\".";
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getAcceptableTokens() {
... | class UseCaughtExceptionCauseCheck extends AbstractCheck {
static final String UNUSED_CAUGHT_EXCEPTION_ERROR = "Caught and rethrown exceptions should include the caught"
+ " exception as the cause in the rethrown exception. Dropping the causal exception makes it more difficult"
+ " to troubleshoot i... |
I run ValidatesRunner tests and the result is green. | private void checkNoMoreMatches(final List<PTransformOverride> overrides) {
traverseTopologically(
new PipelineVisitor.Defaults() {
SetMultimap<Node, PTransformOverride> matched = HashMultimap.create();
@Override
public CompositeBehavior enterCompositeTransform(Node node) {
... | SetMultimap<Node, PTransformOverride> matched = HashMultimap.create(); | private void checkNoMoreMatches(final List<PTransformOverride> overrides) {
traverseTopologically(
new PipelineVisitor.Defaults() {
SetMultimap<Node, PTransformOverride> matched = HashMultimap.create();
@Override
public CompositeBehavior enterCompositeTransform(Node node) {
... | class PipelineExecutionException extends RuntimeException {
/**
* Wraps {@code cause} into a {@link PipelineExecutionException}.
*/
public PipelineExecutionException(Throwable cause) {
super(cause);
}
} | class PipelineExecutionException extends RuntimeException {
/** Wraps {@code cause} into a {@link PipelineExecutionException}. */
public PipelineExecutionException(Throwable cause) {
super(cause);
}
} |
Also, when you start a context in the parser. You have to start a context in error handler in parrelly. Need to add this context to the `startContextIfRequired()` method in errorhandler | private boolean isServiceDeclStart(ParserRuleContext currentContext, int lookahead) {
switch (peek(lookahead + 1).kind) {
case IDENTIFIER_TOKEN:
SyntaxKind tokenAfterIdentifier = peek(lookahead + 2).kind;
switch (tokenAfterIdentifier) {
ca... | startContext(ParserRuleContext.XML_STEP_EXTEND); | 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... |
I did change it in https://github.com/apache/beam/pull/14849/files but it seems like this portion is not removed during cherry-pick. | public PipelineResult runTest(Pipeline pipeline) {
Twister2PipelineExecutionEnvironment env = new Twister2PipelineExecutionEnvironment(options);
LOG.info("Translating pipeline to Twister2 program.");
pipeline.replaceAll(getDefaultOverrides());
if (!ExperimentalOptions.hasExperiment(pipeline.ge... | pipeline.getOptions().as(ExperimentalOptions.class), "beam_fn_api_use_deprecated_read"); | public PipelineResult runTest(Pipeline pipeline) {
Twister2PipelineExecutionEnvironment env = new Twister2PipelineExecutionEnvironment(options);
LOG.info("Translating pipeline to Twister2 program.");
pipeline.replaceAll(getDefaultOverrides());
if (!ExperimentalOptions.hasExperiment(pipeline.ge... | class Twister2Runner extends PipelineRunner<PipelineResult> {
private static final Logger LOG = Logger.getLogger(Twister2Runner.class.getName());
private static final String SIDEINPUTS = "sideInputs";
private static final String LEAVES = "leaves";
private static final String GRAPH = "graph";
/** Provided opt... | class Twister2Runner extends PipelineRunner<PipelineResult> {
private static final Logger LOG = Logger.getLogger(Twister2Runner.class.getName());
private static final String SIDEINPUTS = "sideInputs";
private static final String LEAVES = "leaves";
private static final String GRAPH = "graph";
/** Provided opt... |
Why do we traverse the children here? Can't we use the specific APIs instead? | public Optional<DocumentSymbol> transform(ClassDefinitionNode classDefinitionNode) {
String name = classDefinitionNode.className().text();
SymbolKind symbolKind = SymbolKind.Class;
Range range = DocumentSymbolUtil.generateNodeRange(classDefinitionNode);
Optional<MetadataNode> metadata = ... | Optional<MetadataNode> metadata = classDefinitionNode.metadata(); | public Optional<DocumentSymbol> transform(ClassDefinitionNode classDefinitionNode) {
String name = classDefinitionNode.className().text();
SymbolKind symbolKind = SymbolKind.Class;
Range range = DocumentSymbolUtil.generateNodeRange(classDefinitionNode);
Optional<MetadataNode> metadata = ... | class DocumentSymbolResolver extends NodeTransformer<Optional<DocumentSymbol>> {
private List<DocumentSymbol> documentSymbolStore;
private DocumentSymbolContext context;
DocumentSymbolResolver(DocumentSymbolContext context) {
this.context = context;
documentSymbolStore = new ArrayList<>();... | class DocumentSymbolResolver extends NodeTransformer<Optional<DocumentSymbol>> {
private List<DocumentSymbol> documentSymbolStore;
private DocumentSymbolContext context;
DocumentSymbolResolver(DocumentSymbolContext context) {
this.context = context;
documentSymbolStore = new ArrayList<>();... |
It's very minor but could we call it `MONGODB_PANACHE` as the feature? See a few lines below. | CapabilityBuildItem capability() {
return new CapabilityBuildItem(Capabilities.MONGO_PANACHE);
} | return new CapabilityBuildItem(Capabilities.MONGO_PANACHE); | CapabilityBuildItem capability() {
return new CapabilityBuildItem(Capabilities.MONGODB_PANACHE);
} | class PanacheResourceProcessor {
static final DotName DOTNAME_PANACHE_REPOSITORY_BASE = DotName.createSimple(PanacheMongoRepositoryBase.class.getName());
private static final DotName DOTNAME_PANACHE_REPOSITORY = DotName.createSimple(PanacheMongoRepository.class.getName());
static final DotName DOTNAME_PANAC... | class PanacheResourceProcessor {
static final DotName DOTNAME_PANACHE_REPOSITORY_BASE = DotName.createSimple(PanacheMongoRepositoryBase.class.getName());
private static final DotName DOTNAME_PANACHE_REPOSITORY = DotName.createSimple(PanacheMongoRepository.class.getName());
static final DotName DOTNAME_PANAC... |
should be wrapped in a try-catch block | public void testLogicalScopeShouldIgnoreValueGroupName() {
Configuration config = new Configuration();
config.setString(ConfigConstants.METRICS_REPORTER_PREFIX + "test." + ConfigConstants.METRICS_REPORTER_CLASS_SUFFIX, TestReporter.class.getName());
MetricRegistryImpl registry = new MetricRegistryImpl(MetricRegis... | MetricRegistryImpl registry = new MetricRegistryImpl(MetricRegistryConfiguration.fromConfiguration(config)); | public void testLogicalScopeShouldIgnoreValueGroupName() throws Exception {
Configuration config = new Configuration();
config.setString(ConfigConstants.METRICS_REPORTER_PREFIX + "test." + ConfigConstants.METRICS_REPORTER_CLASS_SUFFIX, TestReporter.class.getName());
MetricRegistryImpl registry = new MetricRegist... | class MetricGroupTest extends TestLogger {
private static final MetricRegistryConfiguration defaultMetricRegistryConfiguration = MetricRegistryConfiguration.defaultMetricRegistryConfiguration();
private MetricRegistryImpl registry;
private final MetricRegistryImpl exceptionOnRegister = new ExceptionOnRegisterRegi... | class MetricGroupTest extends TestLogger {
private static final MetricRegistryConfiguration defaultMetricRegistryConfiguration = MetricRegistryConfiguration.defaultMetricRegistryConfiguration();
private MetricRegistryImpl registry;
private final MetricRegistryImpl exceptionOnRegister = new ExceptionOnRegisterRegi... |
I really like these 4 lines. | private Tensor mappedHashJoin(Tensor a, Tensor b, TensorType joinedType) {
TensorType commonDimensionType = commonDimensions(a, b);
if (commonDimensionType.dimensions().isEmpty()) {
return mappedGeneralJoin(a, b, joinedType);
}
Tensor smallerTensor = a.size() > b.size() ? b... | b = largerTensor; | private Tensor mappedHashJoin(Tensor a, Tensor b, TensorType joinedType) {
TensorType commonDimensionType = commonDimensions(a, b);
if (commonDimensionType.dimensions().isEmpty()) {
return mappedGeneralJoin(a, b, joinedType);
}
boolean swapTensors = a.size() > b.size();
... | class Join extends PrimitiveTensorFunction {
private final TensorFunction argumentA, argumentB;
private final DoubleBinaryOperator combinator;
public Join(TensorFunction argumentA, TensorFunction argumentB, DoubleBinaryOperator combinator) {
Objects.requireNonNull(argumentA, "The first argumen... | class Join extends PrimitiveTensorFunction {
private final TensorFunction argumentA, argumentB;
private final DoubleBinaryOperator combinator;
public Join(TensorFunction argumentA, TensorFunction argumentB, DoubleBinaryOperator combinator) {
Objects.requireNonNull(argumentA, "The first argumen... |
throw new DdlException("Failed to remove worker. error: " + e.getMessage()); | public void removeWorker(String workerIpPort) throws StarClientException {
long workerId = -1;
try {
WorkerInfo workerInfo = client.getWorkerInfo(serviceId, workerIpPort);
workerId = workerInfo.getWorkerId();
} catch (StarClientException e2) {
LOG.war... | throw new StarClientException(e.getCode(), "remove worker error"); | public void removeWorker(String workerIpPort) throws DdlException {
long workerId = -1;
if (workerToId.containsKey(workerIpPort)) {
workerId = workerToId.get(workerIpPort);
} else {
try {
WorkerInfo workerInfo = client.getWorkerIn... | class StarOSAgent {
private static final Logger LOG = LogManager.getLogger(StarOSAgent.class);
private StarClient client;
private long serviceId;
private Map<String, Long> workerToId;
private Map<Long, Long> workerToBackend;
public StarOSAgent() {
serviceId = -1;
if (C... | class StarOSAgent {
private static final Logger LOG = LogManager.getLogger(StarOSAgent.class);
private StarClient client;
private long serviceId;
private Map<String, Long> workerToId;
private Map<Long, Long> workerToBackend;
public StarOSAgent() {
serviceId = -1;
if (C... |
ten parameters in a constructor, this is not that elegant | private DataSourceParameter crateDataSourceParameter() {
return new DataSourceParameter("jdbc:mysql:
} | return new DataSourceParameter("jdbc:mysql: | private DataSourceParameter crateDataSourceParameter() {
return new DataSourceParameter("jdbc:mysql:
} | class DataSourceParameterConverterTest {
@Test
public void assertGetDataSourceConfigurationMap() {
Map<String, DataSourceParameter> dataSourceParameterMap = new HashMap<>(2, 1);
dataSourceParameterMap.put("ds_0", crateDataSourceParameter());
dataSourceParameterMap.put("ds_1", crateD... | class DataSourceParameterConverterTest {
@Test
public void assertGetDataSourceConfigurationMap() {
Map<String, DataSourceParameter> dataSourceParameterMap = new HashMap<>(2, 1);
dataSourceParameterMap.put("ds_0", crateDataSourceParameter());
dataSourceParameterMap.put("ds_1", crateD... |
@bobby-richard Have a look at https://issues.apache.org/jira/browse/FLINK-29267 | protected JdbcSerializationConverter createExternalConverter(LogicalType type) {
switch (type.getTypeRoot()) {
case CHAR:
case VARCHAR:
return (val, index, statement) -> {
String valString = val.getString(index).toString();
if (UUI... | if (UUID_REGEX_PATTERN.matcher(valString).matches()) { | protected JdbcSerializationConverter createExternalConverter(LogicalType type) {
switch (type.getTypeRoot()) {
case CHAR:
case VARCHAR:
return (val, index, statement) -> {
String valString = val.getString(index).toString();
if (UUI... | class PostgresRowConverter extends AbstractJdbcRowConverter {
private static final long serialVersionUID = 1L;
private static final Pattern UUID_REGEX_PATTERN =
Pattern.compile("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$");
@Override
public String converterName() {
... | class PostgresRowConverter extends AbstractJdbcRowConverter {
private static final long serialVersionUID = 1L;
private static final Pattern UUID_REGEX_PATTERN =
Pattern.compile("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$");
@Override
public String converterName() {
... |
This is how the cool kids on the street do it | private static void addRestApiHandler(ContainerCluster<?> cluster, Options options) {
String handlerClassName = options.useNewRestapiHandler
? "com.yahoo.document.restapi.resource.DocumentV1ApiHandler"
: "com.yahoo.document.restapi.resource.RestApi";
var handler = newVesp... | handler.inject(executor); | private static void addRestApiHandler(ContainerCluster<?> cluster, Options options) {
String handlerClassName = options.useNewRestapiHandler
? "com.yahoo.document.restapi.resource.DocumentV1ApiHandler"
: "com.yahoo.document.restapi.resource.RestApi";
var handler = newVesp... | class ContainerDocumentApi {
private static final int FALLBACK_MAX_POOL_SIZE = 0;
private static final int FALLBACK_CORE_POOL_SIZE = 0;
public ContainerDocumentApi(ContainerCluster<?> cluster, Options options) {
addRestApiHandler(cluster, options);
addFeedHandler(cluster, options);
}... | class ContainerDocumentApi {
private static final int FALLBACK_MAX_POOL_SIZE = 0;
private static final int FALLBACK_CORE_POOL_SIZE = 0;
public ContainerDocumentApi(ContainerCluster<?> cluster, Options options) {
addRestApiHandler(cluster, options);
addFeedHandler(cluster, options);
}... |
We should use default values if `locationHeader` and `allowedMethods` are null or *empty* and document it. | public DefaultRedirectStrategy(int maxAttempts, String locationHeader, Set<HttpMethod> allowedMethods) {
if (maxAttempts < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Max attempts cannot be less than 0."));
}
this.maxAttempts = maxAttempts;
this.locati... | this.redirectMethods = allowedMethods == null ? DEFAULT_REDIRECT_ALLOWED_METHODS : allowedMethods; | public DefaultRedirectStrategy(int maxAttempts, String locationHeader, Set<HttpMethod> allowedMethods) {
if (maxAttempts < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Max attempts cannot be less than 0."));
}
this.maxAttempts = maxAttempts;
if (CoreUti... | class DefaultRedirectStrategy implements RedirectStrategy {
private final ClientLogger logger = new ClientLogger(DefaultRedirectStrategy.class);
private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3;
private static final String DEFAULT_REDIRECT_LOCATION_HEADER_NAME = "Location";
private static fin... | class DefaultRedirectStrategy implements RedirectStrategy {
private final ClientLogger logger = new ClientLogger(DefaultRedirectStrategy.class);
private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3;
private static final String DEFAULT_REDIRECT_LOCATION_HEADER_NAME = "Location";
private static fin... |
dns requires triple slash, I'll fix the comment | public static Channel createChannel(String name) throws SSLException {
InstanceHandle<GrpcClientConfigProvider> instance = Arc.container().instance(GrpcClientConfigProvider.class);
if (!instance.isAvailable()) {
throw new IllegalStateException("Unable to find the GrpcClientConfigProvider");... | host = "/" + host; | public static Channel createChannel(String name) throws SSLException {
InstanceHandle<GrpcClientConfigProvider> instance = Arc.container().instance(GrpcClientConfigProvider.class);
if (!instance.isAvailable()) {
throw new IllegalStateException("Unable to find the GrpcClientConfigProvider");... | class Channels {
private static final Logger LOGGER = Logger.getLogger(Channels.class.getName());
private Channels() {
}
private static GrpcClientConfiguration testConfig(GrpcServerConfiguration serverConfiguration) {
GrpcClientConfiguration config = new GrpcClientConfiguration... | class Channels {
private static final Logger LOGGER = Logger.getLogger(Channels.class.getName());
private Channels() {
}
private static GrpcClientConfiguration testConfig(GrpcServerConfiguration serverConfiguration) {
GrpcClientConfiguration config = new GrpcClientConfiguration... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.