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
Don't use `+ exception`. Instead pass it as param `LOGGER.logExceptionAsError(new IllegalArgumentException( "Can't parse Feature Flag configuration setting value.", exception))`. Or use `exception.getMessage()`.
private void updateSettingValue() { try { super.setValue(writeFeatureFlagConfigurationSetting(this)); } catch (IOException exception) { LOGGER.logExceptionAsError(new IllegalArgumentException( "Can't parse Feature Flag configuration setting value. Exception:" + ex...
"Can't parse Feature Flag configuration setting value. Exception:" + exception));
private void updateSettingValue() { try { super.setValue(writeFeatureFlagConfigurationSetting(this)); } catch (IOException exception) { LOGGER.logExceptionAsError(new IllegalArgumentException( "Can't parse Feature Flag configuration setting value.", exception)); ...
class FeatureFlagConfigurationSetting extends ConfigurationSetting { private static final ClientLogger LOGGER = new ClientLogger(FeatureFlagConfigurationSetting.class); private static final String FEATURE_FLAG_CONTENT_TYPE = "application/vnd.microsoft.appconfig.ff+json;charset=utf-8"; private String featur...
class FeatureFlagConfigurationSetting extends ConfigurationSetting { private static final ClientLogger LOGGER = new ClientLogger(FeatureFlagConfigurationSetting.class); private static final String FEATURE_FLAG_CONTENT_TYPE = "application/vnd.microsoft.appconfig.ff+json;charset=utf-8"; private String featur...
Also printing that website is created - can be moved to map part of individual observables.
public static boolean runSample(final Azure azure) { final String suffix = ".azurewebsites.net"; final String app1Name = SdkContext.randomResourceName("webapp1-", 20); final String app2Name = SdkContext.randomResourceName("webapp2-", 20); final String app3Nam...
Observable<?> app234Observable = azure.appServices().appServicePlans()
public static boolean runSample(final Azure azure) { final String suffix = ".azurewebsites.net"; final String app1Name = SdkContext.randomResourceName("webapp1-", 20); final String app2Name = SdkContext.randomResourceName("webapp2-", 20); final String app3Nam...
class ManageWebAppSourceControlAsync { private static OkHttpClient httpClient; /** * Main function which runs the actual sample. * @param azure instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters...
class ManageWebAppSourceControlAsync { private static OkHttpClient httpClient; /** * Main function which runs the actual sample. * @param azure instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters...
The exception is not clear after change the comparison in the if branch.
public void renamePath(String srcPath, String destPath, Map<String, String> loadProperties) throws UserException { WildcardURI srcPathUri = new WildcardURI(srcPath); WildcardURI destPathUri = new WildcardURI(destPath); if ((srcPathUri.getAuthority() == null && destPathUri.getAuthority() != null...
HdfsFs fileSystem = getFileSystem(srcPath, loadProperties, null);
public void renamePath(String srcPath, String destPath, Map<String, String> loadProperties) throws UserException { WildcardURI srcPathUri = new WildcardURI(srcPath); WildcardURI destPathUri = new WildcardURI(destPath); boolean srcAuthorityNull = (srcPathUri.getAuthority() == null); bool...
class HdfsFsManager { private static final Logger LOG = LogManager.getLogger(HdfsFsManager.class); private static final String HDFS_SCHEME = "hdfs"; private static final String VIEWFS_SCHEME = "viewfs"; private static final String S3_SCHEMA = "s3"; private static final String S3A_SCHEME = "s3...
class HdfsFsManager { private static final Logger LOG = LogManager.getLogger(HdfsFsManager.class); private static final String HDFS_SCHEME = "hdfs"; private static final String VIEWFS_SCHEME = "viewfs"; private static final String S3_SCHEMA = "s3"; private static final String S3A_SCHEME = "s3...
I wanted to say that what the user ultimately needs to do is _not_ setting our config property, but make sure that the app's service account has access to secrets. Obviously `quarkus.kubernetes-config.secrets.enabled` is the easiest way, if people use the Kubernetes extension. But that doesn't always have to be the ca...
public void warnAboutSecrets(KubernetesConfigSourceConfig config, KubernetesConfigBuildTimeConfig buildTimeConfig) { if (config.enabled && config.secrets.isPresent() && !config.secrets.get().isEmpty() && !buildTimeConfig.secretsEnabled) { log.warn("Con...
+ " Check if your application's service account has enough permissions to read secrets.");
public void warnAboutSecrets(KubernetesConfigSourceConfig config, KubernetesConfigBuildTimeConfig buildTimeConfig) { if (config.enabled && config.secrets.isPresent() && !config.secrets.get().isEmpty() && !buildTimeConfig.secretsEnabled) { log.warn("Con...
class KubernetesConfigRecorder { private static final Logger log = Logger.getLogger(KubernetesConfigRecorder.class); public RuntimeValue<ConfigSourceProvider> configSources(KubernetesConfigSourceConfig kubernetesConfigSourceConfig, KubernetesClientBuildConfig clientConfig) { if (!kubernete...
class KubernetesConfigRecorder { private static final Logger log = Logger.getLogger(KubernetesConfigRecorder.class); public RuntimeValue<ConfigSourceProvider> configSources(KubernetesConfigSourceConfig kubernetesConfigSourceConfig, KubernetesClientBuildConfig clientConfig) { if (!kubernete...
why we can insert null partition? There are many points that need to be adapted if we support it.
public static PartitionData partitionDataFromPath(String relativePartitionPath, PartitionSpec spec) { PartitionData data = new PartitionData(spec.fields().size()); String[] partitions = relativePartitionPath.split("/", -1); List<PartitionField> partitionFields = spec.fields(); for (int ...
if (parts[1].equals("null")) {
public static PartitionData partitionDataFromPath(String relativePartitionPath, PartitionSpec spec) { PartitionData data = new PartitionData(spec.fields().size()); String[] partitions = relativePartitionPath.split("/", -1); List<PartitionField> partitionFields = spec.fields(); for (int ...
class IcebergMetadata implements ConnectorMetadata { private static final Logger LOG = LogManager.getLogger(IcebergMetadata.class); public static final String LOCATION_PROPERTY = "location"; public static final String FILE_FORMAT = "file_format"; public static final String COMPRESSION_CODEC = "compres...
class IcebergMetadata implements ConnectorMetadata { private static final Logger LOG = LogManager.getLogger(IcebergMetadata.class); public static final String LOCATION_PROPERTY = "location"; public static final String FILE_FORMAT = "file_format"; public static final String COMPRESSION_CODEC = "compres...
I guess empty String is better.
public String getSchema() throws SQLException { return null; }
return null;
public String getSchema() throws SQLException { return ""; }
class CircuitBreakerConnection extends AbstractUnsupportedOperationConnection { @Override public DatabaseMetaData getMetaData() { return new CircuitBreakerDatabaseMetaData(); } @Override public void setReadOnly(final boolean readOnly) { } @Override public boolean i...
class CircuitBreakerConnection extends AbstractUnsupportedOperationConnection { @Override public DatabaseMetaData getMetaData() { return new CircuitBreakerDatabaseMetaData(); } @Override public void setReadOnly(final boolean readOnly) { } @Override public boolean i...
If all the user-provided tablet_ids are invalid, will here throw an `Unknown Error` to the MySQL client?
public PlanFragment visitPhysicalOlapScan(OptExpression optExpr, ExecPlan context) { PhysicalOlapScanOperator node = (PhysicalOlapScanOperator) optExpr.getOp(); OlapTable referenceTable = (OlapTable) node.getTable(); context.getDescTbl().addReferencedTable(referenceTable); ...
Preconditions.checkState(selectTabletIds != null && !selectTabletIds.isEmpty());
public PlanFragment visitPhysicalOlapScan(OptExpression optExpr, ExecPlan context) { PhysicalOlapScanOperator node = (PhysicalOlapScanOperator) optExpr.getOp(); OlapTable referenceTable = (OlapTable) node.getTable(); context.getDescTbl().addReferencedTable(referenceTable); ...
class PhysicalPlanTranslator extends OptExpressionVisitor<PlanFragment, ExecPlan> { private final ColumnRefFactory columnRefFactory; private final IdGenerator<RuntimeFilterId> runtimeFilterIdIdGenerator = RuntimeFilterId.createGenerator(); public PhysicalPlanTranslator(ColumnRefFactory columnRe...
class PhysicalPlanTranslator extends OptExpressionVisitor<PlanFragment, ExecPlan> { private final ColumnRefFactory columnRefFactory; private final IdGenerator<RuntimeFilterId> runtimeFilterIdIdGenerator = RuntimeFilterId.createGenerator(); public PhysicalPlanTranslator(ColumnRefFactory columnRe...
The value of that is passed to the ctor of `VertxHttpExporter` by `OtlpRecorder` (same as for the gRPC exporter). Furthermore, the tests already cover this
public void handle(HttpClientRequest request) { HttpClientRequest clientRequest = request.response(new Handler<>() { @Override public void handle(AsyncResult<HttpClientResponse> callResult) { ...
clientRequest.putHeader("Content-Encoding", "gzip");
public void handle(HttpClientRequest request) { HttpClientRequest clientRequest = request.response(new Handler<>() { @Override public void handle(AsyncResult<HttpClientResponse> callResult) { ...
class VertxHttpSender implements HttpSender { private static final String TRACES_PATH = "/v1/traces"; private final boolean compressionEnabled; private final Map<String, String> headers; private final String contentType; private final HttpClient client; VertxHttpSender(...
class VertxHttpSender implements HttpSender { private static final String TRACES_PATH = "/v1/traces"; private final boolean compressionEnabled; private final Map<String, String> headers; private final String contentType; private final HttpClient client; VertxHttpSender(...
fair enough ... I don't have a preference here.
public void testConcurrentGetAndIncrement() throws Exception { final int numThreads = 8; final CountDownLatch startLatch = new CountDownLatch(1); final CheckpointIDCounter counter = createCheckpointIdCounter(); counter.start(); ExecutorService executor = null;...
if (executor != null) {
public void testConcurrentGetAndIncrement() throws Exception { final int numThreads = 8; final CountDownLatch startLatch = new CountDownLatch(1); final CheckpointIDCounter counter = createCheckpointIdCounter(); counter.start(); ExecutorService executor = null;...
class CheckpointIDCounterTestBase extends TestLogger { protected abstract CheckpointIDCounter createCheckpointIdCounter() throws Exception; /** * This test guards an assumption made in the notifications in the {@link * org.apache.flink.runtime.operators.coordination.OperatorCoordinator}. The c...
class CheckpointIDCounterTestBase { protected abstract CheckpointIDCounter createCheckpointIdCounter() throws Exception; /** * This test guards an assumption made in the notifications in the {@link * org.apache.flink.runtime.operators.coordination.OperatorCoordinator}. The coordinator is ...
Maybe `TableExtractor` could provide a `extractTablesFromDML` or `extractTablesFromSQLStatement` function to hide these calls.
private Collection<SimpleTableSegment> extractTablesFromExplain(final ExplainStatement sqlStatement) { Collection<SimpleTableSegment> result = new LinkedList<>(); ExplainStatementHandler.getSimpleTableSegment(sqlStatement).ifPresent(result::add); SQLStatement explainableStatement = sqlStatement....
extractor.extractTablesFromDelete((DeleteStatement) explainableStatement);
private Collection<SimpleTableSegment> extractTablesFromExplain(final ExplainStatement sqlStatement) { Collection<SimpleTableSegment> result = new LinkedList<>(); ExplainStatementHandler.getSimpleTableSegment(sqlStatement).ifPresent(result::add); SQLStatement explainableStatement = sqlStatement....
class ExplainStatementContext extends CommonSQLStatementContext<ExplainStatement> implements TableAvailable { private final TablesContext tablesContext; public ExplainStatementContext(final ExplainStatement sqlStatement) { super(sqlStatement); tablesContext = new TablesContext(extractT...
class ExplainStatementContext extends CommonSQLStatementContext<ExplainStatement> implements TableAvailable { private final TablesContext tablesContext; public ExplainStatementContext(final ExplainStatement sqlStatement) { super(sqlStatement); tablesContext = new TablesContext(extractT...
thank you, this operator chain looks what we want!
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) ...
new AmqpException(true, "Session receive link completed without being active", null)))
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...
Yes, according to the design doc, it has to go as POST.
private Mono<RxDocumentServiceResponse> deleteByPartitionKey(RxDocumentServiceRequest request) { return this.performRequest(request, HttpMethod.POST); }
return this.performRequest(request, HttpMethod.POST);
private Mono<RxDocumentServiceResponse> deleteByPartitionKey(RxDocumentServiceRequest request) { return this.performRequest(request, HttpMethod.POST); }
class RxGatewayStoreModel implements RxStoreModel { private final static byte[] EMPTY_BYTE_ARRAY = {}; private final DiagnosticsClientContext clientContext; private final Logger logger = LoggerFactory.getLogger(RxGatewayStoreModel.class); private final Map<String, String> defaultHeaders; private fin...
class RxGatewayStoreModel implements RxStoreModel { private final static byte[] EMPTY_BYTE_ARRAY = {}; private final DiagnosticsClientContext clientContext; private final Logger logger = LoggerFactory.getLogger(RxGatewayStoreModel.class); private final Map<String, String> defaultHeaders; private fin...
Ah yes, I can't read :man_facepalming:
private List<Path> getMatchingFiles(Instant from, Instant to) { Map<Path, Instant> paths = new HashMap<>(); try { Files.walkFileTree(logDirectory, new SimpleFileVisitor<>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes att...
if (entry.getValue().isAfter(to))
private List<Path> getMatchingFiles(Instant from, Instant to) { Map<Path, Instant> paths = new HashMap<>(); try { Files.walkFileTree(logDirectory, new SimpleFileVisitor<>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes att...
class LogReader { private final Path logDirectory; private final Pattern logFilePattern; LogReader(String logDirectory, String logFilePattern) { this(Paths.get(Defaults.getDefaults().underVespaHome(logDirectory)), Pattern.compile(logFilePattern)); } LogReader(Path logDirectory, Pattern lo...
class LogReader { private final Path logDirectory; private final Pattern logFilePattern; LogReader(String logDirectory, String logFilePattern) { this(Paths.get(Defaults.getDefaults().underVespaHome(logDirectory)), Pattern.compile(logFilePattern)); } LogReader(Path logDirectory, Pattern lo...
maybe ABORTED is better, didn't want to overload a status that is uses on the backend. should we add a new enum value?
public static CompleteCommit forFailedWork(Commit commit) { return create(commit, CommitStatus.DEFAULT); }
return create(commit, CommitStatus.DEFAULT);
public static CompleteCommit forFailedWork(Commit commit) { return create(commit, CommitStatus.ABORTED); }
class CompleteCommit { public static CompleteCommit create(Commit commit, CommitStatus commitStatus) { return new AutoValue_CompleteCommit( commit.computationId(), ShardedKey.create(commit.request().getKey(), commit.request().getShardingKey()), WorkId.builder() .setWorkToken(c...
class CompleteCommit { public static CompleteCommit create(Commit commit, CommitStatus commitStatus) { return new AutoValue_CompleteCommit( commit.computationId(), ShardedKey.create(commit.request().getKey(), commit.request().getShardingKey()), WorkId.builder() .setWorkToken(c...
I have added a new failure reason named `JOB_FAILOVER_REGION` for this scene.
private void restart(long globalModVersionOfFailover) { try { if (transitionState(JobStatus.CREATED, JobStatus.RUNNING)) { if (executionGraph.getCheckpointCoordinator() != null) { executionGraph.getCheckpointCoordinator().abortPendingCheckpoints(new CheckpointException(CheckpointFai...
executionGraph.getCheckpointCoordinator().abortPendingCheckpoints(new CheckpointException(CheckpointFailureReason.JOB_FAILURE));
private void restart(long globalModVersionOfFailover) { try { if (transitionState(JobStatus.CREATED, JobStatus.RUNNING)) { if (executionGraph.getCheckpointCoordinator() != null) { executionGraph.getCheckpointCoordinator().abortPendingCheckpoints( new CheckpointException(Checkp...
class FailoverRegion { private static final AtomicReferenceFieldUpdater<FailoverRegion, JobStatus> STATE_UPDATER = AtomicReferenceFieldUpdater.newUpdater(FailoverRegion.class, JobStatus.class, "state"); /** The log object used for debugging. */ private static final Logger LOG = LoggerFactory.getLogger(FailoverR...
class FailoverRegion { private static final AtomicReferenceFieldUpdater<FailoverRegion, JobStatus> STATE_UPDATER = AtomicReferenceFieldUpdater.newUpdater(FailoverRegion.class, JobStatus.class, "state"); /** The log object used for debugging. */ private static final Logger LOG = LoggerFactory.getLogger(FailoverR...
I don't think we can use `==` here
public static boolean decimalSubtypeContains(SubtypeData d, EnumerableDecimal f) { if (d instanceof AllOrNothingSubtype) { return ((AllOrNothingSubtype) d).isAllSubtype(); } DecimalSubtype v = (DecimalSubtype) d; for (EnumerableType val : v.values) { if (val == f...
if (val == f) {
public static boolean decimalSubtypeContains(SubtypeData d, EnumerableDecimal f) { if (d instanceof AllOrNothingSubtype) { return ((AllOrNothingSubtype) d).isAllSubtype(); } DecimalSubtype v = (DecimalSubtype) d; for (EnumerableType val : v.values) { if (val == f...
class DecimalSubtype extends EnumerableSubtype implements ProperSubtypeData { public boolean allowed; public EnumerableDecimal[] values; private DecimalSubtype(boolean allowed, EnumerableDecimal value) { this(allowed, new EnumerableDecimal[]{value}); } private DecimalSubtype(boolean allowe...
class DecimalSubtype extends EnumerableSubtype implements ProperSubtypeData { public boolean allowed; public EnumerableDecimal[] values; private DecimalSubtype(boolean allowed, EnumerableDecimal value) { this(allowed, new EnumerableDecimal[]{value}); } private DecimalSubtype(boolean allowe...
Ok,I will check if the return value of `getCatalog` is null
public void run() { for (Map.Entry<Long, Integer[]> entry : refreshMap.entrySet()) { Long catalogId = entry.getKey(); Integer[] timeGroup = entry.getValue(); Integer original = timeGroup[0]; Integer current = timeGroup[1]; if (c...
String catalogName = Env.getCurrentEnv().getCatalogMgr().getCatalog(catalogId).getName();
public void run() { for (Map.Entry<Long, Integer[]> entry : refreshMap.entrySet()) { Long catalogId = entry.getKey(); Integer[] timeGroup = entry.getValue(); Integer original = timeGroup[0]; Integer current = timeGroup[1]; if (c...
class TaskRefresh implements Runnable { @Override }
class RefreshTask implements Runnable { @Override }
I saw you have tests with finish reasons `stop` and `length`. How about cases for `content_filter` or `null`? I actually don't know how useful those would be, I only found them when searching for `finish_reason` [values](https://platform.openai.com/docs/guides/chat/response-format) (which I only could only find with a...
static void assertCompletions(int choicesPerPrompt, Completions actual) { assertCompletions(choicesPerPrompt, "stop", actual); }
assertCompletions(choicesPerPrompt, "stop", actual);
static void assertCompletions(int choicesPerPrompt, Completions actual) { assertCompletions(choicesPerPrompt, "stop", actual); }
class OpenAIClientTestBase extends TestProxyTestBase { OpenAIClientBuilder getOpenAIClientBuilder(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { OpenAIClientBuilder builder = new OpenAIClientBuilder() .httpClient(httpClient) .httpLogOptions(new HttpLogOptions().setLog...
class OpenAIClientTestBase extends TestProxyTestBase { OpenAIClientBuilder getOpenAIClientBuilder(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { OpenAIClientBuilder builder = new OpenAIClientBuilder() .httpClient(httpClient) .httpLogOptions(new HttpLogOptions().setLog...
Please use the scheduled executor service from ExecutorOptions once it is merged from https://github.com/apache/beam/pull/23234
private void doClose() { try { closeAutoscaler(); closeConsumer(); ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); executorService.schedule( () -> { LOG.debug( "Closing session and connection afte...
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
private void doClose() { try { closeAutoscaler(); closeConsumer(); ScheduledExecutorService executorService = options.as(ExecutorOptions.class).getScheduledExecutorService(); executorService.schedule( () -> { LOG.debug( "Clos...
class UnboundedJmsReader<T> extends UnboundedReader<T> { private UnboundedJmsSource<T> source; private JmsCheckpointMark checkpointMark; private Connection connection; private Session session; private MessageConsumer consumer; private AutoScaler autoScaler; private T currentMessage; pr...
class UnboundedJmsReader<T> extends UnboundedReader<T> { private UnboundedJmsSource<T> source; private JmsCheckpointMark checkpointMark; private Connection connection; private Session session; private MessageConsumer consumer; private AutoScaler autoScaler; private T currentMessage; pr...
## Accessing files should not lead to filesystem oracle attacks <!--SONAR_ISSUE_KEY:AYtAxwZ6agaDI_wZ9Hvt-->Change this code to not construct the path from user-controlled data. <p>See more on <a href="https://sonarcloud.io/project/issues?id=metersphere_metersphere&issues=AYtAxwZ6agaDI_wZ9Hvt&open=AYtAxwZ6agaDI_wZ9Hvt&...
public String loadPlugin(String fileName) { String filePath = MsFileUtils.PLUGIN_DIR + "/" + fileName; File file = new File(filePath); if (!file.exists()) { downloadPluginFromRepository(fileName); } return msPluginManager.loadPlugin(Paths.get(filePath)); ...
public String loadPlugin(String fileName) { MsFileUtils.validateFileName(fileName); String filePath = MsFileUtils.PLUGIN_DIR + "/" + fileName; File file = new File(filePath); if (!file.exists()) { downloadPluginFromRepository(fileName); } return m...
class PluginLoadService { @Resource private PluginMapper pluginMapper; @Resource private PluginScriptMapper pluginScriptMapper; private MsPluginManager msPluginManager = new MsPluginManager(); /** * 从文件系统中加载jar * * @param fileName * @return */ /** * 从默认...
class PluginLoadService { @Resource private PluginMapper pluginMapper; @Resource private PluginScriptMapper pluginScriptMapper; private MsPluginManager msPluginManager = new MsPluginManager(); /** * 从文件系统中加载jar * * @param fileName * @return */ /** * 从默认...
no idea why this particular zone requires 4G RAM, sounds wrong - should not be needed - you can leave be and we can remove once we know why we need this - @hmusum ?
private NodeResources defaultNodeResources(ClusterSpec.Type clusterType) { if (zone.system() == SystemName.PublicCd && clusterType == ClusterSpec.Type.admin && zone.environment() != Environment.prod) return new NodeResources(1, 3, 50); if (zone.system() == SystemName.cd && zone.environment(...
return new NodeResources(1, 4, 50);
private NodeResources defaultNodeResources(ClusterSpec.Type clusterType) { if (clusterType == ClusterSpec.Type.admin) return new NodeResources(0.5, 3, 50); if (zone.system() == SystemName.cd && zone.environment().isTest()) new NodeResources(4, 4, 50); return new NodeRes...
class CapacityPolicies { private final Zone zone; private final NodeFlavors flavors; public CapacityPolicies(Zone zone, NodeFlavors flavors) { this.zone = zone; this.flavors = flavors; } public int decideSize(Capacity requestedCapacity, ClusterSpec.Type clusterType) { int ...
class CapacityPolicies { private final Zone zone; private final NodeFlavors flavors; public CapacityPolicies(Zone zone, NodeFlavors flavors) { this.zone = zone; this.flavors = flavors; } public int decideSize(Capacity requestedCapacity, ClusterSpec.Type clusterType) { int ...
`restArgs.get(restArgs.size() - 1)` I think we can extract this or related logic to a variable. This is used multiple times. This will simplify the code increasing readability. L5083, L5088, L5098, L5115 (condition)
public void visit(BLangFunction funcNode) { SymbolEnv funcEnv = SymbolEnv.createFunctionEnv(funcNode, funcNode.symbol.scope, env); if (!funcNode.interfaceFunction) { addReturnIfNotPresent(funcNode); } funcNode.originalFuncSymbol = funcNode.symbol; funcNode.s...
restArgs.get(restArgs.size() - 1).getKind() == NodeKind.REST_ARGS_EXPR &&
public void visit(BLangFunction funcNode) { SymbolEnv funcEnv = SymbolEnv.createFunctionEnv(funcNode, funcNode.symbol.scope, env); if (!funcNode.interfaceFunction) { addReturnIfNotPresent(funcNode); } funcNode.originalFuncSymbol = funcNode.symbol; funcNode.s...
class Desugar extends BLangNodeVisitor { private static final CompilerContext.Key<Desugar> DESUGAR_KEY = new CompilerContext.Key<>(); private static final String QUERY_TABLE_WITH_JOIN_CLAUSE = "queryTableWithJoinClause"; private static final String QUERY_TABLE_WITHOUT_JOIN_CLAUSE = "queryTableW...
class Desugar extends BLangNodeVisitor { private static final CompilerContext.Key<Desugar> DESUGAR_KEY = new CompilerContext.Key<>(); private static final String QUERY_TABLE_WITH_JOIN_CLAUSE = "queryTableWithJoinClause"; private static final String QUERY_TABLE_WITHOUT_JOIN_CLAUSE = "queryTableW...
Can you add tests for some of the new utilities ? For example, PendingJobManager and PendingJob.
public void testWriteUnknown() throws Exception { p.apply( Create.of( new TableRow().set("name", "a").set("number", 1), new TableRow().set("name", "b").set("number", 2), new TableRow().set("name", "c").set("number", 3)) .withCod...
thrown.expectMessage("Failed to create job");
public void testWriteUnknown() throws Exception { p.apply( Create.of( new TableRow().set("name", "a").set("number", 1), new TableRow().set("name", "b").set("number", 2), new TableRow().set("name", "c").set("number", 3)) .withCod...
class PartitionedGlobalWindowCoder extends AtomicCoder<PartitionedGlobalWindow> { @Override public void encode(PartitionedGlobalWindow window, OutputStream outStream) throws IOException { encode(window, outStream, Context.NESTED); } @Override public void encode(PartitionedGlobalWindow window,...
class PartitionedGlobalWindowCoder extends AtomicCoder<PartitionedGlobalWindow> { @Override public void encode(PartitionedGlobalWindow window, OutputStream outStream) throws IOException { encode(window, outStream, Context.NESTED); } @Override public void encode(PartitionedGlobalWindow window,...
You want `attributes[1].key`. SQL arrays are 1-indexed.
public void testSQLSelectsArrayAttributes() throws Exception { String createTableString = String.format( "CREATE EXTERNAL TABLE message (\n" + "event_timestamp TIMESTAMP, \n" + "attributes ARRAY<ROW<key VARCHAR, `value` VARCHAR>>, \n" + "payload RO...
String queryString = "SELECT message.payload.id, attributes[0].key AS name FROM message";
public void testSQLSelectsArrayAttributes() throws Exception { String createTableString = String.format( "CREATE EXTERNAL TABLE message (\n" + "event_timestamp TIMESTAMP, \n" + "attributes ARRAY<ROW<key VARCHAR, `value` VARCHAR>>, \n" + "payload RO...
class PubsubTableProviderIT implements Serializable { private static final Schema PAYLOAD_SCHEMA = Schema.builder() .addNullableField("id", Schema.FieldType.INT32) .addNullableField("name", Schema.FieldType.STRING) .build(); @Rule public transient TestPubsub eventsTopic = TestP...
class PubsubTableProviderIT implements Serializable { private static final Schema PAYLOAD_SCHEMA = Schema.builder() .addNullableField("id", Schema.FieldType.INT32) .addNullableField("name", Schema.FieldType.STRING) .build(); @Rule public transient TestPubsub eventsTopic = TestP...
#37039 is resolved and add relevant changes in `2.0-stage` branch. So eventually it will merge into `2.x` branch and it will merge into the `master` branch as well.
public List<String> skipList() { return Arrays.asList("function_typedesc17.json"); }
public List<String> skipList() { return Arrays.asList("function_typedesc17.json"); }
class TypeDescContextTest extends CompletionTest { @Test(dataProvider = "completion-data-provider") @Override public void test(String config, String configPath) throws WorkspaceDocumentException, IOException { super.test(config, configPath); } @DataProvider(name = "completion-data-provider...
class TypeDescContextTest extends CompletionTest { @Test(dataProvider = "completion-data-provider") @Override public void test(String config, String configPath) throws WorkspaceDocumentException, IOException { super.test(config, configPath); } @DataProvider(name = "completion-data-provider...
We can say `isDuplicate` then. It's more intuitive.
private STNode createFuncDefNodeList(List<STNode> qualifierList) { List<STNode> validatedList = new ArrayList<>(); for (int i = 0; i < qualifierList.size(); i++) { STNode qualifier = qualifierList.get(i); int nextIndex = i + 1; if (isNodeWithSyntax...
if (isNodeWithSyntaxKindInList(validatedList, qualifier.kind)) {
private STNode createFuncDefNodeList(List<STNode> qualifierList) { List<STNode> validatedList = new ArrayList<>(); for (int i = 0; i < qualifierList.size(); i++) { STNode qualifier = qualifierList.get(i); int nextIndex = i + 1; if (isDuplicate(vali...
class definition. switch (nextNextToken.kind) { case CLIENT_KEYWORD: case READONLY_KEYWORD: case ISOLATED_KEYWORD: case CLASS_KEYWORD: return true; default: ...
class definition. switch (nextNextToken.kind) { case CLIENT_KEYWORD: case READONLY_KEYWORD: case ISOLATED_KEYWORD: case CLASS_KEYWORD: return true; default: ...
@IMS94 I didn't get any issues when testing this in a project, anyway will have a look. `endsWith()` is a string matching and has some more weird behaviors such as matching with other module's file with the same name(diag location.filePath() contains the relative path only).
public static List<CodeAction> getAvailableCodeActions(CodeActionContext ctx) { LSClientLogger clientLogger = LSClientLogger.getInstance(ctx.languageServercontext()); List<CodeAction> codeActions = new ArrayList<>(); CodeActionProvidersHolder codeActionProvidersHolder = CodeActio...
CommonUtil.isWithinRange(ctx.cursorPosition(), CommonUtil.toRange(diag.location().lineRange()))
public static List<CodeAction> getAvailableCodeActions(CodeActionContext ctx) { LSClientLogger clientLogger = LSClientLogger.getInstance(ctx.languageServercontext()); List<CodeAction> codeActions = new ArrayList<>(); CodeActionProvidersHolder codeActionProvidersHolder = CodeActio...
class CodeActionRouter { /** * Returns a list of supported code actions. * * @param ctx {@link CodeActionContext} * @return list of code actions */ }
class CodeActionRouter { /** * Returns a list of supported code actions. * * @param ctx {@link CodeActionContext} * @return list of code actions */ }
I'd prefer it to log and throw - it's an invalid Content-Range header and there is no recovery from it
public static long extractSizeFromContentRange(String contentRange) { Objects.requireNonNull(contentRange, "Cannot extract length from null 'contentRange'."); int index = contentRange.indexOf('/'); if (index == -1) { return -2; } String sizeString = con...
return -2;
public static long extractSizeFromContentRange(String contentRange) { Objects.requireNonNull(contentRange, "Cannot extract length from null 'contentRange'."); int index = contentRange.indexOf('/'); if (index == -1) { throw LOGGER.logExceptionAsError(new IllegalArgumentE...
class from an array of Objects. * * @param args Array of objects to search through to find the first instance of the given `clazz` type. * @param clazz The type trying to be found. * @param <T> Generic type * @return The first object of the desired type, otherwise null. */ public stati...
class from an array of Objects. * * @param args Array of objects to search through to find the first instance of the given `clazz` type. * @param clazz The type trying to be found. * @param <T> Generic type * @return The first object of the desired type, otherwise null. */ public stati...
Why modify this? I think `org.assertj.core.api.Assertions.assertThat` is suggested test API.
void testCreateAndCloseSessions() throws Exception { List<SessionHandle> sessionHandles = new ArrayList<>(); Set<String> sessionHandleIds = new HashSet<>(); for (int num = 0; num < SESSION_NUMBER; ++num) { CompletableFuture<OpenSessionResponseBody> response = send...
assertNotNull(sessionHandleId);
void testCreateAndCloseSessions() throws Exception { List<SessionHandle> sessionHandles = new ArrayList<>(); Set<String> sessionHandleIds = new HashSet<>(); for (int num = 0; num < SESSION_NUMBER; ++num) { CompletableFuture<OpenSessionResponseBody> response = send...
class SessionRelatedITCase extends RestAPIITCaseBase { private static final String SESSION_NAME = "test"; private static final Map<String, String> properties = new HashMap<>(); private static final int SESSION_NUMBER = 10; static { properties.put("k1", "v1"); properties.put("k2", "v2")...
class SessionRelatedITCase extends RestAPIITCaseBase { private static final String SESSION_NAME = "test"; private static final Map<String, String> properties = new HashMap<>(); private static final int SESSION_NUMBER = 10; static { properties.put("k1", "v1"); properties.put("k2", "v2")...
what will happen if not set startTimemMs?
public void analyze(Analyzer analyzer) throws UserException { super.analyze(analyzer); checkAuth(); labelName.analyze(analyzer); String dbName = labelName.getDbName(); Env.getCurrentInternalCatalog().getDbOrAnalysisException(dbName); analyzerSqlStmt(); ...
timerDefinition.setStartTimeMs(System.currentTimeMillis() - 100L);
public void analyze(Analyzer analyzer) throws UserException { super.analyze(analyzer); checkAuth(); labelName.analyze(analyzer); String dbName = labelName.getDbName(); Env.getCurrentInternalCatalog().getDbOrAnalysisException(dbName); analyzerSqlStmt(); ...
class CreateJobStmt extends DdlStmt { @Getter private StatementBase doStmt; @Getter private AbstractJob jobInstance; private final LabelName labelName; private final String onceJobStartTimestamp; private final Long interval; private final String intervalTimeUnit; private final...
class CreateJobStmt extends DdlStmt { @Getter private StatementBase doStmt; @Getter private AbstractJob jobInstance; private final LabelName labelName; private final String onceJobStartTimestamp; private final Long interval; private final String intervalTimeUnit; private final...
@franz1981 could pls update the comment as well? `private final Lock 1l = new ReentrantLock();` => `private volatile Lock 1l`. I know it's nitpicking but... ;-)
Collection<Resource> generate(DotName scope) { List<BeanInfo> beans = new BeanStream(beanDeployment.getBeans()).withScope(scope).collect(); ResourceClassOutput classOutput = new ResourceClassOutput(true, generateSources); String generatedName = scopeToGeneratedName.get(scope); reflection...
Collection<Resource> generate(DotName scope) { List<BeanInfo> beans = new BeanStream(beanDeployment.getBeans()).withScope(scope).collect(); ResourceClassOutput classOutput = new ResourceClassOutput(true, generateSources); String generatedName = scopeToGeneratedName.get(scope); reflection...
class ContextInstancesGenerator extends AbstractGenerator { static final String CONTEXT_INSTANCES_SUFFIX = "_ContextInstances"; private final BeanDeployment beanDeployment; private final Map<DotName, String> scopeToGeneratedName; public ContextInstancesGenerator(boolean generateSources, ReflectionReg...
class ContextInstancesGenerator extends AbstractGenerator { static final String CONTEXT_INSTANCES_SUFFIX = "_ContextInstances"; private final BeanDeployment beanDeployment; private final Map<DotName, String> scopeToGeneratedName; public ContextInstancesGenerator(boolean generateSources, ReflectionReg...
Not sure. So I made a new check here.
public void clearSparkLauncherLog() { String logPath = sparkLoadAppHandle.getLogPath(); if (!Strings.isNullOrEmpty(logPath)) { File file = new File(logPath); if (file.exists()) { file.delete(); } } }
String logPath = sparkLoadAppHandle.getLogPath();
public void clearSparkLauncherLog() { if (sparkLoadAppHandle != null) { String logPath = sparkLoadAppHandle.getLogPath(); if (!Strings.isNullOrEmpty(logPath)) { File file = new File(logPath); if (file.exists()) { file.delete(); ...
class SparkLoadJob extends BulkLoadJob { private static final Logger LOG = LogManager.getLogger(SparkLoadJob.class); private SparkResource sparkResource; private long etlStartTimestamp = -1; private String appId = ""; private String etlOutputPath = ""; private...
class SparkLoadJob extends BulkLoadJob { private static final Logger LOG = LogManager.getLogger(SparkLoadJob.class); private SparkResource sparkResource; private long etlStartTimestamp = -1; private String appId = ""; private String etlOutputPath = ""; private...
```suggestion getProject().getLogger().warn("quarkus info is experimental, its options and output might change in future versions"); ``` In maven output this comes possibly many many lines away from what you just executed thus better to be explicit.
public void logInfo() { getProject().getLogger().warn("This task is experimental, its options and output might change in future versions"); final QuarkusProject quarkusProject = getQuarkusProject(false); final Map<String, Object> params = new HashMap<>(); params.put(UpdateCommandHandle...
getProject().getLogger().warn("This task is experimental, its options and output might change in future versions");
public void logInfo() { getProject().getLogger().warn(getName() + " is experimental, its options and output might change in future versions"); final QuarkusProject quarkusProject = getQuarkusProject(false); final Map<String, Object> params = new HashMap<>(); params.put(UpdateCommandHan...
class QuarkusInfo extends QuarkusPlatformTask { private boolean perModule = false; @Input public boolean getPerModule() { return perModule; } @Option(description = "Log project's state per module.", option = "perModule") public void setPerModule(boolean perModule) { this.perMo...
class QuarkusInfo extends QuarkusPlatformTask { private boolean perModule = false; @Input public boolean getPerModule() { return perModule; } @Option(description = "Log project's state per module.", option = "perModule") public void setPerModule(boolean perModule) { this.perMo...
yeah agree, ideally. Just not confident enough and want to keep the change limited to what necessary to fix bug (though change is already not minor)
public WriteResult expandUntriggered(PCollection<KV<DestinationT, ElementT>> input) { Pipeline p = input.getPipeline(); final PCollectionView<String> loadJobIdPrefixView = createJobIdPrefixView(p, JobType.LOAD); final PCollectionView<String> tempLoadJobIdPrefixView = createJobIdPrefixView(p, JobType...
PCollection<TableDestination> successfulMultiPartitionWrites =
public WriteResult expandUntriggered(PCollection<KV<DestinationT, ElementT>> input) { Pipeline p = input.getPipeline(); final PCollectionView<String> loadJobIdPrefixView = createJobIdPrefixView(p, JobType.LOAD); final PCollectionView<String> tempLoadJobIdPrefixView = createJobIdPrefixView(p, JobType...
class BatchLoads<DestinationT, ElementT> extends PTransform<PCollection<KV<DestinationT, ElementT>>, WriteResult> { private static final Logger LOG = LoggerFactory.getLogger(BatchLoads.class); @VisibleForTesting static final int DEFAULT_MAX_NUM_WRITERS_PER_BUNDLE = 20; @VisibleFor...
class BatchLoads<DestinationT, ElementT> extends PTransform<PCollection<KV<DestinationT, ElementT>>, WriteResult> { private static final Logger LOG = LoggerFactory.getLogger(BatchLoads.class); @VisibleForTesting static final int DEFAULT_MAX_NUM_WRITERS_PER_BUNDLE = 20; @VisibleFor...
that might be done by Netty under the hood, what is the purpose of keeping the transfer-encoding untouched ? perhaps there is something wrong that should be fixed
public static void runTest(String endpoint, String acceptEncoding, String contentEncoding, String contentLength) { LOG.infof("Endpoint %s; Accept-Encoding: %s; Content-Encoding: %s; Content-Length: %s", endpoint, acceptEncoding, contentEncoding, contentLength); ...
client.requestAbs(HttpMethod.GET, endpoint)
public static void runTest(String endpoint, String acceptEncoding, String contentEncoding, String contentLength) { LOG.infof("Endpoint %s; Accept-Encoding: %s; Content-Encoding: %s; Content-Length: %s", endpoint, acceptEncoding, contentEncoding, contentLength); ...
class Testflow { /** * This test logic is shared by both "all" module and "some" module. * See their RESTEndpointsTest classes. * * @param endpoint * @param acceptEncoding * @param contentEncoding * @param contentLength */ }
class Testflow { public static final int COMPRESSION_TOLERANCE_PERCENT = 2; /** * This test logic is shared by both "all" module and "some" module. * See their RESTEndpointsTest classes. * * @param endpoint * @param acceptEncoding * @param contentEncoding * @p...
do you think creating a github issue and putting it here will help to keep track of this?
static void validateMultipageReceiptData(List<RecognizedForm> recognizedReceipts) { assertEquals(3, recognizedReceipts.size()); RecognizedForm receiptPage1 = recognizedReceipts.get(0); RecognizedForm receiptPage2 = recognizedReceipts.get(1); RecognizedForm receiptPage3 = recognizedReceip...
static void validateMultipageReceiptData(List<RecognizedForm> recognizedReceipts) { assertEquals(3, recognizedReceipts.size()); RecognizedForm receiptPage1 = recognizedReceipts.get(0); RecognizedForm receiptPage2 = recognizedReceipts.get(1); RecognizedForm receiptPage3 = recognizedReceip...
class FormRecognizerClientTestBase extends TestBase { private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final String EXPECTED_MULTIPAGE_ADDRESS_VALUE = "123 Hobbit Lane 567 Main St. Redmond, WA Redmond," + " WA"; private static final String EXPECTED_MULTIPA...
class FormRecognizerClientTestBase extends TestBase { private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final String EXPECTED_MULTIPAGE_ADDRESS_VALUE = "123 Hobbit Lane 567 Main St. Redmond, WA Redmond," + " WA"; private static final String EXPECTED_MULTIPA...
This should be in a try with resources block, or better yet just use Files.write()
public static void writeFile(OutputTargetBuildItem target, String name, String output) throws IOException { FileOutputStream os = new FileOutputStream(target.getOutputDirectory().resolve(name).toFile()); os.write(output.getBytes(StandardCharsets.UTF_8)); os.close(); }
FileOutputStream os = new FileOutputStream(target.getOutputDirectory().resolve(name).toFile());
public static void writeFile(OutputTargetBuildItem target, String name, String output) throws IOException { Path artifact = target.getOutputDirectory().resolve(name); String targetUri = target.getOutputDirectory().resolve("function.zip").toUri().toString().replace("file:", "fileb:"); output = ou...
class LambdaUtil { /** * Strips period, dash, and numbers. Turns characters after to uppercase. i.e. * Also strips "-SNAPSHOT" from end of name. * * "foo.bar-1.0-SNAPSHOT" to "FooBar" * * @param basename * @return */ public static String artifactToLambda(String basename)...
class LambdaUtil { /** * Strips period, dash, and numbers. Turns characters after to uppercase. i.e. * Also strips "-SNAPSHOT" from end of name. * * "foo.bar-1.0-SNAPSHOT" to "FooBar" * * @param basename * @return */ public static String artifactToLambda(String basename)...
The cache generation is skipped for the pulled packages because platform dependencies are found in them and not for the platform dependencies. So does this change properly give that meaning?
static boolean pullDependencyPackages(String orgName, String packageName, String version) { Path ballerinaUserHomeDirPath = ProjectUtils.createAndGetHomeReposPath(); Path centralRepositoryDirPath = ballerinaUserHomeDirPath.resolve(ProjectConstants.REPOSITORIES_DIR) .resolve(ProjectConsta...
errStream.println("Warning: Cache generation skipped due to platform dependencies with 'provided' scope");
static boolean pullDependencyPackages(String orgName, String packageName, String version) { Path ballerinaUserHomeDirPath = ProjectUtils.createAndGetHomeReposPath(); Path centralRepositoryDirPath = ballerinaUserHomeDirPath.resolve(ProjectConstants.REPOSITORIES_DIR) .resolve(ProjectConsta...
class CommandUtil { public static final String ORG_NAME = "ORG_NAME"; public static final String PKG_NAME = "PKG_NAME"; public static final String DIST_VERSION = "DIST_VERSION"; public static final String TOOL_ID = "TOOL_ID"; public static final String USER_HOME = "user.home"; public static fina...
class CommandUtil { public static final String ORG_NAME = "ORG_NAME"; public static final String PKG_NAME = "PKG_NAME"; public static final String DIST_VERSION = "DIST_VERSION"; public static final String TOOL_ID = "TOOL_ID"; public static final String USER_HOME = "user.home"; public static fina...
Made this change to fix CCE for `redeclared variable ANS7` ``` const NUM1 = -1; const int NUM2 = -9223372036854775807 - 1; const int ANS7 = NUM2 - 1; const int ANS7 = NUM2 + NUM1; ``` Is that acceptable?
private void checkUniqueness(BLangConstant constant) { if (constant.symbol.kind == SymbolKind.CONSTANT) { String nameString = constant.name.value; BLangConstantValue value = constant.symbol.value; if (constantMap.containsKey(nameString)) { if (value == null) ...
if (!value.toString().equals(lastValue.toString())) {
private void checkUniqueness(BLangConstant constant) { if (constant.symbol.kind == SymbolKind.CONSTANT) { String nameString = constant.name.value; BLangConstantValue value = constant.symbol.value; if (constantMap.containsKey(nameString)) { if (value == null) ...
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; ...
Add some code comments here ? ```java /* sum = */ ifThenElse(isNull(operands()[0]), sum, minus(sum, operands()[0])), ```
public Expression[] retractExpressions() { return new Expression[] { ifThenElse(isNull(operands()[0]), sum, minus(sum, operands()[0])), ifThenElse(isNull(operands()[0]), count, minus(count, literal(1L))), }; }
ifThenElse(isNull(operands()[0]), sum, minus(sum, operands()[0])),
public Expression[] retractExpressions() { return new Expression[] { /* sum = */ ifThenElse(isNull(operand(0)), sum, minus(sum, operand(0))), /* count = */ ifThenElse(isNull(operand(0)), count, minus(count, literal(1L))), }; }
class AvgAggFunction extends DeclarativeAggregateFunction { private UnresolvedAggBufferReference sum = new UnresolvedAggBufferReference("sum", getSumType()); private UnresolvedAggBufferReference count = new UnresolvedAggBufferReference("count", Types.LONG); public TypeInformation getSumType() { return Types.LONG...
class AvgAggFunction extends DeclarativeAggregateFunction { private FieldReferenceExpression sum = new FieldReferenceExpression("sum", getSumType()); private FieldReferenceExpression count = new FieldReferenceExpression("count", Types.LONG); public TypeInformation getSumType() { return Types.LONG; } @Override...
```suggestion if (operation.getParameters() != null && operation.getParameters().size() > 0) { ```
private void setPaths(OpenAPI openAPI) throws BallerinaOpenApiException { if (openAPI.getPaths() == null) { return; } this.paths = new LinkedHashSet<>(); Paths pathList = openAPI.getPaths(); for (Map.Entry<String, PathItem> path : pathList.entrySet()) { s...
if (null != operation.getParameters() && operation.getParameters().size() > 0) {
private void setPaths(OpenAPI openAPI) throws BallerinaOpenApiException { if (openAPI.getPaths() == null) { return; } this.paths = new LinkedHashSet<>(); Paths pathList = openAPI.getPaths(); for (Map.Entry<String, PathItem> path : pathList.entrySet()) { s...
class BallerinaOpenApi implements BallerinaOpenApiObject<BallerinaOpenApi, OpenAPI> { private String srcPackage; private String modelPackage; private String openapi = "3.0.0"; private String definitionPath = ""; private Info info = null; private ExternalDocumentation externalDocs = null; pri...
class BallerinaOpenApi implements BallerinaOpenApiObject<BallerinaOpenApi, OpenAPI> { private String srcPackage; private String modelPackage; private String openapi = "3.0.0"; private String definitionPath = ""; private Info info = null; private ExternalDocumentation externalDocs = null; pri...
Hm, nice catch. Shouldn't always trust the IDE's suggested changes it seems. Will fix.
private Optional<String> childAsString(Optional<ModelElement> element, String childTagName) { return element.map(modelElement -> modelElement.childAsString(childTagName)); }
return element.map(modelElement -> modelElement.childAsString(childTagName));
private Optional<String> childAsString(Optional<ModelElement> element, String childTagName) { if (element.isEmpty()) return Optional.empty(); return Optional.ofNullable(element.get().childAsString(childTagName)); }
class XmlNodeBuilder { private final ModelElement clusterElement; private final ModelElement element; private XmlNodeBuilder(ModelElement clusterElement, ModelElement element) { this.clusterElement = clusterElement; this.element = element; ...
class XmlNodeBuilder { private final ModelElement clusterElement; private final ModelElement element; private XmlNodeBuilder(ModelElement clusterElement, ModelElement element) { this.clusterElement = clusterElement; this.element = element; ...
Do we need to get the current catalog at this point? You handle that during the execution already, don't you?
public Operation convertSqlNode(SqlShowDatabases sqlShowDatabases, ConvertContext context) { if (sqlShowDatabases.getPreposition() == null) { return new ShowDatabasesOperation( sqlShowDatabases.getLikeType(), sqlShowDatabases.getLikeSqlPattern(), ...
: fullCatalogName[0];
public Operation convertSqlNode(SqlShowDatabases sqlShowDatabases, ConvertContext context) { if (sqlShowDatabases.getPreposition() == null) { return new ShowDatabasesOperation( sqlShowDatabases.getLikeType(), sqlShowDatabases.getLikeSqlPattern(), ...
class SqlShowDatabasesConverter implements SqlNodeConverter<SqlShowDatabases> { @Override }
class SqlShowDatabasesConverter implements SqlNodeConverter<SqlShowDatabases> { @Override }
```suggestion final int cnt = 2 + userToAuthenticationInfo.size() * 2; ```
public void save(DataOutputStream dos) throws IOException { try { final int cnt = 1 + 1 + userToAuthenticationInfo.size() * 2; SRMetaBlockWriter writer = new SRMetaBlockWriter(dos, AuthenticationManager.class.getName(), cnt); writer.writeJson(this); ...
final int cnt = 1 + 1 + userToAuthenticationInfo.size() * 2;
public void save(DataOutputStream dos) throws IOException { try { final int cnt = 1 + 1 + userToAuthenticationInfo.size() * 2; SRMetaBlockWriter writer = new SRMetaBlockWriter(dos, AuthenticationManager.class.getName(), cnt); writer.writeJson(this); ...
class AuthenticationManager { private static final Logger LOG = LogManager.getLogger(AuthenticationManager.class); private static final String DEFAULT_PLUGIN = PlainPasswordAuthenticationProvider.PLUGIN_NAME; public static final String ROOT_USER = "root"; @Expose(serialize = false) priva...
class AuthenticationManager { private static final Logger LOG = LogManager.getLogger(AuthenticationManager.class); private static final String DEFAULT_PLUGIN = PlainPasswordAuthenticationProvider.PLUGIN_NAME; public static final String ROOT_USER = "root"; private Map<UserIdentity, UserA...
Will this log be printed frequently when no more data to consume?
public boolean hasMoreDataToConsume(UUID taskId, Map<Integer, Long> partitionIdToOffset) throws UserException { for (Map.Entry<Integer, Long> entry : partitionIdToOffset.entrySet()) { if (cachedPartitionWithLatestOffsets.containsKey(entry.getKey()) && entry.getValue() < cachedPar...
LOG.info("no more data to consume. offsets to be consumed: {}, latest offsets: {}, task {}, job {}",
public boolean hasMoreDataToConsume(UUID taskId, Map<Integer, Long> partitionIdToOffset) throws UserException { for (Map.Entry<Integer, Long> entry : partitionIdToOffset.entrySet()) { if (cachedPartitionWithLatestOffsets.containsKey(entry.getKey()) && entry.getValue() < cachedPar...
class KafkaRoutineLoadJob extends RoutineLoadJob { private static final Logger LOG = LogManager.getLogger(KafkaRoutineLoadJob.class); public static final String KAFKA_FILE_CATALOG = "kafka"; public static final String PROP_GROUP_ID = "group.id"; private String brokerList; private String topic; ...
class KafkaRoutineLoadJob extends RoutineLoadJob { private static final Logger LOG = LogManager.getLogger(KafkaRoutineLoadJob.class); public static final String KAFKA_FILE_CATALOG = "kafka"; public static final String PROP_GROUP_ID = "group.id"; private String brokerList; private String topic; ...
Actually, `isEmpty` is not implemented :smile: There are just too many ways of checking if a collection is empty or not
public void testBasicInfo() { TestingOneInputStreamOperator inOperator1 = new TestingOneInputStreamOperator(); TestingOneInputStreamOperator inOperator2 = new TestingOneInputStreamOperator(); TestingTwoInputStreamOperator outOperator = new TestingTwoInputStreamOperator(); TableOperatorWr...
assertThat(wrapper2.getInputWrappers().isEmpty()).isTrue();
public void testBasicInfo() { TestingOneInputStreamOperator inOperator1 = new TestingOneInputStreamOperator(); TestingOneInputStreamOperator inOperator2 = new TestingOneInputStreamOperator(); TestingTwoInputStreamOperator outOperator = new TestingTwoInputStreamOperator(); TableOperatorWr...
class TableOperatorWrapperTest extends MultipleInputTestBase { @Test @Test public void testCreateOperator() throws Exception { TestingOneInputStreamOperator operator = new TestingOneInputStreamOperator(); TableOperatorWrapper<TestingOneInputStreamOperator> wrapper = cr...
class TableOperatorWrapperTest extends MultipleInputTestBase { @Test @Test public void testCreateOperator() throws Exception { TestingOneInputStreamOperator operator = new TestingOneInputStreamOperator(); TableOperatorWrapper<TestingOneInputStreamOperator> wrapper = cr...
The tabletInfo will be added to the `List<TabletInfo>`
private void sendTasks() { Map<ComputeNode, List<TabletInfo>> beToTabletInfos = new HashMap<>(); for (Tablet tablet : tablets.values()) { ComputeNode node = Utils.chooseNode((LakeTablet) tablet); if (node == null) { LOG.warn("Stop sending table...
beToTabletInfos.computeIfAbsent(node, k -> Lists.newArrayList()).add(tabletInfo);
private void sendTasks() { Map<ComputeNode, List<TabletInfo>> beToTabletInfos = new HashMap<>(); for (Tablet tablet : tablets.values()) { ComputeNode node = Utils.chooseNode((LakeTablet) tablet); if (node == null) { LOG.warn("Stop sending table...
class CollectTabletStatJob { private final String dbName; private final String tableName; private final long partitionId; private final long version; private final Map<Long, Tablet> tablets; private List<Future<TabletStatResponse>> responseList; CollectTabletStat...
class CollectTabletStatJob { private final String dbName; private final String tableName; private final long partitionId; private final long version; private final Map<Long, Tablet> tablets; private long collectStatTime = 0; private List<Future<TabletStatResponse>...
I think we should gradually refactor existing generated operators. Take `AggregateWindowOperator` as an exmple, every generated class has two objects, e.g. `aggWindowAggregator` and `generatedAggWindowAggregator`, etc.. And they are all nullable, and we have to add a lot of `if else` to compile them in `open` method. ...
public StreamOperator createStreamOperator(StreamTask containingTask, StreamConfig config, Output output) { WatermarkGenerator watermarkGenerator = generatedWatermarkGenerator.newInstance(containingTask.getUserCodeClassLoader()); WatermarkAssignerOperator operator = new WatermarkAssignerOperator(rowtimeFieldIndex, ...
WatermarkAssignerOperator operator = new WatermarkAssignerOperator(rowtimeFieldIndex, watermarkGenerator, idleTimeout);
public StreamOperator createStreamOperator(StreamTask containingTask, StreamConfig config, Output output) { WatermarkGenerator watermarkGenerator = generatedWatermarkGenerator.newInstance(containingTask.getUserCodeClassLoader()); WatermarkAssignerOperator operator = new WatermarkAssignerOperator(rowtimeFieldIndex, ...
class WatermarkAssignerOperatorFactory implements OneInputStreamOperatorFactory<BaseRow, BaseRow> { private static final long serialVersionUID = 1L; private final int rowtimeFieldIndex; private final long idleTimeout; private final GeneratedWatermarkGenerator generatedWatermarkGenerator; private ChainingStrate...
class WatermarkAssignerOperatorFactory implements OneInputStreamOperatorFactory<BaseRow, BaseRow> { private static final long serialVersionUID = 1L; private final int rowtimeFieldIndex; private final long idleTimeout; private final GeneratedWatermarkGenerator generatedWatermarkGenerator; private ChainingStrate...
Same comment here, need to get rid of this .block() too
public void canDeleteExistingMessage() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block(); StepVerifier.create(chatThreadClient.deleteMessage(response.getId()...
SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block();
public void canDeleteExistingMessage() { SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions(); StepVerifier.create( chatThreadClient.sendMessage(messageRequest) .flatMap(response -> { return chatThreadClient.d...
class ChatThreadAsyncClientTest extends ChatClientTestBase { private ClientLogger logger = new ClientLogger(ChatThreadAsyncClientTest.class); private CommunicationIdentityClient communicationClient; private ChatAsyncClient client; private ChatThreadAsyncClient chatThreadClient; private String thre...
class ChatThreadAsyncClientTest extends ChatClientTestBase { private ClientLogger logger = new ClientLogger(ChatThreadAsyncClientTest.class); private CommunicationIdentityClient communicationClient; private ChatAsyncClient client; private ChatThreadAsyncClient chatThreadClient; private String thre...
Method `loginUserFromKeytabAndReturnUGI` does't set the current login user but `loginUserFromKeytab` does, I've used `loginUserFromKeytab` instead.
protected void initLocalObjectsImpl() { HiveConf hiveConf = new HiveConf(); for (String key : catalogProperty.getHdfsProperties().keySet()) { String val = catalogProperty.getOrDefault(key, ""); hiveConf.set(key, val); } String authentication = catalogProperty.get...
UserGroupInformation.setLoginUser(ugi);
protected void initLocalObjectsImpl() { HiveConf hiveConf = new HiveConf(); for (String key : catalogProperty.getHdfsProperties().keySet()) { String val = catalogProperty.getOrDefault(key, ""); hiveConf.set(key, val); } String authentication = catalogProperty.get...
class HMSExternalCatalog extends ExternalCatalog { private static final Logger LOG = LogManager.getLogger(HMSExternalCatalog.class); private static final int MAX_CLIENT_POOL_SIZE = 8; protected PooledHiveMetaStoreClient client; /** * Default constructor for HMSExternalCatalog. */ public ...
class HMSExternalCatalog extends ExternalCatalog { private static final Logger LOG = LogManager.getLogger(HMSExternalCatalog.class); private static final int MAX_CLIENT_POOL_SIZE = 8; protected PooledHiveMetaStoreClient client; /** * Default constructor for HMSExternalCatalog. */ public ...
It may be better to call `TransactionTestConstants.ACCOUNT, 6)` before calling rollback.
private void assertRollback() throws SQLException { Connection conn = getDataSource().getConnection(); conn.setAutoCommit(false); assertTableRowCount(conn, TransactionTestConstants.ACCOUNT, 0); executeWithLog(conn, "insert into account(id, BALANCE, TRANSACTION_ID) values(1, 1, 1),(2, 2, ...
assertTableRowCount(conn, TransactionTestConstants.ACCOUNT, 0);
private void assertRollback() throws SQLException { Connection conn = getDataSource().getConnection(); conn.setAutoCommit(false); assertTableRowCount(conn, TransactionTestConstants.ACCOUNT, 0); executeWithLog(conn, "insert into account(id, BALANCE, TRANSACTION_ID) values(1, 1, 1),(2, 2, ...
class AddResourceTestCase extends BaseTransactionTestCase { public AddResourceTestCase(final BaseTransactionITCase baseTransactionITCase, final DataSource dataSource) { super(baseTransactionITCase, dataSource); } @Override @SneakyThrows public void executeTest() { assertAdd...
class AddResourceTestCase extends BaseTransactionTestCase { public AddResourceTestCase(final BaseTransactionITCase baseTransactionITCase, final DataSource dataSource) { super(baseTransactionITCase, dataSource); } @Override @SneakyThrows public void executeTest() { assertAdd...
The most risky bug in this code is: The `KuduTable` constructor does not initialize the `properties`, `masterAddresses`, `catalogName`, `databaseName`, `tableName`, and `partColNames` fields which could lead to NullPointerException when accessing these fields. You can modify the code like this: ```java public KuduTabl...
public List<String> getPartitionColumnNames() { return partColNames; }
return partColNames;
public List<String> getPartitionColumnNames() { return partColNames; }
class KuduTable extends Table { private static final Logger LOG = LogManager.getLogger(KuduTable.class); public static final Set<String> KUDU_INPUT_FORMATS = Sets.newHashSet( "org.apache.hadoop.hive.kudu.KuduInputFormat", "org.apache.kudu.mapreduce.KuduTableInputFormat"); public static final Str...
class KuduTable extends Table { private static final Logger LOG = LogManager.getLogger(KuduTable.class); public static final Set<String> KUDU_INPUT_FORMATS = Sets.newHashSet( "org.apache.hadoop.hive.kudu.KuduInputFormat", "org.apache.kudu.mapreduce.KuduTableInputFormat"); public static final Str...
> we had to patch Arc in the past to remove some of these as they had a signifcant impact on benchmarks I do remember quite a few optimizations I'm not exactly proud of :shrug:. > you won't notice on micro benchmarks unless you're using all CPUs So I'd personally avoid them All benchmarks are tricky because they run...
public ArcContainerImpl(CurrentContextFactory currentContextFactory, boolean strictMode) { this.strictMode = strictMode; id = String.valueOf(ID_GENERATOR.incrementAndGet()); running = new AtomicBoolean(true); List<InjectableBean<?>> beans = new ArrayList<>(); Map<String, List<Inj...
this.beansByRawType = Map.copyOf(beansByRawType);
public ArcContainerImpl(CurrentContextFactory currentContextFactory, boolean strictMode) { this.strictMode = strictMode; id = String.valueOf(ID_GENERATOR.incrementAndGet()); running = new AtomicBoolean(true); List<InjectableBean<?>> beans = new ArrayList<>(); Map<String, List<Inj...
class ArcContainerImpl implements ArcContainer { private static final Logger LOGGER = Logger.getLogger(ArcContainerImpl.class.getPackage().getName()); private static final AtomicInteger ID_GENERATOR = new AtomicInteger(); private final String id; private final AtomicBoolean running; private fina...
class ArcContainerImpl implements ArcContainer { private static final Logger LOGGER = Logger.getLogger(ArcContainerImpl.class.getPackage().getName()); private static final AtomicInteger ID_GENERATOR = new AtomicInteger(); private final String id; private final AtomicBoolean running; private fina...
Is there a possibility of getting `null` here?
public static Hover getHover(HoverContext context) { Optional<Document> srcFile = context.currentDocument(); Optional<SemanticModel> semanticModel = context.currentSemanticModel(); if (semanticModel.isEmpty() || srcFile.isEmpty()) { return HoverUtil.getHoverObject(""); } ...
if (symbol == null || symbol.isEmpty() || !symbolResolver.isSymbolReferable()) {
public static Hover getHover(HoverContext context) { Optional<Document> srcFile = context.currentDocument(); Optional<SemanticModel> semanticModel = context.currentSemanticModel(); if (semanticModel.isEmpty() || srcFile.isEmpty()) { return HoverUtil.getHoverObject(""); } ...
class HoverUtil { /** * Get the hover content. * * @param context Hover operation context * @return {@link Hover} Hover content */ /** * returns the default hover object. * * @return {@link Hover} hover object. */ protected static Hover getHoverObject() { ...
class HoverUtil { /** * Get the hover content. * * @param context Hover operation context * @return {@link Hover} Hover content */ /** * returns the default hover object. * * @return {@link Hover} hover object. */ protected static Hover getHoverObject() { ...
The pattern of lock should be: ``` olapTable.writeLock(); try { ...... } finally { olapTable.writeUnlock(); }
public void modifyDefaultDistributionBucketNum(Database db, OlapTable olapTable, ModifyDistributionClause modifyDistributionClause) throws DdlException { olapTable.writeLock(); if (olapTable.isColocateTable()) { throw new DdlException("Cannot change default bucket number of colocate table."...
throw new DdlException("Cannot assign hash distribution with different distribution cols. "
public void modifyDefaultDistributionBucketNum(Database db, OlapTable olapTable, ModifyDistributionClause modifyDistributionClause) throws DdlException { olapTable.writeLock(); try { if (olapTable.isColocateTable()) { throw new DdlException("Cannot change default bucket numb...
class SingletonHolder { private static final Catalog INSTANCE = new Catalog(); }
class SingletonHolder { private static final Catalog INSTANCE = new Catalog(); }
Sorry for a bit late response. > 1. There are two types of scenarios where we enqueue to the mailbox (1) to handle fatal exceptions and (2) to add to the buffer any failed request entries. I believe, these should take priority over flushing new items? Apart of that, (2) has also a very important purpose to mark decre...
public void write(InputT element, Context context) throws IOException, InterruptedException { while (mailboxExecutor.tryYield()) {} while (bufferedRequestEntries.size() >= maxBufferedRequests) { flush(); } addEntryToBuffer(elementConverter.apply(element, context), false); ...
while (mailboxExecutor.tryYield()) {}
public void write(InputT element, Context context) throws IOException, InterruptedException { while (bufferedRequestEntries.size() >= maxBufferedRequests) { flush(); } addEntryToBuffer(elementConverter.apply(element, context), false); nonBlockingFlush(); }
class AsyncSinkWriter<InputT, RequestEntryT extends Serializable> implements SinkWriter<InputT, Void, Collection<RequestEntryT>> { private final MailboxExecutor mailboxExecutor; private final Sink.ProcessingTimeService timeService; /* The timestamp of the previous batch of records was sent from th...
class AsyncSinkWriter<InputT, RequestEntryT extends Serializable> implements StatefulSink.StatefulSinkWriter<InputT, BufferedRequestState<RequestEntryT>> { private static final int INFLIGHT_MESSAGES_LIMIT_INCREASE_RATE = 10; private static final double INFLIGHT_MESSAGES_LIMIT_DECREASE_FACTOR = 0.5; ...
I think by two steps Kenn meant that we could merge a PR that did not support processing-time timers and then a second PR that added that support.
private void setAndVerifyOutputTimestamp() { if (outputTimestamp != null && !TimeDomain.EVENT_TIME.equals(spec.getTimeDomain())) { throw new IllegalStateException("Cannot set outputTimestamp in processing time domain."); } if (outputTimestamp == null) { outputTimestamp = ...
throw new IllegalStateException("Cannot set outputTimestamp in processing time domain.");
private void setAndVerifyOutputTimestamp() { if (outputTimestamp != null && !TimeDomain.EVENT_TIME.equals(spec.getTimeDomain())) { throw new IllegalStateException("Cannot set outputTimestamp in processing time domain."); } if (outputTimestamp == null) { outputTimestamp = ...
class TimerInternalsTimer implements Timer { private final TimerInternals timerInternals; private final BoundedWindow window; private final StateNamespace namespace; private final String timerId; private final TimerSpec spec; private Instant target; private Instant outputTime...
class TimerInternalsTimer implements Timer { private final TimerInternals timerInternals; private final BoundedWindow window; private final StateNamespace namespace; private final String timerId; private final TimerSpec spec; private Instant target; private Instant outputTime...
Add comment on these are the min/max values that can be represented as ZetaSQL NUMERIC?
public void testNumericLiteral() { String sql = "SELECT NUMERIC '0', " + "NUMERIC '123456', " + "NUMERIC '-3.14', " + "NUMERIC '-0.54321', " + "NUMERIC '1.23456e05', " + "NUMERIC '-9.876e-3', " + "NUMERIC '-99999999999999999999999999999...
+ "NUMERIC '-99999999999999999999999999999.999999999', "
public void testNumericLiteral() { String sql = "SELECT NUMERIC '0', " + "NUMERIC '123456', " + "NUMERIC '-3.14', " + "NUMERIC '-0.54321', " + "NUMERIC '1.23456e05', " + "NUMERIC '-9.876e-3', " + "NUMERIC '-9999999999999999...
class ZetaSqlDialectSpecTest extends ZetaSqlTestBase { @Rule public transient TestPipeline pipeline = TestPipeline.create(); @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setUp() { initialize(); } @Test public void testSimpleSelect() { String sql = ...
class ZetaSqlDialectSpecTest extends ZetaSqlTestBase { @Rule public transient TestPipeline pipeline = TestPipeline.create(); @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setUp() { initialize(); } @Test public void testSimpleSelect() { String sql = ...
Are we sure length of payload is not 0 here ?
private static String lowerCaseTheFirstLetter(String payload) { char[] characters = payload.toCharArray(); characters[0] = Character.toLowerCase(characters[0]); payload = new String(characters); return payload; }
characters[0] = Character.toLowerCase(characters[0]);
private static String lowerCaseTheFirstLetter(String payload) { if (!payload.isEmpty()) { char[] characters = payload.toCharArray(); characters[0] = Character.toLowerCase(characters[0]); payload = new String(characters); } return payload; }
class HttpUtil { private static final Logger log = LoggerFactory.getLogger(HttpUtil.class); private static final String METHOD_ACCESSED = "isMethodAccessed"; private static final String IO_EXCEPTION_OCCURED = "I/O exception occurred"; private static BStructType headerValueStructType; public static...
class HttpUtil { private static final Logger log = LoggerFactory.getLogger(HttpUtil.class); private static final String METHOD_ACCESSED = "isMethodAccessed"; private static final String IO_EXCEPTION_OCCURED = "I/O exception occurred"; private static BStructType headerValueStructType; public static...
I still don't think this is a real issue. If there is a RESTEasy request is progress then CP will have captured the context, so it should be propagated everywhere and there is no change of behaviour. The only way this will be missing is if a request is started with no request is progress, and then ends up in a RESTEasy...
public ThreadContextSnapshot currentContext(Map<String, String> props) { Map<Class<?>, Object> context = ResteasyContext.getContextDataMap(false); if (context == null) { return null; } return () -> { ResteasyContext.pushContextDataMap(context); return ...
return null;
public ThreadContextSnapshot currentContext(Map<String, String> props) { Map<Class<?>, Object> context = ResteasyContext.getContextDataMap(false); if (context == null) { return null; } return () -> { ResteasyContext.pushContextDataMap(context); return ...
class ResteasyContextProvider implements ThreadContextProvider { private static final String JAXRS_CONTEXT = "JAX-RS"; @Override @Override public ThreadContextSnapshot clearedContext(Map<String, String> props) { Map<Class<?>, Object> context = Collections.emptyMap(); return () ->...
class ResteasyContextProvider implements ThreadContextProvider { private static final String JAXRS_CONTEXT = "JAX-RS"; @Override @Override public ThreadContextSnapshot clearedContext(Map<String, String> props) { Map<Class<?>, Object> context = Collections.emptyMap(); return () ->...
we can make two sources have same length to achieve the same goal, then to void too many vars.
public void testAccumulateWithCopy() { final int firstSourceLength = 128; final int firstSourceStartPosition = 32; final int secondSourceLength = 64; final int secondSourceStartPosition = 0; final int expectedAccumulationSize = 128; final int firstCopyLength = firstSourceLength - firstSourceStartPosition; ...
final int secondSourceLength = 64;
public void testAccumulateWithCopy() { int sourceLength = 128; int firstSourceReaderIndex = 32; int secondSourceReaderIndex = 0; int expectedAccumulationSize = 128; int firstAccumulationSize = sourceLength - firstSourceReaderIndex; int secondAccumulationSize = expectedAccumulationSize - firstAccumulationSi...
class ByteBufUtilsTest { @Test public void testAccumulateWithoutCopy() { final int sourceLength = 128; final int sourceStartPosition = 32; final int expectedAccumulationSize = 16; ByteBuf src = createSourceBuffer(sourceLength, sourceStartPosition); ByteBuf target = Unpooled.buffer(expectedAccumulationSiz...
class ByteBufUtilsTest extends TestLogger { private static final byte ACCUMULATION_BYTE = 0x7d; private static final byte NON_ACCUMULATION_BYTE = 0x23; @Test public void testAccumulateWithoutCopy() { int sourceLength = 128; int sourceReaderIndex = 32; int expectedAccumulationSize = 16; ByteBuf src = creat...
This change makes sense. We don't have any tests that cover this for the issue that's resolved in this PR, though (reverting the change in `Executing` won't cause any failures). We might want to add another test like that one: ```java @Test public void testNotifyNewResourcesAvailableWithCanScaleUpWi...
private Executing build(MockExecutingContext ctx) { executionGraph.transitionToRunning(); try { return new Executing( executionGraph, getExecutionGraphHandler(executionGraph, ctx.getMainThreadExecutor()), op...
try {
private Executing build(MockExecutingContext ctx) { executionGraph.transitionToRunning(); try { return new Executing( executionGraph, getExecutionGraphHandler(executionGraph, ctx.getMainThreadExecutor()), op...
class ExecutingStateBuilder { private ExecutionGraph executionGraph = TestingDefaultExecutionGraphBuilder.newBuilder() .build(EXECUTOR_RESOURCE.getExecutor()); private OperatorCoordinatorHandler operatorCoordinatorHandler; private Duration scalingIntervalM...
class ExecutingStateBuilder { private ExecutionGraph executionGraph = TestingDefaultExecutionGraphBuilder.newBuilder() .build(EXECUTOR_RESOURCE.getExecutor()); private OperatorCoordinatorHandler operatorCoordinatorHandler; private Duration scalingIntervalM...
``` if (dataType.hasPriority() || dataType.requiresAnnouncement()) { firstPriorityEvent = addPriorityBuffer(announce(sequenceBuffer)); } if (!dataType.hasPriority()) { receivedBuffers.add(sequenceBuffer); channelStatePersister.maybePersist(buffer); } ```
public void onBuffer(Buffer buffer, int sequenceNumber, int backlog) throws IOException { boolean recycleBuffer = true; try { if (expectedSequenceNumber != sequenceNumber) { onError(new BufferReorderingException(expectedSequenceNumber, sequenceNumber)); return; } final boolean wasEmpty; boolea...
checkPriorityXorAnnouncement(buffer);
public void onBuffer(Buffer buffer, int sequenceNumber, int backlog) throws IOException { boolean recycleBuffer = true; try { if (expectedSequenceNumber != sequenceNumber) { onError(new BufferReorderingException(expectedSequenceNumber, sequenceNumber)); return; } final boolean wasEmpty; boolea...
class RemoteInputChannel extends InputChannel implements ChannelStateHolder { public static final int ALL = -1; /** ID to distinguish this channel from other channels sharing the same TCP connection. */ private final InputChannelID id = new InputChannelID(); /** The connection to use to request the remote partiti...
class RemoteInputChannel extends InputChannel implements ChannelStateHolder { public static final int ALL = -1; /** ID to distinguish this channel from other channels sharing the same TCP connection. */ private final InputChannelID id = new InputChannelID(); /** The connection to use to request the remote partiti...
I didn't pay attention, tbh. I'll add the brackets.
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (dir.equals(root) || dir.toString().equals("/") || dir.startsWith(devTemplatesPath)) return FileVisitResult.CONTINUE; return FileVisitResult.SKIP_SUBTREE; ...
if (dir.equals(root) || dir.toString().equals("/") || dir.startsWith(devTemplatesPath))
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (dir.equals(root) || dir.toString().equals("/") || dir.startsWith(devTemplatesPath)) { return FileVisitResult.CONTINUE; } return FileVisitResult.SKIP_...
class DevConsoleProcessor { private static final Logger log = Logger.getLogger(DevConsoleProcessor.class); private static final String STATIC_RESOURCES_PATH = "dev-static/"; private static final Object EMPTY = new Object(); private static final String[] suffixes = new String[] { "html", "txt" };...
class DevConsoleProcessor { private static final Logger log = Logger.getLogger(DevConsoleProcessor.class); private static final String STATIC_RESOURCES_PATH = "dev-static/"; private static final Object EMPTY = new Object(); private static final String[] suffixes = new String[] { "html", "txt" };...
Shall we add tests for error throwing if not already covered
public static BString toExpString(double x, Object fractionDigits) { BString str = FloatUtils.getBStringIfInfiniteOrNaN(x); if (str != null) { return str; } long noOfFractionDigits; double xAbsValue = Math.abs(x); if (fractionDigits == null...
throw ErrorUtils.createInvalidFractionDigitsError();
public static BString toExpString(double x, Object fractionDigits) { BString str = FloatUtils.getBStringIfInfiniteOrNaN(x); if (str != null) { return str; } long noOfFractionDigits; double xAbsValue = Math.abs(x); if (fractionDigits == null...
class ToExpString { }
class ToExpString { }
Do we have an issue to fix these, https://github.com/ballerina-platform/ballerina-spec/issues/724#issuecomment-771358941
public void testTypeGuardNegative() { CompileResult negativeResult = BCompileUtil.compile("test-src/statements/ifelse/type-guard-negative.bal"); int i = 0; BAssertUtil.validateError(negativeResult, i++, "incompatible types: 'string' will not be matched to 'int'", 20, 27); ...
public void testTypeGuardNegative() { CompileResult negativeResult = BCompileUtil.compile("test-src/statements/ifelse/type-guard-negative.bal"); int i = 0; BAssertUtil.validateError(negativeResult, i++, "incompatible types: 'string' will not be matched to 'int'", 20, 27); ...
class TypeGuardTest { CompileResult result; @BeforeClass public void setup() { result = BCompileUtil.compile("test-src/statements/ifelse/type-guard.bal"); } @Test @Test public void testTypeGuardSemanticsNegative() { CompileResult negativeResult = BCompileUtil.compile...
class TypeGuardTest { CompileResult result; @BeforeClass public void setup() { result = BCompileUtil.compile("test-src/statements/ifelse/type-guard.bal"); } @Test @Test public void testTypeGuardSemanticsNegative() { CompileResult negativeResult = BCompileUtil.compile...
AvroUtils.toAvroSchema() method provides an avroSchema from the BeamSchema. But the avroSchema geenrated does not have the name of the avroSchema. Now when I use this avroSchema (without the name) to write/read records it fails with error SchemaParseException: No name in schema: {"type":"record","fields": ......
public PDone buildIOWriter(PCollection<Row> input) { PTransform<PCollection<Row>, PCollection<GenericRecord>> writeConverter = GenericRecordWriteConverter.builder().beamSchema(schema).build(); return input .apply("GenericRecordToRow", writeConverter) .apply( "AvroIOWrite", ...
AvroIO.writeGenericRecords(AvroUtils.toAvroSchema(schema, tableName, null))
public PDone buildIOWriter(PCollection<Row> input) { PTransform<PCollection<Row>, PCollection<GenericRecord>> writeConverter = GenericRecordWriteConverter.builder().beamSchema(schema).build(); return input .apply("GenericRecordToRow", writeConverter) .apply( "AvroIOWrite", ...
class AvroTable extends BaseBeamTable implements Serializable { private final String filePattern; private final String tableName; public AvroTable(String tableName, Schema beamSchema, String filePattern) { super(beamSchema); this.filePattern = filePattern; this.tableName = tableName; } @Override...
class AvroTable extends BaseBeamTable implements Serializable { private final String filePattern; private final String tableName; public AvroTable(String tableName, Schema beamSchema, String filePattern) { super(beamSchema); this.filePattern = filePattern; this.tableName = tableName; } @Override...
Based on the known information, it seems that using a time-based gc is already effectively controlling memory usage. Directly limiting memory usage to a maximum of only 5% would introduce other variables and compromise stability. It is recommended to maintain consistency with previous behavior for now.
public void getBinlogInfo(Database db, BaseProcResult result) { BinlogConfig binlogConfig = binlogConfigCache.getTableBinlogConfig(dbId, tableId); String tableName = null; String dropped = null; if (db == null) { tableName = "(dropped).(unknown)"; dropped = "true...
binlogMaxBytes = String.valueOf(binlogConfig.getMaxBytes());
public void getBinlogInfo(Database db, BaseProcResult result) { BinlogConfig binlogConfig = binlogConfigCache.getTableBinlogConfig(dbId, tableId); String tableName = null; String dropped = null; if (db == null) { tableName = "(dropped).(unknown)"; dropped = "true...
class TableBinlog { private static final Logger LOG = LogManager.getLogger(TableBinlog.class); private long dbId; private long tableId; private long binlogSize; private ReentrantReadWriteLock lock; private TreeSet<TBinlog> binlogs; private List<Pair<Long, Long>> timestamps; ...
class TableBinlog { private static final Logger LOG = LogManager.getLogger(TableBinlog.class); private long dbId; private long tableId; private long binlogSize; private ReentrantReadWriteLock lock; private TreeSet<TBinlog> binlogs; private List<Pair<Long, Long>> timestamps; ...
This is already done in BuildCommandTest. `testResources` here is a temporary directory with test resources copied from the original location.
public void testBuildProjectPrecompiledWithOlderDistWithoutStickyFlag() throws IOException { Path projectPath = testResources.resolve("dep-dist-version-projects").resolve("preCompiledPackage"); replaceDependenciesTomlContent(projectPath, "**INSERT_DISTRIBUTION_VERSION_HERE**", "2201.5.0"); Syste...
replaceDependenciesTomlContent(projectPath, RepoUtils.getBallerinaShortVersion(),
public void testBuildProjectPrecompiledWithOlderDistWithoutStickyFlag() throws IOException { Path projectPath = testResources.resolve("dep-dist-version-projects").resolve("preCompiledPackage"); replaceDependenciesTomlContent(projectPath, "**INSERT_DISTRIBUTION_VERSION_HERE**", "2201.5.0"); Syste...
class file */ @Test(description = "Build a ballerina project with conflicted jars") public void testBuildBalProjectWithJarConflicts() throws IOException { Path projectPath = this.testResources.resolve("projectWithConflictedJars"); System.setProperty("user.dir", projectPath.toString()); ...
class file */ @Test(description = "Build a ballerina project with conflicted jars") public void testBuildBalProjectWithJarConflicts() throws IOException { Path projectPath = this.testResources.resolve("projectWithConflictedJars"); System.setProperty("user.dir", projectPath.toString()); ...
LOG.warn("Exception: {} does not exist", dbName, e);
public void removeDatabase(String dbName) { if (closing) { return; } try { LOG.info("begin to remove database {} from replicatedEnviroment", dbName); replicatedEnvironment.removeDatabase(null, dbName); LOG.info("remove database {} fro...
LOG.warn("catch an exception when remove db:{}, this db does not exist", dbName, e);
public void removeDatabase(String dbName) { if (closing) { return; } try { replicatedEnvironment.removeDatabase(null, dbName); LOG.info("remove database {} from replicatedEnviroment successfully", dbName); } catch (DatabaseNotFoundExcepti...
class BDBEnvironment { private static final Logger LOG = LogManager.getLogger(BDBEnvironment.class); protected static int RETRY_TIME = 3; protected static int SLEEP_INTERVAL_SEC = 5; private static final int MEMORY_CACHE_PERCENT = 20; private static final int INITAL_STATE_CHANGE_WAIT_SEC = 10; ...
class BDBEnvironment { private static final Logger LOG = LogManager.getLogger(BDBEnvironment.class); protected static int RETRY_TIME = 3; protected static int SLEEP_INTERVAL_SEC = 5; private static final int MEMORY_CACHE_PERCENT = 20; private static final int INITAL_STATE_CHANGE_WAIT_SEC = 10; ...
super() should be first in method
protected void doPrepare(DeployState deployState) { addAndSendApplicationBundles(deployState); sendUserConfiguredFiles(deployState); createEndpointList(deployState); super.doPrepare(deployState); }
super.doPrepare(deployState);
protected void doPrepare(DeployState deployState) { super.doPrepare(deployState); addAndSendApplicationBundles(deployState); sendUserConfiguredFiles(deployState); createEndpointList(deployState); }
class ApplicationContainerCluster extends ContainerCluster<ApplicationContainer> implements ApplicationBundlesConfig.Producer, QrStartConfig.Producer, RankProfilesConfig.Producer, RankingConstantsConfig.Producer, OnnxModelsConfig.Producer, RankingExpressionsConfig.Produce...
class ApplicationContainerCluster extends ContainerCluster<ApplicationContainer> implements ApplicationBundlesConfig.Producer, QrStartConfig.Producer, RankProfilesConfig.Producer, RankingConstantsConfig.Producer, OnnxModelsConfig.Producer, RankingExpressionsConfig.Produce...
We don't have any standard defined; as you mentioned, it's case by case. For this specific case, I was thinking something like (please review/consider if there is a better format) ```java final String id = "trackingId:" + System.nanoTime(); logger.info("Unable to acquire new session. {}", id, error); Mono.<Long>error(...
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...
Precicely, I wanted to use the same exact keys as Spring Boot does for the benefit of users who might want to migrate.
InfoBuildTimeValuesBuildItem buildInfo(CurateOutcomeBuildItem curateOutcomeBuildItem, InfoBuildTimeConfig config) { ApplicationModel applicationModel = curateOutcomeBuildItem.getApplicationModel(); ResolvedDependency appArtifact = applicationModel.getAppArtifact(); Map<String, Object> buildData ...
buildData.put("artifact", appArtifact.getArtifactId());
InfoBuildTimeValuesBuildItem buildInfo(CurateOutcomeBuildItem curateOutcomeBuildItem, InfoBuildTimeConfig config) { ApplicationModel applicationModel = curateOutcomeBuildItem.getApplicationModel(); ResolvedDependency appArtifact = applicationModel.getAppArtifact(); Map<String, Object> buildData ...
class InfoProcessor { private static final Logger log = Logger.getLogger(InfoProcessor.class); @BuildStep(onlyIf = GitInInfoEndpointEnabled.class) InfoBuildTimeValuesBuildItem gitInfo(CurateOutcomeBuildItem curateOutcomeBuildItem, OutputTargetBuildItem outputTargetBuildItem) { File pro...
class InfoProcessor { private static final Logger log = Logger.getLogger(InfoProcessor.class); @BuildStep(onlyIf = GitInInfoEndpointEnabled.class) InfoBuildTimeValuesBuildItem gitInfo(CurateOutcomeBuildItem curateOutcomeBuildItem, OutputTargetBuildItem outputTargetBuildItem) { File pro...
```suggestion childAccessPaths.stream().distinct() ``` and add some comment?
private Optional<AccessPath> process(ScalarOperator scalarOperator, Deque<AccessPath> accessPaths) { List<Optional<AccessPath>> childAccessPaths = scalarOperator.getChildren().stream() .map(child -> process(child, accessPaths)) .collect(Collectors.toList(...
childAccessPaths.stream().filter(p -> p.isPresent() && p.get() != path)
private Optional<AccessPath> process(ScalarOperator scalarOperator, Deque<AccessPath> accessPaths) { List<Optional<AccessPath>> childAccessPaths = scalarOperator.getChildren().stream() .map(child -> process(child, accessPaths)) .collect(Collectors.toList(...
class Collector extends ScalarOperatorVisitor<Optional<AccessPath>, List<Optional<AccessPath>>> { @Override public Optional<AccessPath> visit(ScalarOperator scalarOperator, List<Optional<AccessPath>> childrenAccessPaths) { return Optional.empty(); ...
class Collector extends ScalarOperatorVisitor<Optional<AccessPath>, List<Optional<AccessPath>>> { @Override public Optional<AccessPath> visit(ScalarOperator scalarOperator, List<Optional<AccessPath>> childrenAccessPaths) { return Optional.empty(); ...
If you look at the comments you see this can not be used for anything machine readable. * If length is 4 or less the string will be truncated to length. * If length is longer than 4, it will be truncated at length-4 with " ..." added at the end. We have a lot of public methods that we have only added for our...
public boolean annotate(StringFieldValue text) { if (text.getSpanTree(SpanTrees.LINGUISTICS) != null) return true; Tokenizer tokenizer = factory.getTokenizer(); String input = (text.getString().length() <= config.getMaxTokenizeLength()) ? text.getString() : Tex...
: Text.safeSubstring(text.getString(), config.getMaxTokenizeLength());
public boolean annotate(StringFieldValue text) { if (text.getSpanTree(SpanTrees.LINGUISTICS) != null) return true; Tokenizer tokenizer = factory.getTokenizer(); String input = (text.getString().length() <= config.getMaxTokenizeLength()) ? text.getString() : Tex...
class TermOccurrences { final Map<String, Integer> termOccurrences = new HashMap<>(); final int maxOccurrences; public TermOccurrences(int maxOccurences) { this.maxOccurrences = maxOccurences; } boolean termCountBelowLimit(String term) { String lowerCas...
class TermOccurrences { final Map<String, Integer> termOccurrences = new HashMap<>(); final int maxOccurrences; public TermOccurrences(int maxOccurences) { this.maxOccurrences = maxOccurences; } boolean termCountBelowLimit(String term) { String lowerCas...
Why don't we have a static variable for this one?
public void validateUserGroupProperties() { if (this.sessionStateless) { if (allowedGroupsConfigured()) { LOGGER.warn("Group names are not supported if you set 'sessionSateless' to 'true'."); } } else if (!allowedGroupsConfigured()) { throw new Illegal...
&& !"transitive".equalsIgnoreCase(groupRelationship)) {
public void validateUserGroupProperties() { if (this.sessionStateless) { if (allowedGroupsConfigured()) { LOGGER.warn("Group names are not supported if you set 'sessionSateless' to 'true'."); } } else if (!allowedGroupsConfigured()) { throw new Illegal...
class UserGroupProperties { /** * Expected UserGroups that an authority will be granted to if found in the response from the MemeberOf Graph * API Call. */ private List<String> allowedGroups = new ArrayList<>(); /** * Key of the JSON Node to get from the Azu...
class UserGroupProperties { /** * Expected UserGroups that an authority will be granted to if found in the response from the MemeberOf Graph * API Call. */ private List<String> allowedGroups = new ArrayList<>(); /** * Key of the JSON Node to get from the Azu...
Add it into method Javadoc please
public SerializationProxy(Read read) { configuration = read.configuration; tableId = read.tableId; scan = read.scan; }
configuration = read.configuration;
public SerializationProxy(Read read) { configuration = read.configuration; tableId = read.tableId; scan = read.scan; }
class SerializationProxy implements Serializable { public SerializationProxy() {} private void writeObject(ObjectOutputStream out) throws IOException { SerializableCoder.of(SerializableConfiguration.class) .encode(new SerializableConfiguration(this.configuration), out); ...
class SerializationProxy implements Serializable { public SerializationProxy() {} private void writeObject(ObjectOutputStream out) throws IOException { SerializableCoder.of(SerializableConfiguration.class) .encode(new SerializableConfiguration(this.configuration), out); ...
I have added test cases for Integer, String.
public void queryItemsAggregate() { long startTime = Instant.now().getEpochSecond(); List<String> actualIds = new ArrayList<>(); EncryptionPojo properties = getItem(UUID.randomUUID().toString()); cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk())...
CosmosPagedFlux<JsonNode> feedResponseIterator1 =
public void queryItemsAggregate() { long startTime = Instant.now().getEpochSecond(); List<String> actualIds = new ArrayList<>(); EncryptionPojo properties = getItem(UUID.randomUUID().toString()); cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk())...
class EncryptionAsyncApiCrudTest extends TestSuiteBase { private CosmosAsyncClient client; private CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient; private CosmosEncryptionAsyncContainer encryptionContainerWithIncompatiblePolicyVersion; CosmosEncryptionAsyncContainer cosmosEncryptionAsyncContai...
class EncryptionAsyncApiCrudTest extends TestSuiteBase { private CosmosAsyncClient client; private CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient; private CosmosEncryptionAsyncContainer encryptionContainerWithIncompatiblePolicyVersion; CosmosEncryptionAsyncContainer cosmosEncryptionAsyncContai...
I think you can just do the same in your new Consumer and it should give the same result that you are after.
public Handler<RoutingContext> authenticationMechanismHandler(boolean proactiveAuthentication) { return new Handler<RoutingContext>() { volatile HttpAuthenticator authenticator; @Override public void handle(RoutingContext event) { if (authenticator == null) ...
event.put(QuarkusHttpUser.AUTH_FAILURE_HANDLER, new BiConsumer<RoutingContext, Throwable>() {
public Handler<RoutingContext> authenticationMechanismHandler(boolean proactiveAuthentication) { return new Handler<RoutingContext>() { volatile HttpAuthenticator authenticator; @Override public void handle(RoutingContext event) { if (authenticator == null) ...
class HttpSecurityRecorder { private static final Logger log = Logger.getLogger(HttpSecurityRecorder.class); protected static final Consumer<Throwable> NOOP_CALLBACK = new Consumer<Throwable>() { @Override public void accept(Throwable throwable) { } }; final RuntimeValue<HttpC...
class HttpSecurityRecorder { private static final Logger log = Logger.getLogger(HttpSecurityRecorder.class); protected static final Consumer<Throwable> NOOP_CALLBACK = new Consumer<Throwable>() { @Override public void accept(Throwable throwable) { } }; final RuntimeValue<HttpC...
I will look into it, reported https://github.com/quarkusio/quarkus/issues/1419 I don't have the permission to assign it to myself though.
public void registerBaseMetrics(ShutdownContext shutdown) { MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.BASE); List<GarbageCollectorMXBean> gcs = ManagementFactory.getGarbageCollectorMXBeans(); List<String> names = new ArrayList<>(); for (GarbageCollectorMXBean gc ...
for (String i : names) {
public void registerBaseMetrics(ShutdownContext shutdown) { MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.BASE); List<GarbageCollectorMXBean> gcs = ManagementFactory.getGarbageCollectorMXBeans(); List<String> names = new ArrayList<>(); for (GarbageCollectorMXBean gc ...
class SmallRyeMetricsTemplate { private static final Logger log = Logger.getLogger("io.quarkus.metrics"); private static final String MEMORY_HEAP_USAGE = "memory.heap.usage"; private static final String MEMORY_NON_HEAP_USAGE = "memory.nonHeap.usage"; private static final String THREAD_COUNT = "thread.c...
class SmallRyeMetricsTemplate { private static final Logger log = Logger.getLogger("io.quarkus.metrics"); private static final String MEMORY_HEAP_USAGE = "memory.heap.usage"; private static final String MEMORY_NON_HEAP_USAGE = "memory.nonHeap.usage"; private static final String THREAD_COUNT = "thread.c...
Consider including the exception in the log entry (so that the stack trace is printed to the log).
private JsonResponse v1Response(URI requestUri) { try { return new JsonResponse(OK, v1Content(requestUri)); } catch (JSONException e) { log.warning("Bad JSON construction in " + V1_PATH + " response: " + e.getMessage()); return new ErrorResponse(INTERNAL_SERVER_ERROR...
log.warning("Bad JSON construction in " + V1_PATH + " response: " + e.getMessage());
private JsonResponse v1Response(URI requestUri) { try { return new JsonResponse(OK, v1Content(requestUri)); } catch (JSONException e) { log.warning("Bad JSON construction in " + V1_PATH + " response: " + e.getMessage()); return new ErrorResponse(INTERNAL_SERVER_ERROR...
class MetricsHandler extends ThreadedHttpRequestHandler { static final String V1_PATH = "/metrics/v1"; static final String VALUES_PATH = V1_PATH + "/values"; private final ValuesFetcher valuesFetcher; @Inject public MetricsHandler(Executor executor, MetricsManager metric...
class MetricsHandler extends ThreadedHttpRequestHandler { static final String V1_PATH = "/metrics/v1"; static final String VALUES_PATH = V1_PATH + "/values"; private final ValuesFetcher valuesFetcher; @Inject public MetricsHandler(Executor executor, MetricsManager metric...
It does not get invoked when the deprecated params doc is not available. So null check is removed
public void exitDeprecatedParametersDocumentation(BallerinaParser.DeprecatedParametersDocumentationContext ctx) { if (isInErrorState) { return; } String str = ctx.DeprecatedParametersDocumentation() != null ? ctx.DeprecatedParametersDocumentation().getText() : ""; ...
String str = ctx.DeprecatedParametersDocumentation() != null ?
public void exitDeprecatedParametersDocumentation(BallerinaParser.DeprecatedParametersDocumentationContext ctx) { if (isInErrorState) { return; } this.pkgBuilder.endDeprecatedParametersDocumentation(getCurrentPos(ctx.getParent()), getWS(ctx)); }
class BLangParserListener extends BallerinaParserBaseListener { private static final String KEYWORD_PUBLIC = "public"; private static final String KEYWORD_KEY = "key"; private BLangPackageBuilder pkgBuilder; private BDiagnosticSource diagnosticSrc; private BLangDiagnosticLogHelper dlog; privat...
class BLangParserListener extends BallerinaParserBaseListener { private static final String KEYWORD_PUBLIC = "public"; private static final String KEYWORD_KEY = "key"; private BLangPackageBuilder pkgBuilder; private BDiagnosticSource diagnosticSrc; private BLangDiagnosticLogHelper dlog; privat...
``` "storage_medium" = "SSD" is not need ``` If the BE not specified the SSD, you will can not create table successfully.
void createTable() throws SQLException { runSql(db, "create table " + table + " ( pk bigint NOT NULL, v0 string not null) primary KEY (pk) DISTRIBUTED BY HASH(pk) BUCKETS " + numTablet + " PROPERTIES(\"replication_num\" = \"" + repl...
"\", \"storage_medium\" = \"SSD\");");
void createTable() throws SQLException { runSql(db, "create table " + table + " ( pk bigint NOT NULL, v0 string not null) primary KEY (pk) DISTRIBUTED BY HASH(pk) BUCKETS " + numTablet + " PROPERTIES(\"replication_num\" = \"" + repl...
class TableLoad { String db; String table; int id; int numTablet; int replicationNum; int loadIntervalMs; TableLoad(String db, int id, int numTablet, int replicationNum, int loadIntervalMs) { this.db = db; this.table = "table_" + id; ...
class TableLoad { String db; String table; int id; int numTablet; int replicationNum; int loadIntervalMs; TableLoad(String db, int id, int numTablet, int replicationNum, int loadIntervalMs) { this.db = db; this.table = "table_" + id; ...
`SYNCHRONIZED_PROCESSING_TIME`? Why is this the case? Specifically, why do we consider event time timers?
public void onTimers(Iterable<TimerData> timers) throws Exception { if (!timers.iterator().hasNext()) { return; } Map<BoundedWindow, EnrichedTimerData> enrichedTimers = new HashMap(); for (TimerData timer : timers) { checkArgument(timer.getNamespace() instanceof WindowNamespace, ...
if (TimeDomain.PROCESSING_TIME == timer.getDomain() && windowIsExpired(window)) {
public void onTimers(Iterable<TimerData> timers) throws Exception { if (!timers.iterator().hasNext()) { return; } Map<BoundedWindow, WindowActivation> windowActivations = new HashMap(); for (TimerData timer : timers) { checkArgument(timer.getNamespace() instanceof WindowNamespace...
class EnrichedTimerData { public final ReduceFn<K, InputT, OutputT, W>.Context directContext; public final ReduceFn<K, InputT, OutputT, W>.Context renamedContext; public final boolean isEndOfWindow; public final boolean isGarbageCollection; EnrichedTimerData( Reduce...
class WindowActivation { public final ReduceFn<K, InputT, OutputT, W>.Context directContext; public final ReduceFn<K, InputT, OutputT, W>.Context renamedContext; public final boolean isEndOfWindow; public final boolean isGarbageCollection; WindowActivation( ReduceFn...
It's just to remove the unecessary autoboxing, since you're comparing primitives here, but it's not that relevant anyway
void mapsWithBase() { assertEquals("localhost", mapsWithBase.server().get("host")); assertEquals(8080, Integer.valueOf(mapsWithBase.server().get("port"))); assertEquals("localhost", mapsWithBase.group().get("server").host()); assertEquals(8080, mapsWithBase.group().get("server").port())...
assertEquals(8080, Integer.valueOf(mapsWithBase.server().get("port")));
void mapsWithBase() { assertEquals("localhost", mapsWithBase.server().get("host")); assertEquals(8080, Integer.valueOf(mapsWithBase.server().get("port"))); assertEquals("localhost", mapsWithBase.group().get("server").host()); assertEquals(8080, mapsWithBase.group().get("server").port())...
class ConfigMappingTest { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class) .addAsResource(new StringAsset("config.my.prop=1234\n" + "group.host=localhost\n" + ...
class ConfigMappingTest { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class) .addAsResource(new StringAsset("config.my.prop=1234\n" + "group.host=localhost\n" + ...
"availability" in resolver means that tracked remote repository (by repoID) is available in the context artifact is asked for. So "remote" may come in as "remote repo ID is available in current context asking for artifact" :)
public void testValidTailFromRemoteIgnoringAvailabilityViaSystemPropBlank() throws Exception { setSystemProp("maven.repo.local.tail.ignoreAvailability", " "); final BootstrapMavenContext mvn = bootstrapMavenContextForProject("workspace-with-local-repo-tail", BootstrapMavenContext.config...
assertNotNull(resolveOrgAcmeFooJar001(mvn));
public void testValidTailFromRemoteIgnoringAvailabilityViaSystemPropBlank() throws Exception { setSystemProp("maven.repo.local.tail.ignoreAvailability", " "); final BootstrapMavenContext mvn = bootstrapMavenContextForProject("workspace-with-local-repo-tail", BootstrapMavenContext.config...
class ChainedLocalRepositoryManagerTest extends BootstrapMavenContextTestBase { private static final String M2_LOCAL_1; private static final String M2_LOCAL_2; private static final String M2_FROM_REMOTE; static { final String projectLocation; try { projectLocation = getProj...
class ChainedLocalRepositoryManagerTest extends BootstrapMavenContextTestBase { private static final String M2_LOCAL_1; private static final String M2_LOCAL_2; private static final String M2_FROM_REMOTE; static { final String projectLocation; try { projectLocation = getProj...
I was thinking of just having the loop ``` for (T newValue : newValues) { valueCoder.encode(newValue, out); if (out.size() > BAG_APPEND_BATCHING_LIMIT) { [send out.toByteStringAndReset()] } } ... ``` rather than introducing the (I think correct, but complex to reason about) `consumePrefixToByteString`. True...
public void asyncClose() throws Exception { checkState( !isClosed, "Bag user state is no longer usable because it is closed for %s", request.getStateKey()); isClosed = true; if (!isCleared && newValues.isEmpty()) { return; } if (isCleared) { beamFnStateClient.hand...
if (out.size() > BAG_APPEND_BATCHING_LIMIT) {
public void asyncClose() throws Exception { checkState( !isClosed, "Bag user state is no longer usable because it is closed for %s", request.getStateKey()); isClosed = true; if (!isCleared && newValues.isEmpty()) { return; } if (isCleared) { beamFnStateClient.hand...
class BagUserState<T> { private final Cache<?, ?> cache; private final BeamFnStateClient beamFnStateClient; private final StateRequest request; private final Coder<T> valueCoder; private final CachingStateIterable<T> oldValues; private List<T> newValues; private boolean isCleared; private boolean isClos...
class BagUserState<T> { private final Cache<?, ?> cache; private final BeamFnStateClient beamFnStateClient; private final StateRequest request; private final Coder<T> valueCoder; private final CachingStateIterable<T> oldValues; private List<T> newValues; private boolean isCleared; private boolean isClos...
Do we have any numbers that indicate disabling `TCP_NODELAY` is worth it? We unconditionally enabled nodelay for everything to get rid of spurious latency spikes incurred by the in-kernel deferred packet sending.
public Connection(TransportThread parent, Supervisor owner, Spec spec, Object context, boolean tcpNoDelay) { super(context); this.parent = parent; this.owner = owner; this.spec = spec; this.tcpNoDelay = tcpNoDelay; server = false; owner.sessionInit(this); }
this.tcpNoDelay = tcpNoDelay;
public Connection(TransportThread parent, Supervisor owner, Spec spec, Object context, boolean tcpNoDelay) { super(context); this.parent = parent; this.owner = owner; this.spec = spec; this.tcpNoDelay = tcpNoDelay; server = false; owner.sessionInit(this); }
class Connection extends Target { private static final Logger log = Logger.getLogger(Connection.class.getName()); private static final int READ_SIZE = 32768; private static final int READ_REDO = 10; private static final int WRITE_SIZE = 32768; private static final int WRITE_REDO = 10; priva...
class Connection extends Target { private static final Logger log = Logger.getLogger(Connection.class.getName()); private static final int READ_SIZE = 32768; private static final int READ_REDO = 10; private static final int WRITE_SIZE = 32768; private static final int WRITE_REDO = 10; priva...
If it is something non-trivial and hard to make a call about, I would propose to skip this refactoring for now.
public void startCluster() throws ClusterEntrypointException { LOG.info("Starting {}.", getClass().getSimpleName()); try { PluginManager pluginManager = PluginUtils.createPluginManagerFromRootFolder(configuration); configureFileSystems(configuration, pluginManager); SecurityContext securityContext = ...
public void startCluster() throws ClusterEntrypointException { LOG.info("Starting {}.", getClass().getSimpleName()); try { PluginManager pluginManager = PluginUtils.createPluginManagerFromRootFolder(configuration); configureFileSystems(configuration, pluginManager); SecurityContext securityContext = inst...
class ClusterEntrypoint implements AutoCloseableAsync, FatalErrorHandler { public static final ConfigOption<String> EXECUTION_MODE = ConfigOptions .key("internal.cluster.execution-mode") .defaultValue(ExecutionMode.NORMAL.toString()); protected static final Logger LOG = LoggerFactory.getLogger(ClusterEntrypoint...
class ClusterEntrypoint implements AutoCloseableAsync, FatalErrorHandler { public static final ConfigOption<String> EXECUTION_MODE = ConfigOptions .key("internal.cluster.execution-mode") .defaultValue(ExecutionMode.NORMAL.toString()); protected static final Logger LOG = LoggerFactory.getLogger(ClusterEntrypoint...
Sure, I added a link to the Cloud docs about specifying pipeline options. This generalizes across different languages and is a good how-to guide.
public void logHotKeyDetection(String userStepName, Duration hotKeyAge) { if (isThrottled()) { return; } LOG.warn( "A hot key was detected in step '{}' with age of '{}'. This is " + "a symptom of key distribution being skewed. To fix, please inspect your data and " + "p...
+ "`hotKeyLoggingEnabled` pipeline option.",
public void logHotKeyDetection(String userStepName, Duration hotKeyAge) { if (isThrottled()) { return; } LOG.warn( "A hot key was detected in step '{}' with age of '{}'. This is " + "a symptom of key distribution being skewed. To fix, please inspect your data and " + "p...
class HotKeyLogger { private final Logger LOG = LoggerFactory.getLogger(HotKeyLogger.class); /** Clock used to either provide real system time or mocked to virtualize time for testing. */ private Clock clock = Clock.SYSTEM; /** * The previous time the HotKeyDetection was logged. This is used to throttle lo...
class HotKeyLogger { private final Logger LOG = LoggerFactory.getLogger(HotKeyLogger.class); /** Clock used to either provide real system time or mocked to virtualize time for testing. */ private Clock clock = Clock.SYSTEM; /** * The previous time the HotKeyDetection was logged. This is used to throttle lo...
if you have just `resteasy` or `spring` then there is no problem :)
public QuarkusCommandOutcome execute() throws QuarkusCommandException { Matcher matcher = JAVA_VERSION_PATTERN .matcher(this.javaTarget != null ? this.javaTarget : System.getProperty("java.version", "")); if (matcher.matches() && Integer.parseInt(matcher.group(1)) < 11) { ...
values.remove(RESOURCE_PATH);
public QuarkusCommandOutcome execute() throws QuarkusCommandException { Matcher matcher = JAVA_VERSION_PATTERN .matcher(this.javaTarget != null ? this.javaTarget : System.getProperty("java.version", "")); if (matcher.matches() && Integer.parseInt(matcher.group(1)) < 11) { ...
class name"); } setValue(CLASS_NAME, className); return this; } public CreateProject extensions(Set<String> extensions) { if (extensions == null) { return this; } this.extensions.addAll(extensions); return this; }
class name"); } setValue(CLASS_NAME, className); return this; } public CreateProject extensions(Set<String> extensions) { if (extensions == null) { return this; } this.extensions.addAll(extensions); return this; }
From a code review perspective, here are some suggestions for improvement: 1. Naming: - Consider providing more descriptive names for variables, methods, and classes to improve code readability and maintainability. 2. Code Style: - Follow a consistent code style throughout the codebase. For example, use consist...
public IHiveMetastore createHiveMetastore() { HiveMetaClient metaClient = HiveMetaClient.createHiveMetaClient(hdfsEnvironment, properties); IHiveMetastore hiveMetastore = new HiveMetastore(metaClient, catalogName, metastoreType); IHiveMetastore baseHiveMetastore; if (!enableMeta...
baseHiveMetastore = hiveMetastore;
public IHiveMetastore createHiveMetastore() { HiveMetaClient metaClient = HiveMetaClient.createHiveMetaClient(hdfsEnvironment, properties); IHiveMetastore hiveMetastore = new HiveMetastore(metaClient, catalogName, metastoreType); IHiveMetastore baseHiveMetastore; if (!enableMeta...
class HiveConnectorInternalMgr { public static final List<String> SUPPORTED_METASTORE_TYPE = Lists.newArrayList("hive", "glue", "dlf"); private final String catalogName; private final HdfsEnvironment hdfsEnvironment; private final Map<String, String> properties; private final boolean enableMetastore...
class HiveConnectorInternalMgr { public static final List<String> SUPPORTED_METASTORE_TYPE = Lists.newArrayList("hive", "glue", "dlf"); private final String catalogName; private final HdfsEnvironment hdfsEnvironment; private final Map<String, String> properties; private final boolean enableMetastore...
done (I can refactor tests to share pairs of inputs later, but anyhow I added the reverse tests)
public static Row recordToRow(Schema schema, Record record) { Row.Builder rowBuilder = Row.withSchema(schema); for (Schema.Field field : schema.getFields()) { switch (field.getType().getTypeName()) { case BYTE: byte byteValue = (byte) record.getField(field.getName()); ...
public static Row recordToRow(Schema schema, Record record) { Row.Builder rowBuilder = Row.withSchema(schema); for (Schema.Field field : schema.getFields()) { switch (field.getType().getTypeName()) { case BYTE: byte byteValue = (byte) record.getField(field.getName()); ...
class SchemaAndRowConversions { private SchemaAndRowConversions() {} public static final String ICEBERG_TYPE_OPTION_NAME = "icebergTypeID"; public static Schema.FieldType icebergTypeToBeamFieldType(final Type type) { switch (type.typeId()) { case BOOLEAN: return Schema.FieldType.BOOLEAN; ...
class SchemaAndRowConversions { private SchemaAndRowConversions() {} public static final String ICEBERG_TYPE_OPTION_NAME = "icebergTypeID"; public static Schema.FieldType icebergTypeToBeamFieldType(final Type type) { switch (type.typeId()) { case BOOLEAN: return Schema.FieldType.BOOLEAN; ...
please add a unit test for the change. See `PartitionKeyInternalTest` for existing tests.
public void serialize(PartitionKeyInternal partitionKey, JsonGenerator writer, SerializerProvider serializerProvider) { try { if (partitionKey.equals(PartitionKeyInternal.getExclusiveMaximum())) { writer.writeString(INFINITY); return; }...
writer.writeEndArray();
public void serialize(PartitionKeyInternal partitionKey, JsonGenerator writer, SerializerProvider serializerProvider) { try { if (partitionKey.equals(PartitionKeyInternal.getExclusiveMaximum())) { writer.writeString(INFINITY); return; }...
class PartitionKeyInternalJsonSerializer extends StdSerializer<PartitionKeyInternal> { private static final long serialVersionUID = 2258093043805843865L; protected PartitionKeyInternalJsonSerializer() { this(null); } protected PartitionKeyInternalJsonSerializer(Class<PartitionKeyInternal> t) ...
class PartitionKeyInternalJsonSerializer extends StdSerializer<PartitionKeyInternal> { private static final long serialVersionUID = 2258093043805843865L; protected PartitionKeyInternalJsonSerializer() { this(null); } protected PartitionKeyInternalJsonSerializer(Class<PartitionKeyInternal> t) ...
```suggestion // if they are found before 'By' ``` ?
public Result parse(MethodInfo methodInfo) { String methodName = methodInfo.name(); ClassInfo repositoryClassInfo = methodInfo.declaringClass(); String repositoryMethodDescription = "'" + methodName + "' of repository '" + repositoryClassInfo + "'"; QueryType queryType = getType(methodNa...
public Result parse(MethodInfo methodInfo) { String methodName = methodInfo.name(); ClassInfo repositoryClassInfo = methodInfo.declaringClass(); String repositoryMethodDescription = "'" + methodName + "' of repository '" + repositoryClassInfo + "'"; QueryType queryType = getType(methodNa...
class MethodNameParser { private static final String ALL_IGNORE_CASE = "AllIgnoreCase"; private static final String IGNORE_CASE = "IgnoreCase"; private static final String ORDER_BY = "OrderBy"; private static final List<String> HANDLED_PROPERTY_OPERATIONS = Arrays.asList( "Is", "Equals", ...
class MethodNameParser { private static final String ALL_IGNORE_CASE = "AllIgnoreCase"; private static final String IGNORE_CASE = "IgnoreCase"; private static final String ORDER_BY = "OrderBy"; private static final List<String> HANDLED_PROPERTY_OPERATIONS = Arrays.asList( "Is", "Equals", ...
Also an exclusive curator framework per JobMaster will definitely harm the performance and add additional pressure to ZooKeeper.
public void close() throws Exception { if (!running) { return; } running = false; LOG.info("Closing {}.", this); client.getConnectionStateListenable().removeListener(connectionStateListener); cache.close(); try { if (client.getZookeepe...
&& !connectionInformationPath.contains(RESOURCE_MANAGER_NODE)) {
public void close() throws Exception { if (!running) { return; } running = false; LOG.info("Closing {}.", this); client.getConnectionStateListenable().removeListener(connectionStateListener); cache.close(); try { if (client.getZookeepe...
class ZooKeeperLeaderRetrievalDriver implements LeaderRetrievalDriver { private static final Logger LOG = LoggerFactory.getLogger(ZooKeeperLeaderRetrievalDriver.class); /** Connection to the used ZooKeeper quorum. */ private final CuratorFramework client; /** Curator recipe to watch changes of a speci...
class ZooKeeperLeaderRetrievalDriver implements LeaderRetrievalDriver { private static final Logger LOG = LoggerFactory.getLogger(ZooKeeperLeaderRetrievalDriver.class); /** Connection to the used ZooKeeper quorum. */ private final CuratorFramework client; /** Curator recipe to watch changes of a speci...
I think this looks like a bug, why do you increment the counter here?
public boolean triggerCheckpoint(long timestamp, boolean isPeriodic) { try { triggerCheckpoint(timestamp, checkpointProperties, null, isPeriodic, false); return true; } catch (CheckpointException e) { try { long latestGeneratedCheckpointId = getCheckpointIdCounter().getAndIncrement(); failureManage...
long latestGeneratedCheckpointId = getCheckpointIdCounter().getAndIncrement();
public boolean triggerCheckpoint(long timestamp, boolean isPeriodic) { try { triggerCheckpoint(timestamp, checkpointProperties, null, isPeriodic, false); return true; } catch (CheckpointException e) { long latestGeneratedCheckpointId = getCheckpointIdCounter().get(); failureManager.handleCheckpo...
class CheckpointCoordinator { private static final Logger LOG = LoggerFactory.getLogger(CheckpointCoordinator.class); /** The number of recent checkpoints whose IDs are remembered. */ private static final int NUM_GHOST_CHECKPOINT_IDS = 16; /** Coordinator-wide lock to safeguard the checkpoint updates. */ pri...
class CheckpointCoordinator { private static final Logger LOG = LoggerFactory.getLogger(CheckpointCoordinator.class); /** The number of recent checkpoints whose IDs are remembered. */ private static final int NUM_GHOST_CHECKPOINT_IDS = 16; /** Coordinator-wide lock to safeguard the checkpoint updates. */ pri...
But once the `CheckpointCoordinator` is shut down, these exceptions should no longer matter, at least not in terms of correctness of the job. I don't really understand why this was not a problem before and now we want to fine grained filter out exceptions, this does not seem like a straight forward solution to me.
private void startTriggeringCheckpoint(CheckpointTriggerRequest request) { try { synchronized (lock) { preCheckGlobalState(request.isPeriodic); } final Execution[] executions = getTriggerExecutions(); final Map<ExecutionAttemptID, ExecutionVertex> ackTasks = getAckTasks(); Preconditions.check...
if (error != null) {
private void startTriggeringCheckpoint(CheckpointTriggerRequest request) { try { synchronized (lock) { preCheckGlobalState(request.isPeriodic); } final Execution[] executions = getTriggerExecutions(); final Map<ExecutionAttemptID, ExecutionVertex> ackTasks = getAckTasks(); Preconditions.check...
class CheckpointCoordinator { private static final Logger LOG = LoggerFactory.getLogger(CheckpointCoordinator.class); /** The number of recent checkpoints whose IDs are remembered. */ private static final int NUM_GHOST_CHECKPOINT_IDS = 16; /** Coordinator-wide lock to safeguard the checkpoint updates. */ pri...
class CheckpointCoordinator { private static final Logger LOG = LoggerFactory.getLogger(CheckpointCoordinator.class); /** The number of recent checkpoints whose IDs are remembered. */ private static final int NUM_GHOST_CHECKPOINT_IDS = 16; /** Coordinator-wide lock to safeguard the checkpoint updates. */ pri...
I think calling this method every time, whether log empty diagnostics is enabled or not is not good. We should have the check on this method, so that we don't even go into the execution of this method if the flag is disabled (avoids creating unnecessary method stack and saves some small resources and computation).
public Flux<FeedResponse<T>> apply(Flux<DocumentProducer<T>.DocumentProducerFeedResponse> source) { return source.filter(documentProducerFeedResponse -> { if (documentProducerFeedResponse.pageResult.getResults().isEmpty() && !ModelBridgeInter...
logEmptyPageDiagnostics(
Combining previous empty page query metrics with current non empty page query metrics if (!emptyPageQueryMetricsMap.isEmpty()) { ConcurrentMap<String, QueryMetrics> currentQueryMetrics = BridgeInternal.queryMetricsFromFeedResponse(documentProducerFeedResponse....
class EmptyPagesFilterTransformer<T extends Resource> implements Function<Flux<DocumentProducer<T>.DocumentProducerFeedResponse>, Flux<FeedResponse<T>>> { private final RequestChargeTracker tracker; private DocumentProducer<T>.DocumentProducerFeedResponse previousPage; private final Cosm...
class EmptyPagesFilterTransformer<T extends Resource> implements Function<Flux<DocumentProducer<T>.DocumentProducerFeedResponse>, Flux<FeedResponse<T>>> { private final RequestChargeTracker tracker; private DocumentProducer<T>.DocumentProducerFeedResponse previousPage; private final Cosm...
You could look into removing the nullness warning suppression at the top of the class to automate this catch if needed. But that might require more fixes than we want to make in this cl
public void addTimingInfo(Collection<GetWorkStreamTimingInfo> infos) { Map<Event, Instant> getWorkStreamTimings = new HashMap<>(); for (GetWorkStreamTimingInfo info : infos) { getWorkStreamTimings.putIfAbsent( info.getEvent(), Insta...
return duration.plus(newDuration);
public void addTimingInfo(Collection<GetWorkStreamTimingInfo> infos) { Map<Event, Instant> getWorkStreamTimings = new HashMap<>(); for (GetWorkStreamTimingInfo info : infos) { getWorkStreamTimings.putIfAbsent( info.get...
class GetWorkTimingInfosTracker { private Instant workItemCreationEndTime = Instant.EPOCH; private Instant workItemLastChunkReceivedByWorkerTime = Instant.EPOCH; private LatencyAttribution workItemCreationLatency = null; private final Map<State, Duration> aggregatedGetWorkStreamLatencies; private...
class SumAndMaxDurations { private Duration sum; private Duration max; public SumAndMaxDurations(Duration sum, Duration max) { this.sum = sum; this.max = max; } }