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
If return true constant, which means we need to keep all partitions or prunes all partitions?
public ScalarOperator visitBinaryPredicate(BinaryPredicateOperator predicate, Void context) { if (partitionColumnSet.containsAll(predicate.getUsedColumns())) { ScalarOperator left = predicate.getChild(0).accept(this, null); if (isShortCut(left)) { return ConstantOperator....
return ConstantOperator.createBoolean(true);
public ScalarOperator visitBinaryPredicate(BinaryPredicateOperator predicate, Void context) { if (partitionColumnSet.containsAll(predicate.getUsedColumns())) { ScalarOperator left = predicate.getChild(0).accept(this, null); if (isShortCut(left)) { return ConstantOperator....
class PartitionColPredicateExtractor extends ScalarOperatorVisitor<ScalarOperator, Void> { private ColumnRefSet partitionColumnSet; public PartitionColPredicateExtractor(RangePartitionInfo rangePartitionInfo, Map<Column, ColumnRefOperator> columnMetaToColRefMap) { ...
class PartitionColPredicateExtractor extends ScalarOperatorVisitor<ScalarOperator, Void> { private ColumnRefSet partitionColumnSet; public PartitionColPredicateExtractor(RangePartitionInfo rangePartitionInfo, Map<Column, ColumnRefOperator> columnMetaToColRefMap) { ...
That can be added any time when we feel comfortable with Spotless formatting the code in Monitor OpenTelemetry Exporter. I can file another PR after this for that if you want.
private static boolean isClient(String metricName) { return metricName.contains(".client."); }
return metricName.contains(".client.");
private static boolean isClient(String metricName) { return metricName.contains(".client."); }
class MetricDataMapper { private static final ClientLogger logger = new ClientLogger(MetricDataMapper.class); private static final Set<String> OTEL_UNSTABLE_METRICS_TO_EXCLUDE = new HashSet<>(); private static final String OTEL_INSTRUMENTATION_NAME_PREFIX = "io.opentelemetry"; private static final Set...
class MetricDataMapper { private static final ClientLogger logger = new ClientLogger(MetricDataMapper.class); private static final Set<String> OTEL_UNSTABLE_METRICS_TO_EXCLUDE = new HashSet<>(); private static final String OTEL_INSTRUMENTATION_NAME_PREFIX = "io.opentelemetry"; private static final Set...
you need to modify exception message for you delete 'BinaryPredicate'
public void analyzeImpl(Analyzer analyzer) throws AnalysisException { Type whenType = null; Type returnType = null; Expr lastCompatibleThenExpr = null; Expr lastCompatibleWhenExpr = null; int loopEnd = children.size(); if (hasElseExpr) { ...
throw new AnalysisException("Only support subquery in binary predicate in case statement.");
public void analyzeImpl(Analyzer analyzer) throws AnalysisException { Type whenType = null; Type returnType = null; Expr lastCompatibleThenExpr = null; Expr lastCompatibleWhenExpr = null; int loopEnd = children.size(); if (hasElseExpr) { ...
class CaseExpr extends Expr { private boolean hasCaseExpr; private boolean hasElseExpr; public CaseExpr(Expr caseExpr, List<CaseWhenClause> whenClauses, Expr elseExpr) { super(); if (caseExpr != null) { children.add(caseExpr); hasCaseExpr = true; } fo...
class CaseExpr extends Expr { private boolean hasCaseExpr; private boolean hasElseExpr; public CaseExpr(Expr caseExpr, List<CaseWhenClause> whenClauses, Expr elseExpr) { super(); if (caseExpr != null) { children.add(caseExpr); hasCaseExpr = true; } fo...
Junit 5 has API to assert thrown exception, ```java assertThrows( MyException.class, () -> myObject.doThing(), "Expected doThing() to throw, but it didn't" ); ```
public void testInvalidScopeFromRequestSync(String invalidCharacter) { TokenRequestContext request = new TokenRequestContext().addScopes("scope" + invalidCharacter); AzureCliCredential credential = new AzureCliCredentialBuilder().build(); try { credential.getTokenSync(request); ...
credential.getTokenSync(request);
public void testInvalidScopeFromRequestSync(String invalidCharacter) { TokenRequestContext request = new TokenRequestContext().addScopes("scope" + invalidCharacter); AzureCliCredential credential = new AzureCliCredentialBuilder().build(); assertThrows(IllegalArgumentException.class, () -> crede...
class AzureCliCredentialNegativeTest { static Stream<String> invalidCharacters() { return Stream.of("|", "&", ";"); } @ParameterizedTest @MethodSource("invalidCharacters") public void testInvalidScopeFromRequest(String invalidCharacter) { TokenRequestContext request = new TokenReque...
class AzureCliCredentialNegativeTest { static Stream<String> invalidCharacters() { return Stream.of("|", "&", ";"); } @ParameterizedTest @MethodSource("invalidCharacters") public void testInvalidScopeFromRequest(String invalidCharacter) { TokenRequestContext request = new TokenReque...
Not sure if this comment adds any value
OperationHandlerImpl createHandler() throws Exception { VisitorSession visitorSession = mock(VisitorSession.class); when(documentAccess.createVisitorSession(any(VisitorParameters.class))).thenAnswer(p -> { VisitorParameters params = (VisitorParameter...
OperationHandlerImpl createHandler() throws Exception { VisitorSession visitorSession = mock(VisitorSession.class); when(documentAccess.createVisitorSession(any(VisitorParameters.class))).thenAnswer(p -> { VisitorParameters params = (VisitorParameters)p.getArguments(...
class OperationHandlerImplFixture { DocumentAccess documentAccess = mock(DocumentAccess.class); AtomicReference<VisitorParameters> assignedParameters = new AtomicReference<>(); VisitorControlHandler.CompletionCode completionCode = VisitorControlHandler.CompletionCode.SUCCESS; int buckets...
class OperationHandlerImplFixture { DocumentAccess documentAccess = mock(DocumentAccess.class); AtomicReference<VisitorParameters> assignedParameters = new AtomicReference<>(); VisitorControlHandler.CompletionCode completionCode = VisitorControlHandler.CompletionCode.SUCCESS; int buckets...
Seems one `getSchemaLock` call is enough.
public void stopClusterWriteDB(final String schemaName, final String jobId) { LockContext lockContext = PipelineContext.getContextManager().getLockContext(); ShardingSphereLock lock = lockContext.getSchemaLock(schemaName).orElse(lockContext.getSchemaLock(schemaName).orElse(null)); if (null == lo...
ShardingSphereLock lock = lockContext.getSchemaLock(schemaName).orElse(lockContext.getSchemaLock(schemaName).orElse(null));
public void stopClusterWriteDB(final String schemaName, final String jobId) { LockContext lockContext = PipelineContext.getContextManager().getLockContext(); ShardingSphereLock lock = lockContext.getSchemaLock(schemaName).orElse(null); if (null == lock) { log.info("stopClusterWriteDB...
class RuleAlteredJobAPIImpl extends AbstractPipelineJobAPIImpl implements RuleAlteredJobAPI { private static final Map<String, DataConsistencyCheckAlgorithm> DATA_CONSISTENCY_CHECK_ALGORITHM_MAP = new TreeMap<>( SingletonSPIRegistry.getTypedSingletonInstancesMap(DataConsistencyCheckAlgorithm.class)...
class RuleAlteredJobAPIImpl extends AbstractPipelineJobAPIImpl implements RuleAlteredJobAPI { private static final Map<String, DataConsistencyCheckAlgorithm> DATA_CONSISTENCY_CHECK_ALGORITHM_MAP = new TreeMap<>( SingletonSPIRegistry.getTypedSingletonInstancesMap(DataConsistencyCheckAlgorithm.class)...
Otherwise, an application with two upgrade targets (due to previous failed deployments, or, later, due to an aborted change) would start tests for the other target immediately after completing them for the first, disregarding the delay.
private List<Job> computeReadyJobs(ApplicationId id) { List<Job> jobs = new ArrayList<>(); applications().get(id).ifPresent(application -> { List<Step> steps = application.deploymentSpec().steps().isEmpty() ? singletonList(new DeploymentSpec.DeclaredZone(test)) ...
if ( ! alreadyTriggered(application, target))
private List<Job> computeReadyJobs(ApplicationId id) { List<Job> jobs = new ArrayList<>(); applications().get(id).ifPresent(application -> { List<Step> steps = application.deploymentSpec().steps().isEmpty() ? singletonList(new DeploymentSpec.DeclaredZone(test)) ...
class DeploymentTrigger { private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final DeploymentOrder order; private final BuildService buildService; public DeploymentTrigger(Controller co...
class DeploymentTrigger { private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final DeploymentOrder order; private final BuildService buildService; public DeploymentTrigger(Controller co...
Couldn't we remove the "primitive" attribute from the Read transform instead of introducing the additional logic? Runners could still decide whether they want to consider READ primitive.
static Collection<String> getPrimitiveTransformIds(RunnerApi.Components components) { Collection<String> ids = new LinkedHashSet<>(); for (Map.Entry<String, PTransform> transformEntry : components.getTransformsMap().entrySet()) { PTransform transform = transformEntry.getValue(); boolean isPrimitive...
if (isPrimitive) {
static Collection<String> getPrimitiveTransformIds(RunnerApi.Components components) { Collection<String> ids = new LinkedHashSet<>(); for (Map.Entry<String, PTransform> transformEntry : components.getTransformsMap().entrySet()) { PTransform transform = transformEntry.getValue(); boolean isPrimitive...
class QueryablePipeline { /** * Create a new {@link QueryablePipeline} based on the provided components. * * <p>The returned {@link QueryablePipeline} will contain only the primitive transforms present * within the provided components. */ public static QueryablePipeline forPrimitivesIn(Co...
class QueryablePipeline { /** * Create a new {@link QueryablePipeline} based on the provided components. * * <p>The returned {@link QueryablePipeline} will contain only the primitive transforms present * within the provided components. */ public static QueryablePipeline forPrimitivesIn(Co...
We don't need a variable 'contentType' here. Check all getPayload methods
public void testGetBinaryPayloadMethod() { BStruct request = BCompileUtil.createAndGetStruct(result.getProgFile(), protocolPackageHttp, requestStruct); BStruct entity = BCompileUtil.createAndGetStruct(result.getProgFile(), protocolPackageMime, entityStruct); BStruct mediaType = BCompileUtil.crea...
String contentType = OCTET_STREAM;
public void testGetBinaryPayloadMethod() { BStruct request = BCompileUtil.createAndGetStruct(result.getProgFile(), protocolPackageHttp, requestStruct); BStruct entity = BCompileUtil.createAndGetStruct(result.getProgFile(), protocolPackageMime, entityStruct); BStruct mediaType = BCompileUtil.crea...
class RequestNativeFunctionSuccessTest { private static final Logger LOG = LoggerFactory.getLogger(RequestNativeFunctionSuccessTest.class); private CompileResult result, serviceResult; private final String requestStruct = Constants.REQUEST; private final String headerStruct = HEADER_VALUE_STRUCT; p...
class RequestNativeFunctionSuccessTest { private static final Logger LOG = LoggerFactory.getLogger(RequestNativeFunctionSuccessTest.class); private CompileResult result, serviceResult; private final String requestStruct = Constants.REQUEST; private final String headerStruct = HEADER_VALUE_STRUCT; p...
No need for null check here
public void listExtensions(boolean all, String format, String search) throws IOException { final Map<String, Dependency> installed = findInstalled(); Stream<Extension> extensionsStream = loadExtensions().stream(); if (search != null && !"*".equalsIgnoreCase(search)) { final Pattern ...
if (this.buildFile != null && this.buildFile instanceof GradleBuildFile) {
public void listExtensions(boolean all, String format, String search) throws IOException { final Map<String, Dependency> installed = findInstalled(); Stream<Extension> extensionsStream = loadExtensions().stream(); if (search != null && !"*".equalsIgnoreCase(search)) { final Pattern ...
class ListExtensions { private static final String FULL_FORMAT = "%-8s %-50s %-50s %-25s%n%s"; private static final String CONCISE_FORMAT = "%-50s %-50s"; private static final String NAME_FORMAT = "%-50s"; private BuildFile buildFile = null; public ListExtensions(final BuildFile buildFile) throws I...
class ListExtensions { private static final String FULL_FORMAT = "%-8s %-50s %-50s %-25s%n%s"; private static final String CONCISE_FORMAT = "%-50s %-50s"; private static final String NAME_FORMAT = "%-50s"; private BuildFile buildFile = null; public ListExtensions(final BuildFile buildFile) throws I...
I'd just name this variable "errors". Feel like naming is not consistent with the previous variable (responses) :)
public void testCircuitBreaker() { int[] expectedStatusCodes = new int[] { 200, 200, 500, 503, 503, 200, 200, 200 }; BValue[] returnVals = BRunUtil.invoke(compileResult, "testTypicalScenario"); Assert.assertEquals(returnVals.length, 2); BRefValueArray responses = (BRefValueArr...
BRefValueArray errorsArray = (BRefValueArray) returnVals[1];
public void testCircuitBreaker() { int[] expectedStatusCodes = new int[] { 200, 200, 500, 503, 503, 200, 200, 200 }; BValue[] returnVals = BRunUtil.invoke(compileResult, "testTypicalScenario"); Assert.assertEquals(returnVals.length, 2); BRefValueArray responses = (BRefValueArr...
class CircuitBreakerTest { private static final String CB_ERROR_MSG = "Upstream service unavailable."; private static final String MOCK_ENDPOINT_NAME = "mockEP"; private static final int CB_CLIENT_FIRST_ERROR_INDEX = 3; private static final int CB_CLIENT_SECOND_ERROR_INDEX = 4; private static...
class CircuitBreakerTest { private static final String CB_ERROR_MSG = "Upstream service unavailable."; private static final String MOCK_ENDPOINT_NAME = "mockEP"; private static final int CB_CLIENT_FIRST_ERROR_INDEX = 3; private static final int CB_CLIENT_SECOND_ERROR_INDEX = 4; private static...
```suggestion assertThat(group.getScopeComponents()).containsExactly("constant", "host", "foo", "host"); ```
void testGenerateScopeCustom() throws Exception { Configuration cfg = new Configuration(); cfg.setString(MetricOptions.SCOPE_NAMING_TM, "constant.<host>.foo.<host>"); MetricRegistryImpl registry = new MetricRegistryImpl(MetricRegistryTestUtils.fromConfiguration(cfg)); Tas...
assertThat(group.getScopeComponents()).containsAnyOf("constant", "host", "foo", "host");
void testGenerateScopeCustom() throws Exception { Configuration cfg = new Configuration(); cfg.setString(MetricOptions.SCOPE_NAMING_TM, "constant.<host>.foo.<host>"); MetricRegistryImpl registry = new MetricRegistryImpl(MetricRegistryTestUtils.fromConfiguration(cfg)); Tas...
class TaskManagerGroupTest { private MetricRegistryImpl registry; @BeforeEach void setup() { registry = new MetricRegistryImpl( MetricRegistryTestUtils.defaultMetricRegistryConfiguration()); } @AfterEach void teardown() throws Exception { ...
class TaskManagerGroupTest { private MetricRegistryImpl registry; @BeforeEach void setup() { registry = new MetricRegistryImpl( MetricRegistryTestUtils.defaultMetricRegistryConfiguration()); } @AfterEach void teardown() throws Exception { ...
This seems like it should be a subtype check. What was wrong with the prior code?
private static void verifySplittableMethods(DoFnSignature signature, ErrorReporter errors) { DoFnSignature.ProcessElementMethod processElement = signature.processElement(); DoFnSignature.GetInitialRestrictionMethod getInitialRestriction = signature.getInitialRestriction(); DoFnSignature.NewTrackerMe...
processElement.trackerT().getRawType().equals(RestrictionTracker.class),
private static void verifySplittableMethods(DoFnSignature signature, ErrorReporter errors) { DoFnSignature.ProcessElementMethod processElement = signature.processElement(); DoFnSignature.GetInitialRestrictionMethod getInitialRestriction = signature.getInitialRestriction(); DoFnSignature.NewTrackerMe...
class %s." + " Timer callbacks must be declared in the same lexical scope as their timer", onTimerMethod, id, timerDecl.field().getDeclaringClass().getCanonicalName()); onTimerMethodMap.put( id, analyzeOnTimerMethod(errors, fnT, onTimerMethod, id, inputT, out...
class %s." + " Timer callbacks must be declared in the same lexical scope as their timer", onTimerMethod, id, timerDecl.field().getDeclaringClass().getCanonicalName()); onTimerMethodMap.put( id, analyzeOnTimerMethod(errors, fnT, onTimerMethod, id, inputT, out...
Shouldn't we suspend the `mailboxProcessor` here? It was being done before when the future completed.
protected void processInput(MailboxDefaultAction.Controller controller) throws Exception { controller.suspendDefaultAction(); sourceThread.setTaskDescription(getName()); if (operatorChain.isFinishedOnRestore()) { LOG.debug( "...
sourceThread.getCompletionFuture().complete(null);
protected void processInput(MailboxDefaultAction.Controller controller) throws Exception { controller.suspendDefaultAction(); sourceThread.setTaskDescription(getName()); if (operatorChain.isFinishedOnRestore()) { LOG.debug( "...
class SourceStreamTask< OUT, SRC extends SourceFunction<OUT>, OP extends StreamSource<OUT, SRC>> extends StreamTask<OUT, OP> { private final LegacySourceFunctionThread sourceThread; private final Object lock; private volatile boolean externallyInducedCheckpoints; /** * In...
class SourceStreamTask< OUT, SRC extends SourceFunction<OUT>, OP extends StreamSource<OUT, SRC>> extends StreamTask<OUT, OP> { private final LegacySourceFunctionThread sourceThread; private final Object lock; private volatile boolean externallyInducedCheckpoints; /** * In...
``` // instead of completing stop with savepoint via `notifyCheckpointCompleted` call // we simulate that source has finished first. As a result we expect that the endOfInput // should have been issued ``` ?
public void testInputEndedBeforeStopWithSavepointConfirmed() throws Exception { CancelTestSource source = new CancelTestSource( STRING_TYPE_INFO.createSerializer(new ExecutionConfig()), "src"); TestBoundedOneInputStreamOperator chainTail = new TestBoundedOneInputS...
public void testInputEndedBeforeStopWithSavepointConfirmed() throws Exception { CancelTestSource source = new CancelTestSource( STRING_TYPE_INFO.createSerializer(new ExecutionConfig()), "src"); TestBoundedOneInputStreamOperator chainTail = new TestBoundedOneInputS...
class SourceStreamTaskTest { @Test /** This test verifies that open() and close() are correctly called by the StreamTask. */ @Test public void testOpenClose() throws Exception { final StreamTaskTestHarness<String> testHarness = new StreamTaskTestHarness<>(SourceStreamTask:...
class SourceStreamTaskTest { @Test /** This test verifies that open() and close() are correctly called by the StreamTask. */ @Test public void testOpenClose() throws Exception { final StreamTaskTestHarness<String> testHarness = new StreamTaskTestHarness<>(SourceStreamTask:...
What do you think about making `ModuleManager.loadedModules` to be `LinkedHashMap`? This can provide deterministic result for `listFullModules` and make the testing easier. If we do this, we should add a comment on the `loadedModules` to explain why we use `LinkedHashMap`.
public void testListFullModules() { ModuleMock.ModuleZ x = new ModuleMock.ModuleZ("x"); ModuleMock.ModuleY y = new ModuleMock.ModuleY("y"); ModuleMock.ModuleZ z = new ModuleMock.ModuleZ("z"); manager.loadModule("y", y); manager.loadModule("x", x); manager.loadModule("z",...
getActualModuleEntries());
public void testListFullModules() { ModuleMock x = new ModuleMock("x"); ModuleMock y = new ModuleMock("y"); ModuleMock z = new ModuleMock("z"); manager.loadModule("y", y); manager.loadModule("x", x); manager.loadModule("z", z); manager.useModules("z", "y"); ...
class ModuleManagerTest extends TestLogger { private static final Comparator<ModuleEntry> COMPARATOR = Comparator.comparing(ModuleEntry::name); private ModuleManager manager; @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void before() { manager...
class ModuleManagerTest extends TestLogger { private ModuleManager manager; @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void before() { manager = new ModuleManager(); } @Test public void testLoadModuleTwice() { assertEquals(Coll...
I'm not familiar with this API, but is it safe to expect the input stream to contain the full output when the process is already terminated?
public void provideOutcome(AppCreator ctx) throws AppCreatorException { outputDir = outputDir == null ? ctx.getWorkPath() : IoUtils.mkdirs(outputDir); final RunnerJarOutcome runnerJarOutcome = ctx.resolveOutcome(RunnerJarOutcome.class); Path runnerJar = runnerJarOutcome.getRunnerJar(); ...
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
public void provideOutcome(AppCreator ctx) throws AppCreatorException { outputDir = outputDir == null ? ctx.getWorkPath() : IoUtils.mkdirs(outputDir); final RunnerJarOutcome runnerJarOutcome = ctx.resolveOutcome(RunnerJarOutcome.class); Path runnerJar = runnerJarOutcome.getRunnerJar(); ...
class NativeImagePhase implements AppCreationPhase<NativeImagePhase>, NativeImageOutcome { private static final Logger log = Logger.getLogger(NativeImagePhase.class); private static final String GRAALVM_HOME = "GRAALVM_HOME"; private static final String QUARKUS_PREFIX = "quarkus."; private static fi...
class NativeImagePhase implements AppCreationPhase<NativeImagePhase>, NativeImageOutcome { private static final Logger log = Logger.getLogger(NativeImagePhase.class); private static final String GRAALVM_HOME = "GRAALVM_HOME"; private static final String QUARKUS_PREFIX = "quarkus."; private static fi...
it will be used only with Write which already does the PDone.in
public boolean start() throws IOException { restClient = source.spec.getConnectionConfiguration().createClient(); String query = source.spec.getQuery() != null ? source.spec.getQuery().get() : null; if (query == null) { query = "{\"query\": { \"match_all\": {} }}"; } if ((source.b...
return PDone.in(input.getPipeline());
public boolean start() throws IOException { restClient = source.spec.getConnectionConfiguration().createClient(); String query = source.spec.getQuery() != null ? source.spec.getQuery().get() : null; if (query == null) { query = "{\"query\": { \"match_all\": {} }}"; } if ((source.b...
class BoundedElasticsearchReader extends BoundedSource.BoundedReader<String> { private final BoundedElasticsearchSource source; private RestClient restClient; private String current; private String scrollId; private ListIterator<String> batchIterator; private BoundedElasticsearchReader(Bounde...
class BoundedElasticsearchReader extends BoundedSource.BoundedReader<String> { private final BoundedElasticsearchSource source; private RestClient restClient; private String current; private String scrollId; private ListIterator<String> batchIterator; private BoundedElasticsearchReader(Bounde...
```suggestion deployLogger.logApplicationPackage(Level.WARNING, msg); ``` To show this as a notification in console, e.g.: ![Screenshot from 2021-09-08 18-25-41](https://user-images.githubusercontent.com/3785505/132547847-87c8befe-3809-480a-a4cf-2b4ed6f13d74.png)
private RankProfile getInherited() { if (inheritedName == null) return null; if (inherited == null) { inherited = resolveInherited(); if (inherited == null) { String msg = "rank-profile '" + getName() + "' inherits '" + inheritedName + "', ...
deployLogger.log(Level.WARNING, msg);
private RankProfile getInherited() { if (inheritedName == null) return null; if (inherited == null) { inherited = resolveInherited(); if (inherited == null) { String msg = "rank-profile '" + getName() + "' inherits '" + inheritedName + "', ...
class RankProfile implements Cloneable { public final static String FIRST_PHASE = "firstphase"; public final static String SECOND_PHASE = "secondphase"; /** The search definition-unique name of this rank profile */ private final String name; /** The search definition owning this profile, or null i...
class RankProfile implements Cloneable { public final static String FIRST_PHASE = "firstphase"; public final static String SECOND_PHASE = "secondphase"; /** The search definition-unique name of this rank profile */ private final String name; /** The search definition owning this profile, or null i...
why we are passing in a null value here?
private void createReport(final IBundleCoverage bundleCoverage, ModuleCoverage moduleCoverage) { boolean containsSourceFiles = true; for (IPackageCoverage packageCoverage : bundleCoverage.getPackages()) { if (TesterinaConstants.DOT.equals(this.module.moduleName())) { contains...
boolean containsSourceFiles = true;
private void createReport(final IBundleCoverage bundleCoverage, ModuleCoverage moduleCoverage) { boolean containsSourceFiles = true; for (IPackageCoverage packageCoverage : bundleCoverage.getPackages()) { if (TesterinaConstants.DOT.equals(this.module.moduleName())) { contain...
class per module CodeCoverageUtils.unzipCompiledSource(jarPath, coverageDir, orgName, packageName, version); } catch (NoSuchFileException e) { if (Files.exists(coverageDir.resolve(BIN_DIR))) { CodeCoverageUtils.deleteDirectory(coverageDir.r...
class per module CodeCoverageUtils.unzipCompiledSource(jarPath, coverageDir, orgName, packageName, version); } catch (NoSuchFileException e) { if (Files.exists(coverageDir.resolve(BIN_DIR))) { CodeCoverageUtils.deleteDirectory(coverageDir.r...
shouldn't we check `containsKey` here as well?
private Optional<ExecutionVertex> updateAndGet(ExecutionAttemptID id) { synchronized (tasks) { ExecutionVertex vertex = cachedTasksById.get(id); if (vertex != null) { return Optional.of(vertex); } Map<ExecutionAttemptID, ExecutionVertex> mappings ...
if (vertex != null) {
private Optional<ExecutionVertex> updateAndGet(ExecutionAttemptID id) { synchronized (tasks) { ExecutionVertex vertex = cachedTasksById.get(id); if (vertex != null || cachedTasksById.containsKey(id)) { return Optional.ofNullable(vertex); } Map<Exe...
class ExecutionAttemptMappingProvider { /** A full list of tasks. */ private final List<ExecutionVertex> tasks; /** The cached mapping, which would only be updated on miss. */ private Map<ExecutionAttemptID, ExecutionVertex> cachedTasksById; public ExecutionAttemptMappingProvider(Iterable<Executi...
class ExecutionAttemptMappingProvider { /** A full list of tasks. */ private final List<ExecutionVertex> tasks; /** The cached mapping, which would only be updated on miss. */ private Map<ExecutionAttemptID, ExecutionVertex> cachedTasksById; public ExecutionAttemptMappingProvider(Iterable<Executi...
Any reason to not use `Text.format`?
private Mail mailOf(Notification n, Collection<String> recipients) { var subject = new Formatter().format("[%s] Vespa Notification for %s", n.level().toString().toUpperCase(), n.type().name()); var body = new StringBuilder(); body.append("Source: ").append(n.source().toString()).append("\n") ...
var subject = new Formatter().format("[%s] Vespa Notification for %s", n.level().toString().toUpperCase(), n.type().name());
private Mail mailOf(Notification n, Collection<String> recipients) { var subject = Text.format("[%s] Vespa Notification for %s", n.level().toString().toUpperCase(), n.type().name()); var body = new StringBuilder(); body.append("Source: ").append(n.source().toString()).append("\n") ...
class Notifier { private final CuratorDb curatorDb; private final Mailer mailer; private static final Logger log = Logger.getLogger(Notifier.class.getName()); public Notifier(CuratorDb curatorDb, Mailer mailer) { this.curatorDb = curatorDb; this.mailer = mailer; } public void ...
class Notifier { private final CuratorDb curatorDb; private final Mailer mailer; private static final Logger log = Logger.getLogger(Notifier.class.getName()); public Notifier(CuratorDb curatorDb, Mailer mailer) { this.curatorDb = Objects.requireNonNull(curatorDb); this.mailer = Objects...
also mark it final for consistency
public void testQueuedBuffers() throws Exception { final NettyShuffleEnvironment network = createNettyShuffleEnvironment(); final ResultPartition localResultPartition = new ResultPartitionBuilder() .setResultPartitionManager(network.getResultPartitionManager()) .setupBufferPoolFactoryFromNettyShuffleEnvironm...
RemoteInputChannel remoteInputChannel = InputChannelBuilder.newBuilder()
public void testQueuedBuffers() throws Exception { final NettyShuffleEnvironment network = createNettyShuffleEnvironment(); final ResultPartition resultPartition = new ResultPartitionBuilder() .setResultPartitionManager(network.getResultPartitionManager()) .setupBufferPoolFactoryFromNettyShuffleEnvironment(n...
class SingleInputGateTest extends InputGateTestBase { /** * Tests basic correctness of buffer-or-event interleaving and correct <code>null</code> return * value after receiving all end-of-partition events. */ @Test public void testBasicGetNextLogic() throws Exception { final SingleInputGate inputGate = cr...
class SingleInputGateTest extends InputGateTestBase { /** * Tests basic correctness of buffer-or-event interleaving and correct <code>null</code> return * value after receiving all end-of-partition events. */ @Test public void testBasicGetNextLogic() throws Exception { final SingleInputGate inputGate = cr...
Sorry for the confusion. No, there is no case that `preposition` is `not null` and `catalog` is `null`. In fact, based on our discussion, I have already removed `preposition` field from `ShowDatabasesOperation`. `catalog` is null (so the `preposition` that doesn't exist now) only when there is no `FROM/IN` clause. ...
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 }
can we add a TODO here, because actually the record should pass the Table API unmodified, but this will come with FLUP-136
public void testAvroToRow() throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.getConfig().registerTypeWithKryoSerializer(LocalDate.class, AvroKryoSerializerUtils.JodaLocalDateSerializer.class); env.getConfig().registerTypeWithKryoSerializer(LocalTime.cla...
"Berlin,42,Berlin,Bakerstreet,12049,null,null,123456,12:12:12.000,123456," +
public void testAvroToRow() throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); StreamTableEnvironment tEnv = StreamTableEnvironment.create( env, EnvironmentSettings.newInstance().useBlinkPlanner().build()); Table t = tEnv.fromDataStream(testData(env));...
class AvroTypesITCase extends TableProgramsClusterTestBase { private static final User USER_1 = User.newBuilder() .setName("Charlie") .setFavoriteColor("blue") .setFavoriteNumber(null) .setTypeBoolTest(false) .setTypeDoubleTest(1.337d) .setTypeNullTest(null) .setTypeLongTest(1337L) .setTypeArr...
class AvroTypesITCase extends TableProgramsClusterTestBase { private static final User USER_1 = User.newBuilder() .setName("Charlie") .setFavoriteColor("blue") .setFavoriteNumber(null) .setTypeBoolTest(false) .setTypeDoubleTest(1.337d) .setTypeNullTest(null) .setTypeLongTest(1337L) .setTypeArr...
HBase and JDBC DataSource should be process in pluggable way. I will refactor here after merged
public static YamlProxyConfiguration load(final String path) throws IOException { YamlProxyServerConfiguration serverConfig = loadServerConfiguration(getResourceFile(String.join("/", path, SERVER_CONFIG_FILE))); File configPath = getResourceFile(path); Collection<YamlProxyDatabaseConfiguration> ...
LinkedHashMap::new)));
public static YamlProxyConfiguration load(final String path) throws IOException { YamlProxyServerConfiguration serverConfig = loadServerConfiguration(getResourceFile(String.join("/", path, SERVER_CONFIG_FILE))); File configPath = getResourceFile(path); Collection<YamlProxyDatabaseConfiguration> ...
class ProxyConfigurationLoader { private static final String SERVER_CONFIG_FILE = "server.yaml"; private static final Pattern SCHEMA_CONFIG_FILE_PATTERN = Pattern.compile("config-.+\\.yaml"); private static final Pattern HBASE_CONFIG_FILE = Pattern.compile("hbase-.+\\.yaml"); /** ...
class ProxyConfigurationLoader { private static final String SERVER_CONFIG_FILE = "server.yaml"; private static final Pattern SCHEMA_CONFIG_FILE_PATTERN = Pattern.compile("config-.+\\.yaml"); /** * Load configuration of ShardingSphere-Proxy. * * @param path configuration path o...
Thinking about this a bit more, perhaps always having an empty PCollection here would be good. Then people can unconditionally do things like add up all the errors or check for them etc.
public PCollectionRowTuple expand(PCollectionRowTuple input) { String queryString = config.getString("query"); if (queryString == null) { throw new IllegalArgumentException("Configuration must provide a query string."); } S...
if (errorList.size() == 0) {
public PCollectionRowTuple expand(PCollectionRowTuple input) { String queryString = config.getString("query"); if (queryString == null) { throw new IllegalArgumentException("Configuration must provide a query string."); } S...
class SqlSchemaTransform implements SchemaTransform { final Row config; public SqlSchemaTransform(Row config) { this.config = config; } @Override public PTransform<PCollectionRowTuple, PCollectionRowTuple> buildTransform() { return new PTransform<PCollectionRowTuple, PCollectionRowTupl...
class SqlSchemaTransform implements SchemaTransform { final Row config; public SqlSchemaTransform(Row config) { this.config = config; } @Override public PTransform<PCollectionRowTuple, PCollectionRowTuple> buildTransform() { return new PTransform<PCollectionRowTuple, PCollectionRowTupl...
```suggestion this.deploymentMetricsMaintainer = duration(10, MINUTES); ``` With so many collisions already, and at such a low rate, this one probably needs more bump?
public Intervals(SystemName system) { this.system = Objects.requireNonNull(system); this.defaultInterval = duration(system.isCd() || system == SystemName.dev ? 1 : 5, MINUTES); this.outstandingChangeDeployer = duration(3, MINUTES); this.versionStatusUpdater = duration(3, ...
this.deploymentMetricsMaintainer = duration(6, MINUTES);
public Intervals(SystemName system) { this.system = Objects.requireNonNull(system); this.defaultInterval = duration(system.isCd() || system == SystemName.dev ? 1 : 5, MINUTES); this.outstandingChangeDeployer = duration(3, MINUTES); this.versionStatusUpdater = duration(3, ...
class Intervals { private static final Duration MAX_CD_INTERVAL = Duration.ofHours(1); private final SystemName system; private final Duration defaultInterval; private final Duration outstandingChangeDeployer; private final Duration versionStatusUpdater; private final ...
class Intervals { private static final Duration MAX_CD_INTERVAL = Duration.ofHours(1); private final SystemName system; private final Duration defaultInterval; private final Duration outstandingChangeDeployer; private final Duration versionStatusUpdater; private final ...
Simplified the logic. Currently, we are allowing empty application Id. @JonathanGiles do we want to disallow empty application Id?
public HttpLogOptions setApplicationId(final String applicationId) { if (applicationId != null && (applicationId.length() > MAX_APPLICATION_ID_LENGTH || applicationId.contains(" "))) { if (applicationId.contains(" ")) { throw logger .logExceptionAsErro...
if (applicationId != null
public HttpLogOptions setApplicationId(final String applicationId) { if (!CoreUtils.isNullOrEmpty(applicationId)) { if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) { throw logger .logExceptionAsError(new IllegalArgumentException("'applicationId' length can...
class HttpLogOptions { private String applicationId; private HttpLogDetailLevel logLevel; private Set<String> allowedHeaderNames; private Set<String> allowedQueryParamNames; private final ClientLogger logger = new ClientLogger(HttpLogOptions.class); private static final int MAX_APPLICATION_ID_L...
class HttpLogOptions { private String applicationId; private HttpLogDetailLevel logLevel; private Set<String> allowedHeaderNames; private Set<String> allowedQueryParamNames; private final ClientLogger logger = new ClientLogger(HttpLogOptions.class); private static final int MAX_APPLICATION_ID_L...
Please 1. Check the valid of metadata 2. Check the permission The logic of the two should not be interspersed and executed together
public void analyze(Analyzer analyzer) throws UserException { super.analyze(analyzer); if (this.dbTableName != null) { String dbName; if (Strings.isNullOrEmpty(this.dbTableName.getDb())) { dbName = analyzer.getDefaultDb(); } else { ...
if (Strings.isNullOrEmpty(dbName)) {
public void analyze(Analyzer analyzer) throws UserException { super.analyze(analyzer); if (this.dbTableName != null) { this.dbTableName.analyze(analyzer); String dbName = this.dbTableName.getDb(); String tblName = this.dbTableName.getTbl(); check...
class AnalyzeStmt extends DdlStmt { private final TableName dbTableName; private final List<String> columnNames; private Map<String, String> properties; private Database db; private List<Table> tables; private final Map<Long, List<String>> tableIdToColumnName = Maps.newHashMap(); publ...
class AnalyzeStmt extends DdlStmt { private static final Logger LOG = LogManager.getLogger(AnalyzeStmt.class); public static final String CBO_STATISTICS_TASK_TIMEOUT_SEC = "cbo_statistics_task_timeout_sec"; private static final ImmutableSet<String> PROPERTIES_SET = new ImmutableSet.Builder<String>() ...
We can use a constant for ".balo". There is already one in ProjectDirConstants. We can copy it to ProjectConstants and use it.
private static Path validateBaloPath(String baloPath) { if (baloPath == null) { throw new IllegalArgumentException("baloPath cannot be null"); } Path absBaloPath = Paths.get(baloPath).toAbsolutePath(); if (!absBaloPath.toFile().canRead()) { throw new RuntimeExcep...
if (!absBaloPath.toString().endsWith(".balo")) {
private static Path validateBaloPath(String baloPath) { if (baloPath == null) { throw new IllegalArgumentException("baloPath cannot be null"); } Path absBaloPath = Paths.get(baloPath).toAbsolutePath(); if (!absBaloPath.toFile().canRead()) { throw new RuntimeExcep...
class BaloFiles { private static final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**.bal"); private static Gson gson = new Gson(); private BaloFiles() { } public static PackageData loadPackageData(String baloPath) { Path absBaloPath = validateBaloPath(baloPath); ...
class name to utils private BaloFiles() { }
Could `3L` be replaced to `columnNames.size()`? So if `columnNames` value changed, it's not necessary to change the hard coded `3L`.
public void assertCalculateSuccess() { Iterable<Object> calculate = new CRC32MatchMySQLSingleTableDataCalculator().calculate(dataCalculateParameter); long calculateSize = StreamSupport.stream(calculate.spliterator(), false).count(); assertThat(calculateSize, is(3L)); }
assertThat(calculateSize, is(3L));
public void assertCalculateSuccess() { Iterable<Object> calculate = new CRC32MatchMySQLSingleTableDataCalculator().calculate(dataCalculateParameter); long actualDatabaseTypesSize = StreamSupport.stream(calculate.spliterator(), false).count(); long expectedDatabaseTypesSize = dataCalculateParamet...
class CRC32MatchMySQLSingleTableDataCalculatorTest { @Mock private DataCalculateParameter dataCalculateParameter; private PipelineDataSourceWrapper pipelineJobPrepareFailedException; @Before public void setUp() throws SQLException { pipelineJobPrepareFailedException = mock(PipelineDataSou...
class CRC32MatchMySQLSingleTableDataCalculatorTest { @Mock private DataCalculateParameter dataCalculateParameter; private PipelineDataSourceWrapper pipelineDataSource; private Connection connection; @Mock private PreparedStatement preparedStatement; @Mock private ResultSet resultSet...
You can use the constant for "UTF-8" from StandardCharsets class[1] [1] https://docs.oracle.com/javase/8/docs/api/index.html?java/nio/charset/StandardCharsets.html
public void execute(Context context) { BMap<String, BValue> channelObject = (BMap<String, BValue>) context.getRefArgument(0); Channel channel = RabbitMQUtils.getNativeObject(channelObject, RabbitMQConstants.CHANNEL_NATIVE_OBJECT, Channel.class, context); BValue msgContent = conte...
ChannelUtils.basicPublish(channel, routingKey, msgContent.stringValue().getBytes(Charset.forName("UTF-8")),
public void execute(Context context) { BMap<String, BValue> channelObject = (BMap<String, BValue>) context.getRefArgument(0); Channel channel = RabbitMQUtils.getNativeObject(channelObject, RabbitMQConstants.CHANNEL_NATIVE_OBJECT, Channel.class, context); BValue msgContent = conte...
class BasicPublish extends BlockingNativeCallableUnit { private static final Logger LOGGER = LoggerFactory.getLogger(BasicPublish.class); @Override }
class BasicPublish extends BlockingNativeCallableUnit { private static final Logger LOGGER = LoggerFactory.getLogger(BasicPublish.class); @Override }
This is a nice one-liner!
public void updateKeyStore(KeyStore keyStore, String password) { updateKeyStore(sslContextFactory -> { sslContextFactory.setKeyStore(keyStore); if (password != null) { sslContextFactory.setKeyStorePassword(null); } }); }
if (password != null) {
public void updateKeyStore(KeyStore keyStore, String password) { updateKeyStore(sslContextFactory -> { sslContextFactory.setKeyStore(keyStore); if (password != null) { sslContextFactory.setKeyStorePassword(null); } }); }
class DefaultSslKeyStoreContext implements SslKeyStoreContext { private final SslContextFactory sslContextFactory; public DefaultSslKeyStoreContext(SslContextFactory sslContextFactory) { this.sslContextFactory = sslContextFactory; } @Override public void updateKeyStore(KeyStore keyStore) ...
class DefaultSslKeyStoreContext implements SslKeyStoreContext { private final SslContextFactory sslContextFactory; public DefaultSslKeyStoreContext(SslContextFactory sslContextFactory) { this.sslContextFactory = sslContextFactory; } @Override public void updateKeyStore(KeyStore keyStore) ...
@simplynaveen20 In Spring, you can have duplicate parameters in query which are of the same name - for example this query - `Iterable<Project> findByNameAndCreatorOrNameAndCreator(String name, String creator, String name2, String creator2);` This would get converted to this - `select * from c where c.name = @name an...
private String generateQueryParameter(@NonNull String subject, int counter) { return subject.replaceAll("[^a-zA-Z\\d]", "_") + counter; }
return subject.replaceAll("[^a-zA-Z\\d]", "_") + counter;
private String generateQueryParameter(@NonNull String subject, int counter) { return subject.replaceAll("[^a-zA-Z\\d]", "_") + counter; }
class AbstractQueryGenerator { protected AbstractQueryGenerator() { } private String generateUnaryQuery(@NonNull Criteria criteria) { Assert.isTrue(criteria.getSubjectValues().isEmpty(), "Unary criteria should have no one subject value"); Assert.isTrue(CriteriaType.isUnary(criteria.g...
class AbstractQueryGenerator { protected AbstractQueryGenerator() { } private String generateUnaryQuery(@NonNull Criteria criteria) { Assert.isTrue(criteria.getSubjectValues().isEmpty(), "Unary criteria should have no one subject value"); Assert.isTrue(CriteriaType.isUnary(criteria.g...
this is test and it doesn't matter much. but in general you should not create a ObjectMapper per method invocation, This is costly timewise.
private void validateJson(String jsonInString) { try { ObjectMapper mapper = new ObjectMapper(); mapper.readTree(jsonInString); } catch(JsonProcessingException ex) { fail("Diagnostic string is not in json format"); } }
ObjectMapper mapper = new ObjectMapper();
private void validateJson(String jsonInString) { try { OBJECT_MAPPER.readTree(jsonInString); } catch(JsonProcessingException ex) { fail("Diagnostic string is not in json format"); } }
class CosmosDiagnosticsTest extends TestSuiteBase { private CosmosClient gatewayClient; private CosmosClient directClient; private CosmosContainer container; private CosmosAsyncContainer cosmosAsyncContainer; private CosmosClientBuilder cosmosClientBuilder; @BeforeClass(groups = {"emulator"}, t...
class CosmosDiagnosticsTest extends TestSuiteBase { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private CosmosClient gatewayClient; private CosmosClient directClient; private CosmosContainer container; private CosmosAsyncContainer cosmosAsyncContainer; @BeforeClass(gro...
Isn't it more suitable to represent these strings Eg:- "Receiver" constants?
private void annotateLeafPsiElementNodes(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { IElementType elementType = ((LeafPsiElement) element).getElementType(); if (elementType == BallerinaTypes.AT && element.getParent() instanceof AnnotationAttachmentNode) { Annotation anno...
msg = "Receiver";
private void annotateLeafPsiElementNodes(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { IElementType elementType = ((LeafPsiElement) element).getElementType(); if (elementType == BallerinaTypes.AT && element.getParent() instanceof AnnotationAttachmentNode) { Annotation anno...
class BallerinaAnnotator implements Annotator { private static final String VALID_ESCAPE_CHARACTERS = "\\\\[btnfr\"'\\\\]|\\\\u[0-f]{4}|\\\\[0-3][0-7]{2}" + "|\\\\[0-7]{1,2}"; private static final Pattern VALID_ESCAPE_CHAR_PATTERN = Pattern.compile(VALID_ESCAPE_CHARACTERS); private static final...
class BallerinaAnnotator implements Annotator { private static final String VALID_ESCAPE_CHARACTERS = "\\\\[btnfr\"'\\\\]|\\\\u[0-f]{4}|\\\\[0-3][0-7]{2}" + "|\\\\[0-7]{1,2}"; private static final Pattern VALID_ESCAPE_CHAR_PATTERN = Pattern.compile(VALID_ESCAPE_CHARACTERS); private static final...
Why the model name has Schema, can we call it PackageSearchResult etc
private static void searchInCentral(String query) { try { CentralAPIClient client = new CentralAPIClient(); PackageSearchJsonSchema packageSearchJsonSchema = client.searchPackage(query); if (packageSearchJsonSchema.getCount() > 0) { printPackages(packageSearc...
PackageSearchJsonSchema packageSearchJsonSchema = client.searchPackage(query);
private static void searchInCentral(String query) { try { CentralAPIClient client = new CentralAPIClient(); PackageSearchResult packageSearchResult = client.searchPackage(query); if (packageSearchResult.getCount() > 0) { printPackages(packageSearchResult.getP...
class SearchCommand implements BLauncherCmd { private static PrintStream outStream = System.err; @CommandLine.Parameters private List<String> argList; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) private boolean helpFlag; @CommandLine.Option(names = "--debug", hidden = true) ...
class SearchCommand implements BLauncherCmd { private static PrintStream outStream = System.err; @CommandLine.Parameters private List<String> argList; @CommandLine.Option(names = {"--help", "-h"}, hidden = true) private boolean helpFlag; @CommandLine.Option(names = "--debug", hidden = true) ...
It's removed. `tests/jballerina-unit-test/src/test/resources/test-src/query/group_by_clause_negative.bal` L74:82
public void testNegativeCases() { int i = 0; BAssertUtil.validateError(negativeResult, i++, "incompatible types: expected '(any|error)[]', found 'int'", 23, 37); BAssertUtil.validateError(negativeResult, i++, "sequence variable can be used in a single element list " + ...
BAssertUtil.validateError(negativeResult, i++, "invalid operation: type " +
public void testNegativeCases() { int i = 0; BAssertUtil.validateError(negativeResult, i++, "incompatible types: expected '(any|error)[]', found 'int'", 23, 37); BAssertUtil.validateError(negativeResult, i++, "sequence variable can be used in a single element list " + ...
class GroupByClauseTest { private CompileResult resultWithListCtr; private CompileResult resultWithInvocation; private CompileResult negativeResult; private CompileResult negativeSemanticResult; @BeforeClass public void setup() { resultWithListCtr = BCompileUtil.compile("test-src/query/...
class GroupByClauseTest { private CompileResult resultWithListCtr; private CompileResult resultWithInvocation; private CompileResult negativeResult; private CompileResult negativeSemanticResult; @BeforeClass public void setup() { resultWithListCtr = BCompileUtil.compile("test-src/query/...
It's fine to me, we only read serial from PG and wont write a serial column.
public static TestTable getSerialTable() { return new TestTable( TableSchema.builder() .field("f0", DataTypes.SMALLINT()) .field("f1", DataTypes.INT()) .field("f2", DataTypes.SMALLINT()) .field("f3", DataTypes.INT()) .field("f4", DataTypes.BIGINT()) .field("f5", DataTypes.BIGINT()) .bui...
"5"
public static TestTable getSerialTable() { return new TestTable( TableSchema.builder() .field("f0", DataTypes.SMALLINT().notNull()) .field("f1", DataTypes.INT().notNull()) .field("f2", DataTypes.SMALLINT().notNull()) .field("f3", DataTypes.INT().notNull()) .field("f4", DataTypes.BIGINT().n...
class TestTable { TableSchema schema; String pgSchemaSql; String values; public TestTable(TableSchema schema, String pgSchemaSql, String values) { this.schema = schema; this.pgSchemaSql = pgSchemaSql; this.values = values; } }
class TestTable { TableSchema schema; String pgSchemaSql; String values; public TestTable(TableSchema schema, String pgSchemaSql, String values) { this.schema = schema; this.pgSchemaSql = pgSchemaSql; this.values = values; } }
The returned `NodeMetrics` object is shared and thus may be read outside the lock whilst concurrently being updated by another thread. Is this a problem? Should we deep-copy the metrics to make sure they're internally consistent? This is not something introduced by this PR, but just a general observation.
public Node getRecipient(List<Mirror.Entry> choices) { if (choices.isEmpty()) return null; double weightSum = 0.0; Node selectedNode = null; synchronized (this) { for (Mirror.Entry entry : choices) { NodeMetrics nodeMetrics = getNodeMetrics(entry); ...
selectedNode = new Node(entry, nodeMetrics);
public Node getRecipient(List<Mirror.Entry> choices) { if (choices.isEmpty()) return null; double weightSum = 0.0; Node selectedNode = null; synchronized (this) { for (Mirror.Entry entry : choices) { NodeMetrics nodeMetrics = getNodeMetrics(entry); ...
class Node { Node(Mirror.Entry e, NodeMetrics m) { entry = e; metrics = m; } Mirror.Entry entry; NodeMetrics metrics; }
class Node { Node(Mirror.Entry e, NodeMetrics m) { entry = e; metrics = m; } Mirror.Entry entry; NodeMetrics metrics; }
Consider adding some additional validation of tenant id
private static void verifyValues(JsonNode root) { var cursor = new JsonAccessor(root); cursor.get("rules").forEachArrayElement(rule -> rule.get("conditions").forEachArrayElement(condition -> { var dimension = condition.get("dimension"); if (dimension.isEqualTo(DimensionHelper.toW...
condition.get("values").forEachArrayElement(conditionValue -> conditionValue.asString()
private static void verifyValues(JsonNode root) { var cursor = new JsonAccessor(root); cursor.get("rules").forEachArrayElement(rule -> rule.get("conditions").forEachArrayElement(condition -> { var dimension = condition.get("dimension"); if (dimension.isEqualTo(DimensionHelper.toW...
class SystemFlagsDataArchive { private static final ObjectMapper mapper = new ObjectMapper(); private final Map<FlagId, Map<String, FlagData>> files; private SystemFlagsDataArchive(Map<FlagId, Map<String, FlagData>> files) { this.files = files; } public static SystemFlagsDataArchive from...
class SystemFlagsDataArchive { private static final ObjectMapper mapper = new ObjectMapper(); private final Map<FlagId, Map<String, FlagData>> files; private SystemFlagsDataArchive(Map<FlagId, Map<String, FlagData>> files) { this.files = files; } public static SystemFlagsDataArchive from...
Do you think we should add a new method in `ExceptionUtils` to represent this meaning?
private void ensureRunning() throws Exception { if (wasClosed || !thread.isAlive()) { cleanupRequests(); IllegalStateException exception = new IllegalStateException("not running"); if (thrown != null) { exception.addSuppressed(thrown); ...
IllegalStateException exception = new IllegalStateException("not running");
private void ensureRunning() throws Exception { if (wasClosed || !thread.isAlive()) { cleanupRequests(); IllegalStateException exception = new IllegalStateException("not running"); if (thrown != null) { exception.addSuppressed(thrown); ...
class ChannelStateWriteRequestExecutorImpl implements ChannelStateWriteRequestExecutor { private static final Logger LOG = LoggerFactory.getLogger(ChannelStateWriteRequestExecutorImpl.class); private final ChannelStateWriteRequestDispatcher dispatcher; private final BlockingDeque<ChannelStateW...
class ChannelStateWriteRequestExecutorImpl implements ChannelStateWriteRequestExecutor { private static final Logger LOG = LoggerFactory.getLogger(ChannelStateWriteRequestExecutorImpl.class); private final ChannelStateWriteRequestDispatcher dispatcher; private final BlockingDeque<ChannelStateW...
See my earlier comment, I think it should check if more than one mechanism is reg-ed - if it is only one then no need to check the mech in the context
public Uni<Boolean> sendChallenge(RoutingContext routingContext) { routingContext.request().resume(); Uni<Boolean> result = null; if (usePathSpecificMechanism(routingContext)) { HttpAuthenticationMechanism matchingMech = routingContext.get(HttpAut...
if (usePathSpecificMechanism(routingContext)) {
public Uni<Boolean> sendChallenge(RoutingContext routingContext) { routingContext.request().resume(); Uni<Boolean> result = null; if (mechanisms.length > 1) { HttpAuthenticationMechanism matchingMech = routingContext.get(HttpAuthenticationMechanis...
class HttpAuthenticator { private final IdentityProviderManager identityProviderManager; private final Instance<PathMatchingHttpSecurityPolicy> pathMatchingPolicy; private final HttpAuthenticationMechanism[] mechanisms; public HttpAuthenticator(IdentityProviderManager identityProviderManager, ...
class HttpAuthenticator { private final IdentityProviderManager identityProviderManager; private final Instance<PathMatchingHttpSecurityPolicy> pathMatchingPolicy; private final HttpAuthenticationMechanism[] mechanisms; public HttpAuthenticator(IdentityProviderManager identityProviderManager, ...
Even though the operator precedence is well defined here, I think it could be good to have some parentheses to be entirely explicit about the intention
public double getRetryDelay(int retry) { long retryMultiplier = 0l; if (retry > 1) { retryMultiplier = Math.min(10000, 1L << (retry-1)); } return Math.min(10.0, retryMultiplier*baseDelayUS.get()/US); }
return Math.min(10.0, retryMultiplier*baseDelayUS.get()/US);
public double getRetryDelay(int retry) { long retryMultiplier = 0l; if (retry > 1) { retryMultiplier = 1L << Math.min(20, retry-1); } return Math.min(10.0, (retryMultiplier*baseDelayUS.get())/US); }
class RetryTransientErrorsPolicy implements RetryPolicy { private static final double US = 1000000; private final AtomicBoolean enabled = new AtomicBoolean(true); private volatile AtomicLong baseDelayUS = new AtomicLong(1000); /** * Sets whether or not this policy should allow retries or not. ...
class RetryTransientErrorsPolicy implements RetryPolicy { private static final double US = 1000000; private final AtomicBoolean enabled = new AtomicBoolean(true); private volatile AtomicLong baseDelayUS = new AtomicLong(1000); /** * Sets whether or not this policy should allow retries or not. ...
```suggestion candidateBeList.add(backendList.get(beIndex++ % size)); ``` obtain size = backendList.size() in other place
private List<TScanRangeLocations> getShardLocations() throws UserException { if (esTablePartitions == null) { if (table.getLastMetaDataSyncException() != null) { throw new UserException("fetch es table [" + table.getName() + "] metadata failure: " + table.getLastMetaDataSync...
candidateBeList.add(backendList.get(beIndex++ % backendList.size()));
private List<TScanRangeLocations> getShardLocations() throws UserException { if (esTablePartitions == null) { if (table.getLastMetaDataSyncException() != null) { throw new UserException("fetch es table [" + table.getName() + "] metadata failure: " + table.getLastMetaDataSync...
class EsScanNode extends ScanNode { private static final Logger LOG = LogManager.getLogger(EsScanNode.class); private final Random random = new Random(System.currentTimeMillis()); private Multimap<String, Backend> backendMap; private List<Backend> backendList; private EsTablePartitions esTablePart...
class EsScanNode extends ScanNode { private static final Logger LOG = LogManager.getLogger(EsScanNode.class); private final Random random = new Random(System.currentTimeMillis()); private Multimap<String, Backend> backendMap; private List<Backend> backendList; private EsTablePartitions esTablePart...
According to the spec yes, but in quarkus, if `quarkus.arc.transform-unproxyable-classes=true` (default value) the `final` modifier is simply removed and the method is intercepted. It should be tested in the `io.quarkus.security.test.cdi.SecurityAnnotationOnFinalMethodTest`.
void forEachMethod(ClassInfo clazz, Consumer<MethodInfo> action) { for (MethodInfo method : clazz.methods()) { if (method.name().startsWith("<")) { continue; } if (Modifier.isPrivate(method.flags())) { continue...
void forEachMethod(ClassInfo clazz, Consumer<MethodInfo> action) { for (MethodInfo method : clazz.methods()) { if (method.name().startsWith("<")) { continue; } if (method.isSynthetic()) { continue; ...
class FaultToleranceScanner { private final IndexView index; private final AnnotationStore annotationStore; private final AnnotationProxyBuildItem proxy; private final ClassOutput output; FaultToleranceScanner(IndexView index, AnnotationStore annotationStore, AnnotationProxyBuildItem proxy, ...
class FaultToleranceScanner { private final IndexView index; private final AnnotationStore annotationStore; private final AnnotationProxyBuildItem proxy; private final ClassOutput output; FaultToleranceScanner(IndexView index, AnnotationStore annotationStore, AnnotationProxyBuildItem proxy, ...
Yes, it's the same format as in `dependency:tree`
public void visit(DependencyNode node) { final Dependency dep = node.getDependency(); if(dep == null) { return; } if(depth != null) { buf.setLength(0); if (!depth.isEmpty()) { for (int i = 0; i < depth.size() - 1; ++i) { ...
visitEnter(node);
public void visit(DependencyNode node) { final Dependency dep = node.getDependency(); if(dep == null) { return; } if(depth != null) { buf.setLength(0); if (!depth.isEmpty()) { for (int i = 0; i < depth.size() - 1; ++i) { ...
class BuildDependencyGraphVisitor { private final Set<AppArtifactKey> appDeps; private final StringBuilder buf; private final Consumer<String> buildTreeConsumer; private final List<Boolean> depth; private DependencyNode deploymentNode; private DependencyNode runtimeNode; private Artifact r...
class BuildDependencyGraphVisitor { private final Set<AppArtifactKey> appDeps; private final StringBuilder buf; private final Consumer<String> buildTreeConsumer; private final List<Boolean> depth; private DependencyNode deploymentNode; private DependencyNode runtimeNode; private Artifact r...
i do not see a big difference between these tests and tests for int types... `ARRAY_REMOVE` invokes same code for both.... Probably just one (int or varchar is enough)
Stream<TestSetSpec> getTestSetSpecs() { return Stream.of( TestSetSpec.forFunction(BuiltInFunctionDefinitions.ARRAY_CONTAINS) .onFieldsWithData( new Integer[] {1, 2, 3}, null, n...
"ARRAY_REMOVE(f2, cast(NULL AS VARCHAR))",
Stream<TestSetSpec> getTestSetSpecs() { return Stream.of( TestSetSpec.forFunction(BuiltInFunctionDefinitions.ARRAY_CONTAINS) .onFieldsWithData( new Integer[] {1, 2, 3}, null, n...
class CollectionFunctionsITCase extends BuiltInFunctionTestBase { @Override }
class CollectionFunctionsITCase extends BuiltInFunctionTestBase { @Override }
I don't think we should. It's more like a fire-and-forget style of communication...
public CompletionStage<Void> invoke(ScheduledExecution execution) throws Exception { if (running.compareAndSet(false, true)) { return delegate.invoke(execution).whenComplete((r, t) -> running.set(false)); } LOG.debugf("Skipped scheduled invoker execution: %s", delegate.getClass().get...
event.fireAsync(payload);
public CompletionStage<Void> invoke(ScheduledExecution execution) throws Exception { if (running.compareAndSet(false, true)) { return delegate.invoke(execution).whenComplete((r, t) -> running.set(false)); } LOG.debugf("Skipped scheduled invoker execution: %s", delegate.getClass().get...
class SkipConcurrentExecutionInvoker extends DelegateInvoker { private static final Logger LOG = Logger.getLogger(SkipConcurrentExecutionInvoker.class); private final AtomicBoolean running; private final Event<SkippedExecution> event; public SkipConcurrentExecutionInvoker(ScheduledInvoker delegate, E...
class SkipConcurrentExecutionInvoker extends DelegateInvoker { private static final Logger LOG = Logger.getLogger(SkipConcurrentExecutionInvoker.class); private final AtomicBoolean running; private final Event<SkippedExecution> event; public SkipConcurrentExecutionInvoker(ScheduledInvoker delegate, E...
this may throw java.lang.ClassCastException. It is better to compare their class before convert.
public boolean equals(Object o) { if (!super.equals(o)) { return false; } VarcharType that = (VarcharType) o; return len == that.len; }
VarcharType that = (VarcharType) o;
public boolean equals(Object o) { if (!super.equals(o)) { return false; } VarcharType that = (VarcharType) o; return len == that.len; }
class VarcharType extends DataType { private final int len; public VarcharType(int len) { this.len = len; } public static VarcharType createVarcharType(int len) { return new VarcharType(len); } @Override public Type toCatalogDataType() { return ScalarType.createVar...
class VarcharType extends DataType { private final int len; public VarcharType(int len) { this.len = len; } public static VarcharType createVarcharType(int len) { return new VarcharType(len); } @Override public Type toCatalogDataType() { return ScalarType.createVar...
I think we can add the constant for `CompressedSourceTest.java` at least.
public void testEmptyLzoProgress() throws IOException { File tmpFile = tmpFolder.newFile("empty.lzo_deflate"); String filename = tmpFile.toPath().toString(); writeFile(tmpFile, new byte[0], CompressionMode.LZO); PipelineOptions options = PipelineOptionsFactory.create(); CompressedSource<Byte> sourc...
assertEquals(0.0, reader.getFractionConsumed(), 1e-6);
public void testEmptyLzoProgress() throws IOException { File tmpFile = tmpFolder.newFile("empty.lzo_deflate"); String filename = tmpFile.toPath().toString(); writeFile(tmpFile, new byte[0], CompressionMode.LZO); PipelineOptions options = PipelineOptionsFactory.create(); CompressedSource<Byte> sourc...
class ExtractIndexFromTimestamp extends DoFn<Byte, KV<Long, Byte>> { @ProcessElement public void processElement(ProcessContext context) { context.output(KV.of(context.timestamp().getMillis(), context.element())); } }
class ExtractIndexFromTimestamp extends DoFn<Byte, KV<Long, Byte>> { @ProcessElement public void processElement(ProcessContext context) { context.output(KV.of(context.timestamp().getMillis(), context.element())); } }
How about ``` Preconditions.checkState( serializedJobInformation instanceof NonOffloaded, "Trying to work with offloaded serialized job information."); NonOffloaded<JobInformation> jobInformation = (NonOffloaded<JobInformation>) serializedJobInformation;...
public TaskInformation getTaskInformation() throws IOException, ClassNotFoundException { if (taskInformation != null) { return taskInformation; } if (serializedTaskInformation instanceof NonOffloaded) { NonOffloaded<TaskInformation> taskInformation = (...
"Trying to work with offloaded serialized task information.");
public TaskInformation getTaskInformation() throws IOException, ClassNotFoundException { if (taskInformation != null) { return taskInformation; } if (serializedTaskInformation instanceof NonOffloaded) { NonOffloaded<TaskInformation> taskInformation = (...
class Offloaded<T> extends MaybeOffloaded<T> { private static final long serialVersionUID = 4544135485379071679L; /** The key of the offloaded value BLOB. */ public PermanentBlobKey serializedValueKey; @SuppressWarnings("unused") public Offloaded() {} public Offloaded(...
class Offloaded<T> extends MaybeOffloaded<T> { private static final long serialVersionUID = 4544135485379071679L; /** The key of the offloaded value BLOB. */ public PermanentBlobKey serializedValueKey; @SuppressWarnings("unused") public Offloaded() {} public Offloaded(...
Thanks! Let's try this then ...
public void close() { if (closed.get()) return; closed.set(true); synchronized (nodeTable.writeLock) { synchronized (clusterTable.writeLock) { for (SqlCompiler sqlCompiler : sqlCompilerPool) sqlCompiler.close(); engine.close(); ...
closed.set(true);
public void close() { if (closed.getAndSet(true)) return; synchronized (nodeTable.writeLock) { synchronized (clusterTable.writeLock) { for (SqlCompiler sqlCompiler : sqlCompilerPool) sqlCompiler.close(); engine.close(); } ...
class QuestMetricsDb extends AbstractComponent implements MetricsDb { private static final Logger log = Logger.getLogger(QuestMetricsDb.class.getName()); private final Table nodeTable; private final Table clusterTable; private final Clock clock; private final String dataDir; private final Cai...
class QuestMetricsDb extends AbstractComponent implements MetricsDb { private static final Logger log = Logger.getLogger(QuestMetricsDb.class.getName()); private final Table nodeTable; private final Table clusterTable; private final Clock clock; private final String dataDir; private final Cai...
Hi @pnowojski , thanks for your analysis! > I would move: SinkWriterOperatorFactory.class.getName().equals(streamOperatorFactoryClassName) > check, into the boolean StreamConfig#isSinkWriterOperatorFactory(Class<...> ...) method. > It doesn't fit there very well, BUT at least it would justify why we have the checkSta...
public void setStreamOperatorFactory(StreamOperatorFactory<?> factory) { if (factory != null) { toBeSerializedConfigObjects.put(SERIALIZED_UDF, factory); config.setString(SERIALIZED_UDF_CLASS_NAME, factory.getClass().getName()); } }
config.setString(SERIALIZED_UDF_CLASS_NAME, factory.getClass().getName());
public void setStreamOperatorFactory(StreamOperatorFactory<?> factory) { if (factory != null) { toBeSerializedConfigObjects.put(SERIALIZED_UDF, factory); config.setString(SERIALIZED_UDF_CLASS_NAME, factory.getClass().getName()); } }
class StreamConfig implements Serializable { private static final long serialVersionUID = 1L; public static final String SERIALIZED_UDF = "serializedUDF"; /** * Introduce serializedUdfClassName to avoid unnecessarily heavy {@link * */ public static final String SERIALIZ...
class StreamConfig implements Serializable { private static final long serialVersionUID = 1L; public static final String SERIALIZED_UDF = "serializedUDF"; /** * Introduce serializedUdfClassName to avoid unnecessarily heavy {@link * */ public static final String SERIALIZ...
what is the difference between DUPLICATE_CREATE_TASK and TAKS_EXISTS?
public long createTask(Task task) { if (!tryLock()) { return TASK_CREATE_TIMEOUT; } try { if (nameToTaskMap.containsKey(task.getName())) { return TASK_EXISTS; } nameToTaskMap.put(task.getName(), task); if (manualTaskMap....
return TASK_EXISTS;
public long createTask(Task task) { if (!tryLock()) { return GET_TASK_LOCK_FAILED; } try { if (nameToTaskMap.containsKey(task.getName())) { return TASK_EXISTS; } nameToTaskMap.put(task.getName(), task); if (manualTaskMap...
class TaskManager { private static final Logger LOG = LogManager.getLogger(TaskManager.class); public static final long TASK_EXISTS = -1L; public static final long DUPLICATE_CREATE_TASK = -2L; public static final long TASK_CREATE_TIMEOUT = -3L; private final Map<Long, Task> manualTaskMa...
class TaskManager { private static final Logger LOG = LogManager.getLogger(TaskManager.class); public static final long TASK_EXISTS = -1L; public static final long DUPLICATE_CREATE_TASK = -2L; public static final long GET_TASK_LOCK_FAILED = -3L; private final Map<Long, Task> manualTaskM...
I agree with you - your solution was more elegant. But we try to avoid lambdas for efficiency reasons. Of course we're not extreme about it: lambdas are a fine solution when they are a good solution, but I still tend to prefer avoiding them in such situations.
protected ConnectionProvider selectConnectionProvider(final String tenantIdentifier) { LOG.debugv("selectConnectionProvider({0})", tenantIdentifier); ConnectionProvider provider = providerMap.get(tenantIdentifier); if (provider == null) { final ConnectionProvider connectionProvider ...
final ConnectionProvider connectionProvider = resolveConnectionProvider(tenantIdentifier);
protected ConnectionProvider selectConnectionProvider(final String tenantIdentifier) { LOG.debugv("selectConnectionProvider({0})", tenantIdentifier); ConnectionProvider provider = providerMap.get(tenantIdentifier); if (provider == null) { final ConnectionProvider connectionProvider ...
class HibernateMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider { private static final Logger LOG = Logger.getLogger(HibernateMultiTenantConnectionProvider.class); private final Map<String, ConnectionProvider> providerMap = new ConcurrentHashMap<>(); @Override protected Con...
class HibernateMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider { private static final Logger LOG = Logger.getLogger(HibernateMultiTenantConnectionProvider.class); private final Map<String, ConnectionProvider> providerMap = new ConcurrentHashMap<>(); @Override protected Con...
Hi, @terrymanu, I've addressed your concern. Please help to take another look. Thanks
void assertUnmarshalYamlAgentConfiguration() { InputStream inputStream = getClass().getResourceAsStream("/conf/agent.yaml"); YamlAgentConfiguration actual = AgentYamlEngine.unmarshalYamlAgentConfiguration(inputStream); assertNotNull(actual); }
assertNotNull(actual);
void assertUnmarshalYamlAgentConfiguration() throws IOException { try (InputStream inputStream = Files.newInputStream(new File(getResourceURL(), "/conf/agent.yaml").toPath())) { YamlAgentConfiguration yamlAgentConfig = AgentYamlEngine.unmarshalYamlAgentConfiguration(inputStream); Map<Str...
class AgentYamlEngineTest { @Test @Test void assertUnmarshalYamlAdvisorsConfiguration() { InputStream inputStream = getClass().getResourceAsStream("/META-INF/conf/advisors.yaml"); YamlAdvisorsConfiguration actual = AgentYamlEngine.unmarshalYamlAdvisorsConfiguration(inputStream...
class AgentYamlEngineTest { @Test @Test void assertUnmarshalYamlAdvisorsConfiguration() { InputStream inputStream = getClass().getResourceAsStream("/META-INF/conf/advisors.yaml"); YamlAdvisorsConfiguration actual = AgentYamlEngine.unmarshalYamlAdvisorsConfiguration(inputStream...
or even pass in maxSize to the serialization logic and only serialize up to that point.
public void onReceive(Object message) { try { if (message instanceof AddMetric) { AddMetric added = (AddMetric) message; String metricName = added.metricName; Metric metric = added.metric; AbstractMetricGroup group = added.group; QueryScopeInfo info = group.getQueryServiceMetricInfo(FILTER); ...
getSender().tell(new Status.Failure(new IOException(overSizeErrorMsg)), getSelf());
public void onReceive(Object message) { try { if (message instanceof AddMetric) { AddMetric added = (AddMetric) message; String metricName = added.metricName; Metric metric = added.metric; AbstractMetricGroup group = added.group; QueryScopeInfo info = group.getQueryServiceMetricInfo(FILTER); ...
class MetricQueryService extends UntypedActor { private static final Logger LOG = LoggerFactory.getLogger(MetricQueryService.class); public static final String METRIC_QUERY_SERVICE_NAME = "MetricQueryService"; public static final String MAXIMUM_FRAME_SIZE_PATH = "akka.remote.netty.tcp.maximum-frame-size"; privat...
class MetricQueryService extends UntypedActor { private static final Logger LOG = LoggerFactory.getLogger(MetricQueryService.class); public static final String METRIC_QUERY_SERVICE_NAME = "MetricQueryService"; private static final String SIZE_EXCEEDED_LOG_TEMPLATE = "{} will not be reported as the metric dump woul...
This can be moved up to initialization and synchronized won't be needed then.
public void testWatermarkEmission() throws Exception { final int numElements = 500; PipelineOptions options = PipelineOptionsFactory.create(); TestCountingSource source = new TestCountingSource(numElements); UnboundedSourceWrapper<KV<Integer, Integer>, TestCountingSource.Co...
synchronized (testHarness.getCheckpointLock()) {
public void testWatermarkEmission() throws Exception { final int numElements = 500; PipelineOptions options = PipelineOptionsFactory.create(); TestCountingSource source = new TestCountingSource(numElements); UnboundedSourceWrapper<KV<Integer, Integer>, TestCountingSource.Co...
class ParameterizedUnboundedSourceWrapperTest { private final int numTasks; private final int numSplits; public ParameterizedUnboundedSourceWrapperTest(int numTasks, int numSplits) { this.numTasks = numTasks; this.numSplits = numSplits; } @Parameterized.Parameters(name = "numTasks = {0...
class ParameterizedUnboundedSourceWrapperTest { private final int numTasks; private final int numSplits; public ParameterizedUnboundedSourceWrapperTest(int numTasks, int numSplits) { this.numTasks = numTasks; this.numSplits = numSplits; } @Parameterized.Parameters(name = "numTasks = {0...
Yes, the `length` check is moved to the constructor of `SqlShowDatabases`, and I added a test case to catch the exception in `catalog_database.q `
public Operation convertSqlNode(SqlShowDatabases sqlShowDatabases, ConvertContext context) { if (sqlShowDatabases.getPreposition() == null) { return new ShowDatabasesOperation( sqlShowDatabases.getLikeType(), sqlShowDatabases.getLikeSqlPattern(), ...
if (fullCatalogName.length > 1) {
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 }
nit: 10000000 name this something so its clear
public void testActiveThreadMetric() throws Exception { int maxThreads = 5; int threadExpirationSec = 60; CountDownLatch processStart1 = new CountDownLatch(2); CountDownLatch processStart2 = new CountDownLatch(3); CountDownLatch processStart3 = new CountDownLatch(4); AtomicBoolean stop = new Ato...
10000000,
public void testActiveThreadMetric() throws Exception { int maxThreads = 5; int threadExpirationSec = 60; CountDownLatch processStart1 = new CountDownLatch(2); CountDownLatch processStart2 = new CountDownLatch(3); CountDownLatch processStart3 = new CountDownLatch(4); AtomicBoolean stop = new Ato...
class StreamingDataflowWorkerTest { private static final Logger LOG = LoggerFactory.getLogger(StreamingDataflowWorkerTest.class); private static final IntervalWindow DEFAULT_WINDOW = new IntervalWindow(new Instant(1234), Duration.millis(1000)); private static final IntervalWindow WINDOW_AT_ZERO = new...
class StreamingDataflowWorkerTest { private static final Logger LOG = LoggerFactory.getLogger(StreamingDataflowWorkerTest.class); private static final IntervalWindow DEFAULT_WINDOW = new IntervalWindow(new Instant(1234), Duration.millis(1000)); private static final IntervalWindow WINDOW_AT_ZERO = new...
Nit: let's pad this string in the front and back to better check "e.getMessage().contains".
public void testInsertFailsGracefully() throws Exception { TableReference ref = new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); List<FailsafeValueInSingleWindow<TableRow, TableRow>> rows = ImmutableList.of(wrapValue(new TableRow()), wrapValue(new TableRo...
toStream(errorWithReasonAndStatus("No rows present in the request.", 400)));
public void testInsertFailsGracefully() throws Exception { TableReference ref = new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); List<FailsafeValueInSingleWindow<TableRow, TableRow>> rows = ImmutableList.of(wrapValue(new TableRow()), wrapValue(new TableRo...
class BigQueryServicesImplTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Rule public ExpectedLogs expectedLogs = ExpectedLogs.none(BigQueryServicesImpl.class); private LowLevelHttpResponse[] responses; private MockLowLevelHttpRequest request; private Bigquery bigquery; @Befor...
class BigQueryServicesImplTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Rule public ExpectedLogs expectedLogs = ExpectedLogs.none(BigQueryServicesImpl.class); private LowLevelHttpResponse[] responses; private MockLowLevelHttpRequest request; private Bigquery bigquery; @Befor...
We don't have this API anymore. What if we extract the defaultable parameters and check?
public void testFunctionType() { Symbol symbol = getSymbol(43, 12); FunctionTypeDescriptor type = ((FunctionSymbol) symbol).typeDescriptor(); assertEquals(type.kind(), TypeDescKind.FUNCTION); List<Parameter> parameters = type.parameters(); assertEquals(parameters.size(), 2); ...
BallerinaTypeDescriptor returnType = type.returnTypeDescriptor().get();
public void testFunctionType() { Symbol symbol = getSymbol(43, 12); FunctionTypeDescriptor type = ((FunctionSymbol) symbol).typeDescriptor(); assertEquals(type.kind(), TypeDescKind.FUNCTION); List<Parameter> parameters = type.parameters(); assertEquals(parameters.size(), 2); ...
class TypedescriptorTest { SemanticModel model; @BeforeClass public void setup() { CompilerContext context = new CompilerContext(); CompileResult result = compile("test-src/typedesc_test.bal", context); BLangPackage pkg = (BLangPackage) result.getAST(); model = new Ballerin...
class TypedescriptorTest { SemanticModel model; @BeforeClass public void setup() { CompilerContext context = new CompilerContext(); CompileResult result = compile("test-src/typedesc_test.bal", context); BLangPackage pkg = (BLangPackage) result.getAST(); model = new Ballerin...
Hi @tsreaper , Thank you for your advice. In `flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/SqlFunctionUtils.java` there is an implementation of truncating method designed for `DecimalData`: ``` public static DecimalData struncate(DecimalData b0, int b1) { if (b1 >=...
public static List<TestSpec> testData() { return Arrays.asList( TestSpec.forFunction(BuiltInFunctionDefinitions.PLUS) .onFieldsWithData(new BigDecimal("1514356320000")) .andDataTypes(DataTypes.DECIMAL(19, 0).notNull()) ...
DataTypes.DECIMAL(6, 2).notNull()));
public static List<TestSpec> testData() { return Arrays.asList( TestSpec.forFunction(BuiltInFunctionDefinitions.PLUS) .onFieldsWithData(new BigDecimal("1514356320000")) .andDataTypes(DataTypes.DECIMAL(19, 0).notNull()) ...
class MathFunctionsITCase extends BuiltInFunctionTestBase { @Parameters(name = "{index}: {0}") }
class MathFunctionsITCase extends BuiltInFunctionTestBase { @Parameters(name = "{index}: {0}") }
You're right! Let me fix that
public void start(Future<Void> startFuture) throws Exception { final AtomicInteger remainingCount = new AtomicInteger(httpsOptions != null ? 2 : 1); final HttpServerStartHandler httpServerStartHandler = new HttpServerStartHandler(startFuture, httpOptions, remainingCount); ...
remainingCount);
public void start(Future<Void> startFuture) { final AtomicInteger remainingCount = new AtomicInteger(httpsOptions != null ? 2 : 1); httpServer = vertx.createHttpServer(httpOptions); httpServer.requestHandler(router); httpServer.listen(port, host, event -> { ...
class WebDeploymentVerticle extends AbstractVerticle { private final int port; private final int httpsPort; private final String host; private HttpServer httpServer; private HttpServer httpsServer; private final HttpServerOptions httpOptions; private final HttpSe...
class WebDeploymentVerticle extends AbstractVerticle { private final int port; private final int httpsPort; private final String host; private HttpServer httpServer; private HttpServer httpsServer; private final HttpServerOptions httpOptions; private final HttpSe...
Please use assertThat and InstanceOf to assert
public void assertRightMysqlSchemaDataSources() throws Exception { JDBCRawBackendDataSourceFactory jdbcRawBackendDataSourceFactory = Mockito.mock(JDBCRawBackendDataSourceFactory.class); Mockito.when(jdbcRawBackendDataSourceFactory.build(Mockito.anyString(), Mockito.any())).thenReturn(new Hikari...
assertTrue(proxyDataSourceContext.getDatabaseType() instanceof MySQLDatabaseType);
public void assertRightMysqlSchemaDataSources() throws Exception { JDBCRawBackendDataSourceFactory jdbcRawBackendDataSourceFactory = mock(JDBCRawBackendDataSourceFactory.class); when(jdbcRawBackendDataSourceFactory.build(anyString(), any())).thenReturn(new HikariDataSource()); ProxyDataSourceCon...
class ProxyDataSourceContextTest { @Test public void assertEmptySchemaDataSources() { Map<String, Map<String, DataSourceParameter>> schemaDataSources = new HashMap<>(); ProxyDataSourceContext proxyDataSourceContext = new ProxyDataSourceContext(schemaDataSources); assertTrue(proxyDataSou...
class ProxyDataSourceContextTest { @Test public void assertEmptySchemaDataSources() { Map<String, Map<String, DataSourceParameter>> schemaDataSources = new HashMap<>(); ProxyDataSourceContext proxyDataSourceContext = new ProxyDataSourceContext(schemaDataSources); assertThat(proxyDataSou...
This is going to count as a crash in our SLO monitoring. Can you actually get here or is this rejected by the parser? If you can actually get here you might throw a `UnsupportedOperationException`, if you can't actually get here consider `IllegalArgumentException` (which will still count as a crash but makes it clear i...
void validateJavaUdf(ResolvedNodes.ResolvedCreateFunctionStmt createFunctionStmt) { for (FunctionArgumentType argumentType : createFunctionStmt.getSignature().getFunctionArgumentList()) { Type type = argumentType.getType(); if (type == null) { throw new UnsupportedOperationException("UDF...
throw new NullPointerException("UDF return type must not be null.");
void validateJavaUdf(ResolvedNodes.ResolvedCreateFunctionStmt createFunctionStmt) { for (FunctionArgumentType argumentType : createFunctionStmt.getSignature().getFunctionArgumentList()) { Type type = argumentType.getType(); if (type == null) { throw new UnsupportedOperationException("UDF...
class BeamZetaSqlCatalog { public static final String PRE_DEFINED_WINDOW_FUNCTIONS = "pre_defined_window_functions"; public static final String USER_DEFINED_SQL_FUNCTIONS = "user_defined_functions"; public static final String USER_DEFINED_JAVA_SCALAR_FUNCTIONS = "user_defined_java_scalar_functions"; ...
class BeamZetaSqlCatalog { public static final String PRE_DEFINED_WINDOW_FUNCTIONS = "pre_defined_window_functions"; public static final String USER_DEFINED_SQL_FUNCTIONS = "user_defined_functions"; public static final String USER_DEFINED_JAVA_SCALAR_FUNCTIONS = "user_defined_java_scalar_functions"; ...
db or full db only need one?
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TableName tableName = (TableName) o; return Objects.equals(catalog, tableName.catalog) && Objects.equals(tbl, tableName.tbl) && Objects...
&& Objects.equals(db, tableName.db)
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TableName tableName = (TableName) o; return Objects.equals(catalog, tableName.catalog) && Objects.equals(tbl, tableName.tbl) && Objects...
class TableName implements Writable, GsonPreProcessable, GsonPostProcessable { public static final String LAMBDA_FUNC_TABLE = "__LAMBDA_TABLE"; private String catalog; @SerializedName(value = "tbl") private String tbl; private String db; @SerializedName(value = "fullDb") private String fullD...
class TableName implements Writable, GsonPreProcessable, GsonPostProcessable { public static final String LAMBDA_FUNC_TABLE = "__LAMBDA_TABLE"; private String catalog; @SerializedName(value = "tbl") private String tbl; private String db; @SerializedName(value = "fullDb") private String fullD...
`getCheckedRecordsCount` might be greater than `getRecordsCount`, the percentage could not greater than 100
public ConsistencyCheckJobProgressInfo getJobProgressInfo(final String parentJobId) { Optional<String> checkLatestJobId = PipelineAPIFactory.getGovernanceRepositoryAPI().getCheckLatestJobId(parentJobId); ShardingSpherePreconditions.checkState(checkLatestJobId.isPresent(), () -> new PipelineJobNotFoundEx...
inventoryFinishedPercentage = BigDecimal.valueOf(Math.floorDiv(jobItemProgress.getCheckedRecordsCount() * 100, jobItemProgress.getRecordsCount())).intValue();
public ConsistencyCheckJobProgressInfo getJobProgressInfo(final String parentJobId) { Optional<String> checkLatestJobId = PipelineAPIFactory.getGovernanceRepositoryAPI().getCheckLatestJobId(parentJobId); ShardingSpherePreconditions.checkState(checkLatestJobId.isPresent(), () -> new PipelineJobNotFoundEx...
class ConsistencyCheckJobAPIImpl extends AbstractPipelineJobAPIImpl implements ConsistencyCheckJobAPI { private final YamlConsistencyCheckJobProgressSwapper swapper = new YamlConsistencyCheckJobProgressSwapper(); @Override protected String marshalJobIdLeftPart(final PipelineJobId pipelineJobId) { ...
class ConsistencyCheckJobAPIImpl extends AbstractPipelineJobAPIImpl implements ConsistencyCheckJobAPI { private final YamlConsistencyCheckJobProgressSwapper swapper = new YamlConsistencyCheckJobProgressSwapper(); @Override protected String marshalJobIdLeftPart(final PipelineJobId pipelineJobId) { ...
I was confused because I don't see where the test attempts to catch the failure via try/catch or ExpectedException test rule.
public IntervalWindow assignWindow(Instant timestamp) { return new IntervalWindow( BoundedWindow.TIMESTAMP_MIN_VALUE, GlobalWindow.INSTANCE.maxTimestamp()); }
BoundedWindow.TIMESTAMP_MIN_VALUE, GlobalWindow.INSTANCE.maxTimestamp());
public IntervalWindow assignWindow(Instant timestamp) { return new IntervalWindow( BoundedWindow.TIMESTAMP_MIN_VALUE, GlobalWindow.INSTANCE.maxTimestamp()); }
class TestWindowFn extends PartitioningWindowFn<Object, IntervalWindow> { @Override @Override public boolean isCompatible(WindowFn<?, ?> other) { return equals(other); } @Override public Coder<IntervalWindow> windowCoder() { return IntervalWindowCoder.of(); } }
class TestWindowFn extends PartitioningWindowFn<Object, IntervalWindow> { @Override @Override public boolean isCompatible(WindowFn<?, ?> other) { return equals(other); } @Override public Coder<IntervalWindow> windowCoder() { return IntervalWindowCoder.of(); } }
Good point, I can try. Without this I got an exception telling me I had to chunk it, but yeah, you're probably right that the header should be enough. If AsyncFile gives me the file size.
public void writeResponse(AsyncFile file, Type genericType, ServerRequestContext context) throws WebApplicationException { ResteasyReactiveRequestContext ctx = ((ResteasyReactiveRequestContext) context); ctx.suspend(); ServerHttpResponse response = context.serverResponse(); response.setC...
response.setChunked(true);
public void writeResponse(AsyncFile file, Type genericType, ServerRequestContext context) throws WebApplicationException { ResteasyReactiveRequestContext ctx = ((ResteasyReactiveRequestContext) context); ctx.suspend(); ServerHttpResponse response = context.serverResponse(); if (...
class ServerVertxAsyncFileMessageBodyWriter extends VertxAsyncFileMessageBodyWriter implements ServerMessageBodyWriter<AsyncFile> { @Override public boolean isWriteable(Class<?> type, Type genericType, ResteasyReactiveResourceInfo target, MediaType mediaType) { return AsyncFile.class.i...
class ServerVertxAsyncFileMessageBodyWriter extends VertxAsyncFileMessageBodyWriter implements ServerMessageBodyWriter<AsyncFile> { @Override public boolean isWriteable(Class<?> type, Type genericType, ResteasyReactiveResourceInfo target, MediaType mediaType) { return AsyncFile.class.i...
It's true, though! 😬 But I'll remove it.
OperationHandlerImpl createHandler() throws Exception { VisitorSession visitorSession = mock(VisitorSession.class); when(documentAccess.createVisitorSession(any(VisitorParameters.class))).thenAnswer(p -> { VisitorParameters params = (VisitorParameter...
OperationHandlerImpl createHandler() throws Exception { VisitorSession visitorSession = mock(VisitorSession.class); when(documentAccess.createVisitorSession(any(VisitorParameters.class))).thenAnswer(p -> { VisitorParameters params = (VisitorParameters)p.getArguments(...
class OperationHandlerImplFixture { DocumentAccess documentAccess = mock(DocumentAccess.class); AtomicReference<VisitorParameters> assignedParameters = new AtomicReference<>(); VisitorControlHandler.CompletionCode completionCode = VisitorControlHandler.CompletionCode.SUCCESS; int buckets...
class OperationHandlerImplFixture { DocumentAccess documentAccess = mock(DocumentAccess.class); AtomicReference<VisitorParameters> assignedParameters = new AtomicReference<>(); VisitorControlHandler.CompletionCode completionCode = VisitorControlHandler.CompletionCode.SUCCESS; int buckets...
Created issue #31678 to track above.
public static Optional<Symbol> getDocumentableSymbol(NonTerminalNode node, SemanticModel semanticModel) { switch (node.kind()) { case FUNCTION_DEFINITION: case OBJECT_METHOD_DEFINITION: case RESOURCE_ACCESSOR_DEFINITION: case METHOD_DECLARATION: case S...
public static Optional<Symbol> getDocumentableSymbol(NonTerminalNode node, SemanticModel semanticModel) { switch (node.kind()) { case FUNCTION_DEFINITION: case OBJECT_METHOD_DEFINITION: case RESOURCE_ACCESSOR_DEFINITION: case METHOD_DECLARATION: case S...
class DocumentationGenerator { private DocumentationGenerator() { } /** * Checks whether the node has documentation. * * @param node documentatable {@link NonTerminalNode} * @return returns True if has documentation False otherwise */ public static boolean hasDocs(NonTerminalN...
class DocumentationGenerator { private DocumentationGenerator() { } /** * Checks whether the node has documentation. * * @param node documentatable {@link NonTerminalNode} * @return returns True if has documentation False otherwise */ public static boolean hasDocs(NonTerminalN...
http and Listener should move to constants.
void invokeFilters(BLangResource resourceNode, SymbolEnv env) { if (resourceNode.requiredParams.size() == 2 && "http".equals(resourceNode.requiredParams.get( 0).type.tsymbol.pkgID.name.value) && "Listener".equals(resourceNode.requiredParams.get( 0).type.tsymbol.name.value)) { ...
if (resourceNode.requiredParams.size() == 2 && "http".equals(resourceNode.requiredParams.get(
void invokeFilters(BLangResource resourceNode, SymbolEnv env) { BLangVariable endpoint; if (resourceNode.requiredParams.size() == 2) { endpoint = resourceNode.requiredParams.get(0); if (ORG_NAME.equals(endpoint.type.tsymbol.pkgID.orgName.value) && PACKAGE_NAME.equals( ...
class HttpFiltersDesugar { private final SymbolTable symTable; private final SymbolResolver symResolver; private final Names names; private static final String HTTP_CONNECTION_VAR = "conn"; private static final String HTTP_ENDPOINT_CONFIG = "config"; private static final String HTTP_FILTERS_VA...
class HttpFiltersDesugar { private final SymbolTable symTable; private final SymbolResolver symResolver; private final Names names; private static final String HTTP_CONNECTION_VAR = "conn"; private static final String HTTP_ENDPOINT_CONFIG = "config"; private static final String HTTP_FILTERS_VA...
In the current state of the PR, `-r` is no longer valid.
public void testClaimRestoreModeParsing() throws Exception { String[] parameters = { "-s", "expectedSavepointPath", "-n", "-r", "claim", getTestJarPath() }; CommandLine commandLine = CliFrontendParser.parse(CliFrontendParser.RUN_OPTIONS, parameters, true); ...
"-s", "expectedSavepointPath", "-n", "-r", "claim", getTestJarPath()
public void testClaimRestoreModeParsing() throws Exception { String[] parameters = { "-s", "expectedSavepointPath", "-n", "-restoreMode", "claim", getTestJarPath() }; CommandLine commandLine = CliFrontendParser.parse(CliFrontendParser.RUN_OPTIONS, parameters...
class CliFrontendRunTest extends CliFrontendTestBase { @BeforeClass public static void init() { CliFrontendTestUtils.pipeSystemOutToNull(); } @AfterClass public static void shutdown() { CliFrontendTestUtils.restoreSystemOut(); } @Test public void testRun() throws Excep...
class CliFrontendRunTest extends CliFrontendTestBase { @BeforeClass public static void init() { CliFrontendTestUtils.pipeSystemOutToNull(); } @AfterClass public static void shutdown() { CliFrontendTestUtils.restoreSystemOut(); } @Test public void testRun() throws Excep...
Why do we need to call clear here?
public void init() throws IOException { resultPath = tempFolder().newFolder().toURI().toString(); clear(); env().setParallelism(3); env().enableCheckpointing(100); rows = new ArrayList<>(); for (int i = 0; i < 100; i++) { rows.add(Row.of(i, String.valueOf(i % 10), String.valueOf(i))); } DataStream...
clear();
public void init() throws IOException { resultPath = tempFolder().newFolder().toURI().toString(); env().setParallelism(3); env().enableCheckpointing(100); List<Row> rows = new ArrayList<>(); for (int i = 0; i < 100; i++) { rows.add(Row.of(i, String.valueOf(i % 10), String.valueOf(i))); } this.expect...
class FileCompactionITCaseBase extends StreamingTestBase { @Rule public Timeout timeoutPerTest = Timeout.seconds(60); private String resultPath; private List<Row> rows; @Before @After public void clear() throws IOException { FileUtils.deleteDirectory(new File(URI.create(resultPath))); } protected abs...
class FileCompactionITCaseBase extends StreamingTestBase { @Rule public Timeout timeoutPerTest = Timeout.seconds(60); private String resultPath; private List<Row> expectedRows; @Before protected abstract String format(); @Test public void testNonPartition() throws Exception { tEnv().executeSql("CREATE...
how about : ``` assertThat(configuration.keySet()).containsExactly(expectedKey); ```
void testDelegationConfigurationWithPrefix() { String prefix = "pref-"; String expectedKey = "key"; /* * Key matches the prefix */ Configuration backingConf = new Configuration(); backingConf.setValueInternal(prefix + expectedKey, "value", false); Dele...
assertThat(expectedKey).isEqualTo(keySet.iterator().next());
void testDelegationConfigurationWithPrefix() { String prefix = "pref-"; String expectedKey = "key"; /* * Key matches the prefix */ Configuration backingConf = new Configuration(); backingConf.setValueInternal(prefix + expectedKey, "value", false); Dele...
class and call it lookForWrapper: for (Method wrapperMethod : delegateMethods) { if (configurationMethod.getName().equals(wrapperMethod.getName())) { Class<?>[] wrapperMethodParams = wrapperMethod.getParameterTypes(); ...
class and call it lookForWrapper: for (Method wrapperMethod : delegateMethods) { if (configurationMethod.getName().equals(wrapperMethod.getName())) { Class<?>[] wrapperMethodParams = wrapperMethod.getParameterTypes(); ...
OK. I didn't notice the `TableProperty`, Thanks for your reminder.
public void readFields(DataInput in) throws IOException { super.readFields(in); this.state = OlapTableState.valueOf(Text.readString(in)); int counter = in.readInt(); for (int i = 0; i < counter; i++) { String indexName = Text.readString(in); long indexI...
isInMemory = in.readBoolean();
public void readFields(DataInput in) throws IOException { super.readFields(in); this.state = OlapTableState.valueOf(Text.readString(in)); int counter = in.readInt(); for (int i = 0; i < counter; i++) { String indexName = Text.readString(in); long indexI...
class OlapTable extends Table { private static final Logger LOG = LogManager.getLogger(OlapTable.class); public enum OlapTableState { NORMAL, ROLLUP, SCHEMA_CHANGE, @Deprecated BACKUP, RESTORE, RESTORE_WITH_LOAD } private OlapTableState state; ...
class OlapTable extends Table { private static final Logger LOG = LogManager.getLogger(OlapTable.class); public enum OlapTableState { NORMAL, ROLLUP, SCHEMA_CHANGE, @Deprecated BACKUP, RESTORE, RESTORE_WITH_LOAD } private OlapTableState state; ...
`checkRange` and `checkDate` return true is error 😂 https://github.com/apache/doris/blob/881670566c0aa577dd83af69c7b3d9f7a3986ab2/fe/fe-core/src/main/java/org/apache/doris/analysis/DateLiteral.java#L1298
private void init(String s, Type type) throws AnalysisException { try { Preconditions.checkArgument(type.isDateType()); TemporalAccessor dateTime = null; boolean parsed = false; if (!s.contains("-")) { for (DateTimeFormatter format...
if (checkRange() || checkDate()) {
private void init(String s, Type type) throws AnalysisException { try { Preconditions.checkArgument(type.isDateType()); TemporalAccessor dateTime = null; boolean parsed = false; if (!s.contains("-")) { for (DateTimeFormatter format...
class DateLiteral extends LiteralExpr { private static final Logger LOG = LogManager.getLogger(DateLiteral.class); private static final DateLiteral MIN_DATE = new DateLiteral(0000, 1, 1); private static final DateLiteral MAX_DATE = new DateLiteral(9999, 12, 31); private static final DateLiteral MIN_DAT...
class DateLiteral extends LiteralExpr { private static final Logger LOG = LogManager.getLogger(DateLiteral.class); private static final DateLiteral MIN_DATE = new DateLiteral(0000, 1, 1); private static final DateLiteral MAX_DATE = new DateLiteral(9999, 12, 31); private static final DateLiteral MIN_DAT...
It's better to use AdminClient rather KafkaConsumer if we only want to get topic meatdata.
private void tryDelete(AdminClient adminClient, String topic) throws Exception { try { adminClient .deleteTopics(Collections.singleton(topic)) .all() .get(DELETE_TIMEOUT_SECONDS, TimeUnit.SECONDS); try (KafkaConsumer<Void, Void>...
try (KafkaConsumer<Void, Void> consumer = createTempConsumer()) {
private void tryDelete(AdminClient adminClient, String topic) throws Exception { try { adminClient .deleteTopics(Collections.singleton(topic)) .all() .get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); CommonTestUtils.waitUtil( ...
class KafkaTestEnvironmentImpl extends KafkaTestEnvironment { protected static final Logger LOG = LoggerFactory.getLogger(KafkaTestEnvironmentImpl.class); private static final String ZOOKEEPER_HOSTNAME = "zookeeper"; private static final int ZOOKEEPER_PORT = 2181; private final Map<Integer, KafkaCont...
class KafkaTestEnvironmentImpl extends KafkaTestEnvironment { protected static final Logger LOG = LoggerFactory.getLogger(KafkaTestEnvironmentImpl.class); private static final String ZOOKEEPER_HOSTNAME = "zookeeper"; private static final int ZOOKEEPER_PORT = 2181; private final Map<Integer, KafkaCont...
Hm... Here we aren't storing the references, just using them to check and then obtain the bean. So we don't need to close them anywhere, no?
private Object getBeanInstance(Object testInstance, Field field) { Class<?> fieldClass = field.getType(); InstanceHandle<?> instance = Arc.container().instance(fieldClass, getQualifiers(field)); if (!instance.isAvailable()) { throw new IllegalStateException("Invalid use of @MockBean ...
InstanceHandle<?> instance = Arc.container().instance(fieldClass, getQualifiers(field));
private Object getBeanInstance(Object testInstance, Field field) { Class<?> fieldClass = field.getType(); InstanceHandle<?> instance = Arc.container().instance(fieldClass, getQualifiers(field)); if (!instance.isAvailable()) { throw new IllegalStateException("Invalid use of @InjectMoc...
class CreateMockitoMocksCallback implements QuarkusTestBeforeAllCallback { @Override public void beforeAll(Object testInstance) { Class<?> current = testInstance.getClass(); while (current.getSuperclass() != null) { for (Field field : current.getDeclaredFields()) { M...
class CreateMockitoMocksCallback implements QuarkusTestBeforeAllCallback { @Override public void beforeAll(Object testInstance) { Class<?> current = testInstance.getClass(); while (current.getSuperclass() != null) { for (Field field : current.getDeclaredFields()) { I...
I guess we could make this method empty and remove `canceled` variable for this concrete unit test.
public void cancel() { canceled = true; }
canceled = true;
public void cancel() { isRunning = false; }
class MockSource implements SourceFunction<Tuple2<Long, Integer>>, ListCheckpointed<Serializable> { private static final long serialVersionUID = 1; private int maxElements; private int checkpointDelay; private int readDelay; private volatile int count; private volatile long lastCheckpointId = -1; priva...
class MockSource implements SourceFunction<Tuple2<Long, Integer>>, ListCheckpointed<Serializable> { private static final long serialVersionUID = 1; private int maxElements; private int checkpointDelay; private int readDelay; private volatile int count; private volatile long lastCheckpointId = -1; priva...
This should be in a `Teardown` method - we can fail at various points above and then the table won't be deleted.
public void testWriteWithBackoff() throws Exception { String tableName = DatabaseTestHelper.getTestTableName("UT_WRITE_BACKOFF"); DatabaseTestHelper.createTable(dataSource, tableName); Connection connection = dataSource.getConnection(); Statement lockStatement = connection.createStatement(); l...
DatabaseTestHelper.deleteTable(dataSource, tableName);
public void testWriteWithBackoff() throws Exception { String tableName = DatabaseTestHelper.getTestTableName("UT_WRITE_BACKOFF"); DatabaseTestHelper.createTable(dataSource, tableName); Connection connection = dataSource.getConnection(); Statement lockStatement = connection.createStatement(); l...
class JdbcIOTest implements Serializable { private static final Logger LOG = LoggerFactory.getLogger(JdbcIOTest.class); public static final int EXPECTED_ROW_COUNT = 1000; private static NetworkServerControl derbyServer; private static ClientDataSource dataSource; private static int port; private static St...
class JdbcIOTest implements Serializable { private static final Logger LOG = LoggerFactory.getLogger(JdbcIOTest.class); public static final int EXPECTED_ROW_COUNT = 1000; public static final String BACKOFF_TABLE = "UT_WRITE_BACKOFF"; private static NetworkServerControl derbyServer; private static ClientData...
Shouldn't this be done irrespective of whether a user-specified module init exists? The following two scenarios would produce two different sets of errors atm? Case I ```ballerina int i; function __init() { } public function main() { int j = i; } ``` Case II ```ballerina int i; public function main() { int...
public void visit(BLangPackage pkgNode) { if (pkgNode.completedPhases.contains(CompilerPhase.DATAFLOW_ANALYZE)) { return; } List<TopLevelNode> sortedListOfNodes = new ArrayList<>(pkgNode.globalVars); pkgNode.topLevelNodes.forEach(topLevelNode -> { if (!s...
checkForUninitializedGlobalVar(pkgNode.globalVars);
public void visit(BLangPackage pkgNode) { if (pkgNode.completedPhases.contains(CompilerPhase.DATAFLOW_ANALYZE)) { return; } List<TopLevelNode> sortedListOfNodes = new ArrayList<>(pkgNode.globalVars); addModuleInitToSortedNodeList(pkgNode, sortedListOfNodes); ...
class DataflowAnalyzer extends BLangNodeVisitor { private final SymbolResolver symResolver; private final Names names; private SymbolEnv env; private SymbolTable symTable; private BLangDiagnosticLogHelper dlog; private Map<BSymbol, InitStatus> uninitializedVars; private Map<BSymbol, Set<BSy...
class DataflowAnalyzer extends BLangNodeVisitor { private final SymbolResolver symResolver; private final Names names; private SymbolEnv env; private SymbolTable symTable; private BLangDiagnosticLogHelper dlog; private Map<BSymbol, InitStatus> uninitializedVars; private Map<BSymbol, Set<BSy...
Yes. Right now there is nothing to do.
public void applyToConfiguration(Configuration configuration) { hdfsCloudCredential.applyToConfiguration(configuration); addConfigResourcesToConfiguration(configResources, configuration); }
hdfsCloudCredential.applyToConfiguration(configuration);
public void applyToConfiguration(Configuration configuration) { hdfsCloudCredential.applyToConfiguration(configuration); addConfigResourcesToConfiguration(configResources, configuration); }
class HDFSCloudConfiguration implements CloudConfiguration { private static final Logger LOG = LogManager.getLogger(HDFSCloudConfiguration.class); private final HDFSCloudCredential hdfsCloudCredential; private String configResources; private String runtimeJars; private static final String CONFIG_R...
class HDFSCloudConfiguration implements CloudConfiguration { private static final Logger LOG = LogManager.getLogger(HDFSCloudConfiguration.class); private final HDFSCloudCredential hdfsCloudCredential; private String configResources; private String runtimeJars; private static final String CONFIG_R...
I am wondering should we use block() here?
public void createContainerWithComputedProperties() { CosmosContainerProperties containerProperties = getCollectionDefinition(containerName); List<ComputedProperty> computedProperties = new ArrayList<>( Arrays.asList( new ComputedProperty("lowerName", "SE...
database.createContainer(containerProperties).subscribe();
public void createContainerWithComputedProperties() { CosmosContainerProperties containerProperties = getCollectionDefinition(containerName); List<ComputedProperty> computedProperties = new ArrayList<>( Arrays.asList( new ComputedProperty("lowerName", "SE...
class ComputedPropertiesCodeSnippet { private CosmosAsyncClient client; private CosmosAsyncDatabase database; private CosmosAsyncContainer container; private String containerName = "TestContainer"; public ComputedPropertiesCodeSnippet() { this.client = new CosmosClientBuilder() ...
class ComputedPropertiesCodeSnippet { private CosmosAsyncClient client; private CosmosAsyncDatabase database; private CosmosAsyncContainer container; private String containerName = "TestContainer"; public ComputedPropertiesCodeSnippet() { this.client = new CosmosClientBuilder() ...
Agree, the API is not ideal.
private List<Node> performOn(NodeFilter filter, BiFunction<Node, Mutex, Node> action) { List<Node> unallocatedNodes = new ArrayList<>(); ListMap<ApplicationId, Node> allocatedNodes = new ListMap<>(); for (Node node : db.readNodes()) { if ( ! filter.matches(node)) continue; ...
Optional<Node> currentNode = db.readNode(node.hostname());
private List<Node> performOn(NodeFilter filter, BiFunction<Node, Mutex, Node> action) { List<Node> unallocatedNodes = new ArrayList<>(); ListMap<ApplicationId, Node> allocatedNodes = new ListMap<>(); for (Node node : db.readNodes()) { if ( ! filter.matches(node)) continue; ...
class NodeRepository extends AbstractComponent { private static final Logger log = Logger.getLogger(NodeRepository.class.getName()); private final CuratorDatabaseClient db; private final Clock clock; private final Zone zone; private final NodeFlavors flavors; private final HostResourcesCalcula...
class NodeRepository extends AbstractComponent { private static final Logger log = Logger.getLogger(NodeRepository.class.getName()); private final CuratorDatabaseClient db; private final Clock clock; private final Zone zone; private final NodeFlavors flavors; private final HostResourcesCalcula...
The most risky bug in this code is: Exposing sensitive information through accessors You can modify the code like this: ```java // It's not recommended to provide public getters for sensitive information like access keys and secret keys. // If you need to provide read access to this data, rethink your design to ensure...
public void applyToConfiguration(Configuration configuration) { configuration.set("fs.oss.impl", "com.aliyun.jindodata.oss.JindoOssFileSystem"); configuration.set("fs.AbstractFileSystem.oss.impl", "com.aliyun.jindodata.oss.OSS"); configuration.set("fs.oss.accessKeyId", accessKey); config...
configuration.set("fs.oss.impl", "com.aliyun.jindodata.oss.JindoOssFileSystem");
public void applyToConfiguration(Configuration configuration) { configuration.set("fs.oss.impl", "com.aliyun.jindodata.oss.JindoOssFileSystem"); configuration.set("fs.AbstractFileSystem.oss.impl", "com.aliyun.jindodata.oss.OSS"); configuration.set("fs.oss.accessKeyId", accessKey); config...
class AliyunCloudCredential implements CloudCredential { private final String accessKey; private final String secretKey; private final String endpoint; public AliyunCloudCredential(String accessKey, String secretKey, String endpoint) { Preconditions.checkNotNull(accessKey); Preconditio...
class AliyunCloudCredential implements CloudCredential { private final String accessKey; private final String secretKey; private final String endpoint; public AliyunCloudCredential(String accessKey, String secretKey, String endpoint) { Preconditions.checkNotNull(accessKey); Preconditio...
I think it's better to assign aliases: `SELECT 1 AS x, '1' AS y ...` so that in unlikely case Calcite changes the convention of calling these `EXPR$..` the test doesn't break
public void testValues_selectEmpty() throws Exception { String sql = "select 1, '1' FROM string_table WHERE false"; PCollection<Row> rows = compilePipeline(sql, pipeline); PAssert.that(rows) .containsInAnyOrder( TestUtils.RowsBuilder.of( Schema.FieldType.INT32, "EXPR$...
String sql = "select 1, '1' FROM string_table WHERE false";
public void testValues_selectEmpty() throws Exception { String sql = "select 1, '1' FROM string_table WHERE false"; PCollection<Row> rows = compilePipeline(sql, pipeline); PAssert.that(rows) .containsInAnyOrder( TestUtils.RowsBuilder.of( Schema.FieldType.INT32, "EXPR$...
class BeamValuesRelTest extends BaseRelTest { @Rule public final TestPipeline pipeline = TestPipeline.create(); @BeforeClass public static void prepare() { registerTable( "string_table", TestBoundedTable.of( Schema.FieldType.STRING, "name", Schema.FieldType.STRING, "de...
class BeamValuesRelTest extends BaseRelTest { @Rule public final TestPipeline pipeline = TestPipeline.create(); @BeforeClass public static void prepare() { registerTable( "string_table", TestBoundedTable.of( Schema.FieldType.STRING, "name", Schema.FieldType.STRING, "de...
I was thinking of when we have to renew multiple lock Token in one go and need to expose that API, this would be helpful. But for now I have changed this like you said.
private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); ...
return message;
private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); ...
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedName...
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedName...
And did you test it? Whether `DefaultOidcUser` serialize / deserialize well?
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { OidcUser oidcUser = oidcUserService.loadUser(userRequest); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { Defa...
DefaultOidcUser defaultOidcUser = (DefaultOidcUser) session.getAttribute("defaultOidcUser");
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { OidcUser oidcUser = oidcUserService.loadUser(userRequest); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); ServletRequestAttributes attr = (ServletRequest...
class AzureActiveDirectoryOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> { private final OidcUserService oidcUserService; private final AADAuthenticationProperties properties; private final GraphClient graphClient; @Autowired private HttpSession session; public Azur...
class AzureActiveDirectoryOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> { private final OidcUserService oidcUserService; private final AADAuthenticationProperties properties; private final GraphClient graphClient; private static final String DEFAULT_OIDC_USER = "defaultOidcU...
This line can be removed if you pass the default client as suggested above.
private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addA...
HttpClient client = httpClient != null ? httpClient : HttpClient.createDefault();
private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addA...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options;...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options;...
Why do we have to add this code block? Shouldn't this implicitly be asserted if the jobs finishes successfully?
public void testDispatcherProcessFailure() throws Exception { final Time timeout = Time.seconds(30L); final File zookeeperStoragePath = temporaryFolder.newFolder(); final int numberOfJobManagers = 2; final int numberOfTaskManagers = 2; final int numberOfSlotsPerTaskManager = 2; assertEquals(PARALLELISM...
waitForTaskManagers(numberOfTaskManagers, newDispatcherGateway, deadline.timeLeft());
public void testDispatcherProcessFailure() throws Exception { final Time timeout = Time.seconds(30L); final File zookeeperStoragePath = temporaryFolder.newFolder(); final int numberOfJobManagers = 2; final int numberOfTaskManagers = 2; final int numberOfSlotsPerTaskManager = 2; assertEquals(PARALLELISM...
class JobManagerHAProcessFailureRecoveryITCase extends TestLogger { private static ZooKeeperTestEnvironment zooKeeper; private static final FiniteDuration TestTimeOut = new FiniteDuration(5, TimeUnit.MINUTES); @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); @BeforeClass public stat...
class JobManagerHAProcessFailureRecoveryITCase extends TestLogger { private static ZooKeeperTestEnvironment zooKeeper; private static final FiniteDuration TestTimeOut = new FiniteDuration(5, TimeUnit.MINUTES); @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); @BeforeClass public stat...
I see 2 paths above for assigning to `from`: ``` String from = String.format("%s/v%s/%s.zip", GITHUB_DOWNLOAD_PREFIX, getSDKVersion(), buildFileName()); if (!Strings.isNullOrEmpty(options.getPrismLocation())) { checkArgument( !options.getPrismLocation().startsWith(GITHUB_TAG_PREFIX), ...
String resolve() throws IOException { String from = String.format("%s/v%s/%s.zip", GITHUB_DOWNLOAD_PREFIX, getSDKVersion(), buildFileName()); if (!Strings.isNullOrEmpty(options.getPrismLocation())) { checkArgument( !options.getPrismLocation().startsWith(GITHUB_TAG_PREFIX), "P...
if (from.startsWith("http")) {
String resolve() throws IOException { String from = String.format("%s/v%s/%s.zip", GITHUB_DOWNLOAD_PREFIX, getSDKVersion(), buildFileName()); if (!Strings.isNullOrEmpty(options.getPrismLocation())) { checkArgument( !options.getPrismLocation().startsWith(GITHUB_TAG_PREFIX), "P...
class PrismLocator { static final String OS_NAME_PROPERTY = "os.name"; static final String ARCH_PROPERTY = "os.arch"; static final String USER_HOME_PROPERTY = "user.home"; private static final String ZIP_EXT = "zip"; private static final String SHA512_EXT = "sha512"; private static final ReleaseInfo RELEAS...
class PrismLocator { static final String OS_NAME_PROPERTY = "os.name"; static final String ARCH_PROPERTY = "os.arch"; static final String USER_HOME_PROPERTY = "user.home"; private static final String ZIP_EXT = "zip"; private static final ReleaseInfo RELEASE_INFO = ReleaseInfo.getReleaseInfo(); private stat...
Yeah, agree, will fix in a forthcoming PR
private String inProgressOutput(JsonNode hosts) { ArrayList<String> statusPerHost = new ArrayList<>(); for (JsonNode host : hosts) { StringBuilder sb = new StringBuilder(); String status = host.get("status").asText(); sb.append(host.get("hostname").asText()).append(":...
else if (status.equals(statusInProgress)) {
private String inProgressOutput(JsonNode hosts) { ArrayList<String> statusPerHost = new ArrayList<>(); for (JsonNode host : hosts) { StringBuilder sb = new StringBuilder(); String status = host.get("status").asText(); sb.append(host.get("hostname").asText()).append(":...
class FileDistributionStatusClient { private static final String statusUnknown = "UNKNOWN"; private static final String statusInProgress = "IN_PROGRESS"; private static final String statusFinished = "FINISHED"; private final String tenantName; private final String applicationName; private fin...
class FileDistributionStatusClient { private static final String statusUnknown = "UNKNOWN"; private static final String statusInProgress = "IN_PROGRESS"; private static final String statusFinished = "FINISHED"; private final String tenantName; private final String applicationName; private fin...
Same with this one. I'm not sure if Yijun fixed this too.
public ServiceBusReceiverAsyncClient buildAsyncClient() { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, ...
validateAndThrow(prefetchCount);
public ServiceBusReceiverAsyncClient buildAsyncClient() { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName, ...
class ServiceBusSessionReceiverClientBuilder { private Integer maxConcurrentSessions = null; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String sessionId; private String su...
class ServiceBusSessionReceiverClientBuilder { private Integer maxConcurrentSessions = null; private int prefetchCount = DEFAULT_PREFETCH_COUNT; private String queueName; private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK; private String sessionId; private String su...
Can we verify that the group doesn't include range deletes, and throw an exception if it does?
public static long countOf(SpannerSchema spannerSchema, MutationGroup mutationGroup) { long mutatedCells = 0L; for (Mutation mutation : mutationGroup) { if (mutation.getOperation() != Op.DELETE) { for (String column : mutation.getColumns()) { mutatedCells += spannerSchema.getCel...
public static long countOf(SpannerSchema spannerSchema, MutationGroup mutationGroup) { long mutatedCells = 0L; for (Mutation mutation : mutationGroup) { if (mutation.getOperation() == Op.DELETE) { if (isPointDelete(mutation)) { final KeySet keySet = mutation.getKeySet()...
class MutationCellCounter { private MutationCellCounter() { } /** * Count the number of cells modified by {@link MutationGroup}. */ }
class MutationCellCounter { private MutationCellCounter() { } /** * Count the number of cells modified by {@link MutationGroup}. */ }
But, if we keep it in a constant, the error will be initialised even if there's no error. Wouldn't that be unnecessary?
public static long abs(long n) { if (n <= Long.MIN_VALUE) { throw ErrorCreator.createError(getModulePrefixedReason(INT_LANG_LIB, BallerinaErrorReasons.NUMBER_OVERFLOW_ERROR_IDENTIFIER), BLangExceptionHelper.getErrorDetails(RuntimeErrors.INT_RANGE_OVERF...
throw ErrorCreator.createError(getModulePrefixedReason(INT_LANG_LIB,
public static long abs(long n) { if (n <= Long.MIN_VALUE) { throw ErrorCreator.createError(getModulePrefixedReason(INT_LANG_LIB, BallerinaErrorReasons.NUMBER_OVERFLOW_ERROR_IDENTIFIER), BLangExceptionHelper.getErrorDetails(RuntimeErrors.INT_RANGE_OVERF...
class Abs { }
class Abs { }
@menghaoranss Why not init workerId in `init` method?
private long getWorkerId() { if (null == instanceContext) { return DEFAULT_WORKER_ID; } long result = instanceContext.getWorkerId(); Preconditions.checkArgument(result >= 0L && result < WORKER_ID_MAX_VALUE, "Illegal worker id."); return result; }
long result = instanceContext.getWorkerId();
private long getWorkerId() { if (null == instanceContext) { return DEFAULT_WORKER_ID; } long result = instanceContext.getWorkerId(); Preconditions.checkArgument(result >= 0L && result < WORKER_ID_MAX_VALUE, "Illegal worker id."); return result; }
class SnowflakeKeyGenerateAlgorithm implements KeyGenerateAlgorithm, ShardingSphereInstanceRequiredAlgorithm { public static final long EPOCH; private static final String MAX_VIBRATION_OFFSET_KEY = "max-vibration-offset"; private static final String MAX_TOLERATE_TIME_DIFFERENCE_MILLISECONDS_K...
class SnowflakeKeyGenerateAlgorithm implements KeyGenerateAlgorithm, ShardingSphereInstanceRequiredAlgorithm { public static final long EPOCH; private static final String MAX_VIBRATION_OFFSET_KEY = "max-vibration-offset"; private static final String MAX_TOLERATE_TIME_DIFFERENCE_MILLISECONDS_K...