focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static void validate(TableConfig tableConfig, @Nullable Schema schema) { validate(tableConfig, schema, null); }
@Test public void validateTimeColumnValidationConfig() { // REALTIME table // null timeColumnName and schema TableConfig tableConfig = new TableConfigBuilder(TableType.REALTIME).setTableName(TABLE_NAME).build(); try { TableConfigUtils.validate(tableConfig, null); Assert.fail("Should fail ...
public static void checkTdg(String tenant, String dataId, String group) throws NacosException { checkTenant(tenant); if (StringUtils.isBlank(dataId) || !ParamUtils.isValid(dataId)) { throw new NacosException(NacosException.CLIENT_INVALID_PARAM, DATAID_INVALID_MSG); } if (Stri...
@Test void testCheckTdgFail2() throws NacosException { Throwable exception = assertThrows(NacosException.class, () -> { String tenant = "a"; String dataId = "b"; String group = ""; ParamUtils.checkTdg(tenant, dataId, group); }); as...
public RunResponse start( @NotNull String workflowId, @NotNull String version, @NotNull RunRequest runRequest) { WorkflowDefinition definition = workflowDao.getWorkflowDefinition(workflowId, version); validateRequest(version, definition, runRequest); RunProperties runProperties = RunProperti...
@Test public void testStartDuplicated() { when(runStrategyDao.startWithRunStrategy(any(), any())).thenReturn(0); RunRequest request = RunRequest.builder() .initiator(new ManualInitiator()) .requestId(UUID.fromString("41f0281e-41a2-468d-b830-56141b2f768b")) .currentP...
void reset(PartitionReplica localReplica) { assert localReplica != null; this.replicas = new PartitionReplica[MAX_REPLICA_COUNT]; this.localReplica = localReplica; version = 0; resetMigrating(); }
@Test public void testReset() { for (int i = 0; i < MAX_REPLICA_COUNT; i++) { replicaOwners[i] = new PartitionReplica(newAddress(5000 + i), UuidUtil.newUnsecureUUID()); } partition.setReplicas(replicaOwners); partition.reset(localReplica); for (int i = 0; i < MAX...
@Override public void dropFunction(QualifiedObjectName functionName, Optional<List<TypeSignature>> parameterTypes, boolean exists) { checkCatalog(functionName); jdbi.useTransaction(handle -> { FunctionNamespaceDao transactionDao = handle.attach(functionNamespaceDaoClass); ...
@Test public void testDropFunction() { // Create functions createFunction(FUNCTION_POWER_TOWER_DOUBLE, false); createFunction(FUNCTION_POWER_TOWER_INT, false); createFunction(FUNCTION_TANGENT, false); // Drop function by name dropFunction(TANGENT, Optional.empty(...
@InvokeOnHeader(Web3jConstants.ETH_GET_BLOCK_TRANSACTION_COUNT_BY_NUMBER) void ethGetBlockTransactionCountByNumber(Message message) throws IOException { DefaultBlockParameter atBlock = toDefaultBlockParameter(message.getHeader(Web3jConstants.AT_BLOCK, configuration::getAtBlock, String.class)...
@Test public void ethGetBlockTransactionCountByNumberTest() throws Exception { EthGetBlockTransactionCountByNumber response = Mockito.mock(EthGetBlockTransactionCountByNumber.class); Mockito.when(mockWeb3j.ethGetBlockTransactionCountByNumber(any())).thenReturn(request); Mockito.when(request....
@Override public void loadConfiguration(NacosLoggingProperties loggingProperties) { String location = loggingProperties.getLocation(); configurator.setLoggingProperties(loggingProperties); LoggerContext loggerContext = loadConfigurationOnStart(location); if (hasNoListener(loggerConte...
@Test void testLoadConfigurationStart() { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.putObject(CoreConstants.RECONFIGURE_ON_CHANGE_TASK, new ReconfigureOnChangeTask()); logbackNacosLoggingAdapter.loadConfiguration(loggingProperties); ...
Object getFromForeach(String foreachStepId, String stepId, String paramName) { try { return executor .submit(() -> fromForeach(foreachStepId, stepId, paramName)) .get(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS); } catch (Exception e) { throw new MaestroInternalError( e, ...
@Test public void testInvalidGetFromForeach() throws Exception { AssertHelper.assertThrows( "Cannot find the referenced step id", MaestroInternalError.class, "getFromForeach throws an exception", () -> paramExtension.getFromForeach("non-existing-job", "job1", "sleep_seconds")); ...
@SuppressWarnings("deprecation") @Override public Integer call() throws Exception { super.call(); try (var files = Files.walk(directory)) { List<String> flows = files .filter(Files::isRegularFile) .filter(YamlFlowParser::isValidExtension) ...
@Test void runNoDelete() { URL directory = FlowNamespaceUpdateCommandTest.class.getClassLoader().getResource("flows"); URL subDirectory = FlowNamespaceUpdateCommandTest.class.getClassLoader().getResource("flows/flowsSubFolder"); ByteArrayOutputStream out = new ByteArrayOutputStream(); ...
protected boolean isJob( HttpServletRequest request ) { return isJob( request.getParameter( PARAMETER_TYPE ) ); }
@Test public void testIsJobHttpServletRequest() { // CASE: job HttpServletRequest requestJob = Mockito.mock( HttpServletRequest.class ); when(requestJob.getParameter( RegisterPackageServlet.PARAMETER_TYPE ) ).thenReturn( "job" ); assertTrue( servlet.isJob( requestJob ) ); // CASE: transformati...
@Override public CommandLineImpl parse(final List<String> originalArgs, final Logger logger) { return CommandLineImpl.of(originalArgs, logger); }
@Test public void testHelp() throws Exception { final CommandLineParserImpl parser = new CommandLineParserImpl(); final CommandLineImpl commandLine = parse(parser, "-h"); assertEquals(Command.NONE, commandLine.getCommand()); assertEquals( "Usage: embulk [common opti...
public static void checkArgument(boolean expression, Object errorMessage) { if (Objects.isNull(errorMessage)) { throw new IllegalArgumentException("errorMessage cannot be null."); } if (!expression) { throw new IllegalArgumentException(String.valueOf(errorMessage)); ...
@Test void testCheckArgument3Args1false() { assertThrows(IllegalArgumentException.class, () -> { Preconditions.checkArgument(false, ERRORMSG, ARG); }); }
@Override public boolean isWritable() { return false; }
@Test public void shouldIndicateNotWritable() { assertFalse(unmodifiableBuffer(buffer(1)).isWritable()); }
public PackageDefinition find(final String id) { return stream().filter(packageDefinition -> packageDefinition.getId().equals(id)).findFirst().orElse(null); }
@Test public void shouldFindPackageGivenThePkgId() throws Exception { PackageRepository repository = PackageRepositoryMother.create("repo-id2", "repo2", "plugin-id", "1.0", null); PackageDefinition p1 = PackageDefinitionMother.create("id1", "pkg1", null, repository); PackageDefinition p2 = P...
public static RandomProjection sparse(int n, int p, String... columns) { if (n < 2) { throw new IllegalArgumentException("Invalid dimension of input space: " + n); } if (p < 1 || p > n) { throw new IllegalArgumentException("Invalid dimension of feature space: " + p); ...
@Test public void testSparseRandomProjection() { System.out.println("sparse random projection"); RandomProjection instance = RandomProjection.sparse(128, 40); Matrix p = instance.projection; System.out.println(p.toString(true)); }
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .nullable(column.isNullable()) .comment(column.getComment()) ...
@Test public void testReconvertString() { Column column = PhysicalColumn.builder() .name("test") .dataType(BasicType.STRING_TYPE) .columnLength(null) .build(); BasicTypeDefine typeDefine ...
public void listenToUris(String clusterName) { // if cluster name is a symlink, watch for D2SymlinkNode instead String resourceName = D2_URI_NODE_PREFIX + clusterName; if (SymlinkUtil.isSymlinkNodeOrPath(clusterName)) { listenToSymlink(clusterName, resourceName); } else { _watc...
@Test public void testListenToUriSymlink() throws PropertySerializationException { XdsToD2PropertiesAdaptorFixture fixture = new XdsToD2PropertiesAdaptorFixture(); fixture.getSpiedAdaptor().listenToUris(SYMLINK_NAME); // verify symlink is watched verify(fixture._xdsClient).watchXdsResource(eq(URI_S...
public GoPluginBundleDescriptor build(BundleOrPluginFileDetails bundleOrPluginJarFile) { if (!bundleOrPluginJarFile.exists()) { throw new RuntimeException(format("Plugin or bundle jar does not exist: %s", bundleOrPluginJarFile.file())); } String defaultId = bundleOrPluginJarFile.fil...
@Test void shouldCreateThePluginDescriptorFromGivenPluginJarWithPluginXML() throws Exception { String pluginJarName = "descriptor-aware-test-plugin.jar"; copyPluginToThePluginDirectory(pluginDirectory, pluginJarName); File pluginJarFile = new File(pluginDirectory, pluginJarName); Bun...
@Override public Map<String, String> contextLabels() { return Collections.unmodifiableMap(contextLabels); }
@Test public void testCreationWithValidNamespaceAndNullLabelValues() { labels.put(LABEL_A_KEY, null); context = new KafkaMetricsContext(namespace, labels); assertEquals(2, context.contextLabels().size()); assertEquals(namespace, context.contextLabels().get(MetricsContext.NAMESPACE))...
@Override public Progress getProgress() { BigDecimal end; if (range.getTo().compareTo(Timestamp.MAX_VALUE) == 0) { // When the given end timestamp equals to Timestamp.MAX_VALUE, this means that // the end timestamp is not specified which should be a streaming job. So we // use now() as the e...
@Test public void testGetProgressReturnsWorkRemainingAsWholeRangeWhenNoClaimWasAttempted() { final Timestamp from = Timestamp.ofTimeSecondsAndNanos(0, 0); final Timestamp to = Timestamp.now(); final TimestampRange range = TimestampRange.of(from, to); final TimestampRangeTracker tracker = new Timestamp...
@RequestMapping("/admin") public List<ServiceDTO> getAdminService() { return discoveryService.getServiceInstances(ServiceNameConsts.APOLLO_ADMINSERVICE); }
@Test public void testGetAdminService() { when(discoveryService.getServiceInstances(ServiceNameConsts.APOLLO_ADMINSERVICE)) .thenReturn(someServices); assertEquals(someServices, serviceController.getAdminService()); }
@Override public GetQueueUserAclsInfoResponse getQueueUserAcls( GetQueueUserAclsInfoRequest request) throws YarnException, IOException { if(request == null){ routerMetrics.incrQueueUserAclsFailedRetrieved(); String msg = "Missing getQueueUserAcls request."; RouterAuditLogger.logFailure(use...
@Test public void testGetQueueUserAcls() throws Exception { LOG.info("Test FederationClientInterceptor : Get QueueUserAcls request."); // null request LambdaTestUtils.intercept(YarnException.class, "Missing getQueueUserAcls request.", () -> interceptor.getQueueUserAcls(null)); // normal requ...
boolean isMethodCorrect(ResolvedMethod m) { if (m.getReturnType()!=null) { log.error("The method {} is annotated with @SelfValidation but does not return void. It is ignored", m.getRawMember()); return false; } else if (m.getArgumentCount() != 1 || !m.getArgumentType(0).getErased...
@Test @SuppressWarnings("Slf4jFormatShouldBeConst") void privateIsNotAccepted() throws NoSuchMethodException { assertThat(selfValidatingValidator.isMethodCorrect( getMethod("validateFailPrivate", ViolationCollector.class))) .isFalse(); verify(log).error("The meth...
public static boolean isValid(final String identifier) { final SqlBaseLexer sqlBaseLexer = new SqlBaseLexer( new CaseInsensitiveStream(CharStreams.fromString(identifier))); final CommonTokenStream tokenStream = new CommonTokenStream(sqlBaseLexer); final SqlBaseParser sqlBaseParser = new SqlBaseParse...
@Test public void shouldBeValid() { // Given: final String[] identifiers = new String[]{ "FOO", // nothing special "foo", // lower-case }; // Then: for (final String identifier : identifiers) { assertThat( "Expected " + identifier + " to be valid.", I...
public static NamenodeRole convert(NamenodeRoleProto role) { switch (role) { case NAMENODE: return NamenodeRole.NAMENODE; case BACKUP: return NamenodeRole.BACKUP; case CHECKPOINT: return NamenodeRole.CHECKPOINT; } return null; }
@Test public void testConvertBlockWithLocations() { boolean[] testSuite = new boolean[]{false, true}; for (int i = 0; i < testSuite.length; i++) { BlockWithLocations locs = getBlockWithLocations(1, testSuite[i]); BlockWithLocationsProto locsProto = PBHelper.convert(locs); BlockWithLocations ...
public static Map<String, Map<String, String>> loadAttributes( Node attributesNode ) { Map<String, Map<String, String>> attributesMap = new HashMap<>(); if ( attributesNode != null ) { List<Node> groupNodes = XMLHandler.getNodes( attributesNode, XML_TAG_GROUP ); for ( Node groupNode : groupNodes ) ...
@Test public void testLoadAttributes_NullParameter() { try ( MockedStatic<AttributesUtil> attributesUtilMockedStatic = mockStatic( AttributesUtil.class ) ) { attributesUtilMockedStatic.when( () -> AttributesUtil.loadAttributes( any( Node.class ) ) ).thenCallRealMethod(); Map<String, Map<String, String...
@Override public Response addToClusterNodeLabels(NodeLabelsInfo newNodeLabels, HttpServletRequest hsr) throws Exception { if (newNodeLabels == null) { routerMetrics.incrAddToClusterNodeLabelsFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), ADD_TO_CLUSTER_NODELABELS,...
@Test public void testAddToClusterNodeLabels2() throws Exception { // In this test, we try to add A0 label, // subCluster0 will return success, and other subClusters will return null NodeLabelsInfo nodeLabelsInfo = new NodeLabelsInfo(); NodeLabelInfo nodeLabelInfo = new NodeLabelInfo("A0", true); ...
public JmxCollector register() { return register(PrometheusRegistry.defaultRegistry); }
@Test public void testDelayedStartReady() throws Exception { // TODO register calls the collector, which is in start delay seconds, need to understand // how to handle JmxCollector jc = new JmxCollector("---\nstartDelaySeconds: 1"); Thread.sleep(2000); jc.register(prometheusR...
public <T> OutputSampler<T> sampleOutput(String pcollectionId, Coder<T> coder) { return (OutputSampler<T>) outputSamplers.computeIfAbsent( pcollectionId, k -> new OutputSampler<>( coder, this.maxSamples, this.sampleEveryN, this.onlySampleExceptions...
@Test public void testMultipleSamePCollections() throws Exception { DataSampler sampler = new DataSampler(); VarIntCoder coder = VarIntCoder.of(); sampler.sampleOutput("pcollection-id", coder).sample(globalWindowedValue(1)); sampler.sampleOutput("pcollection-id", coder).sample(globalWindowedValue(2))...
public static Future<Integer> authTlsHash(SecretOperator secretOperations, String namespace, KafkaClientAuthentication auth, List<CertSecretSource> certSecretSources) { Future<Integer> tlsFuture; if (certSecretSources == null || certSecretSources.isEmpty()) { tlsFuture = Future.succeededFutu...
@Test void getHashFailure() { String namespace = "ns"; GenericSecretSource at = new GenericSecretSourceBuilder() .withSecretName("top-secret-at") .withKey("key") .build(); GenericSecretSource cs = new GenericSecretSourceBuilder() ...
public Optional<InstantAndValue<T>> getAndSet(MetricKey metricKey, Instant now, T value) { InstantAndValue<T> instantAndValue = new InstantAndValue<>(now, value); InstantAndValue<T> valueOrNull = counters.put(metricKey, instantAndValue); // there wasn't already an entry, so return empty. ...
@Test public void testGetAndSetLong() { LastValueTracker<Long> lastValueTracker = new LastValueTracker<>(); Optional<InstantAndValue<Long>> result = lastValueTracker.getAndSet(METRIC_NAME, instant1, 1L); assertFalse(result.isPresent()); }
public MutableInodeFile setLength(long length) { mLength = length; return getThis(); }
@Test public void setLength() { MutableInodeFile inodeFile = createInodeFile(1); inodeFile.setLength(LENGTH); assertEquals(LENGTH, inodeFile.getLength()); }
public static boolean isSupportedVersion(final String ksqlServerVersion) { final KsqlVersion version; try { version = new KsqlVersion(ksqlServerVersion); } catch (IllegalArgumentException e) { throw new MigrationException("Could not parse ksqlDB server version to " + "verify compatibil...
@Test public void shouldReturnUnsupportedVersion() { assertThat(isSupportedVersion("v5.5.5"), is(false)); assertThat(isSupportedVersion("v5.4.0"), is(false)); assertThat(isSupportedVersion("v4.0.1"), is(false)); assertThat(isSupportedVersion("v0.9.5"), is(false)); assertThat(isSupportedVersion("v0...
public String getCatalogDbName() { return getCatalog() + "." + getDatabase(); }
@Test public void testGetCatalogDbName() { UserProperty userProperty = new UserProperty(); userProperty.setDatabase("db"); userProperty.setCatalog("catalog"); String name = userProperty.getCatalogDbName(); Assert.assertEquals("catalog.db", name); }
@Override public String localize(final String key, final String table) { final String identifier = String.format("%s.%s", table, key); if(!cache.contains(identifier)) { cache.put(identifier, bundle.localizedString(key, table)); } return cache.get(identifier); }
@Test public void testGet() { assertEquals("Il y a eu un problème lors de la recherche de mises à jour", new BundleLocale().localize("Il y a eu un problème lors de la recherche de mises à jour", "Localizable")); }
public static String getMaskedStatement(final String query) { try { final ParseTree tree = DefaultKsqlParser.getParseTree(query); return new Visitor().visit(tree); } catch (final Exception | StackOverflowError e) { return fallbackMasking(query); } }
@Test public void shouldMaskInvalidCreateStreamWithQuotes() { // Given: // Typo in "WITH" => "WIT" final String query = "CREATE STREAM `stream` (id varchar) WIT ('format' = 'avro', \"kafka_topic\" = 'test_topic', partitions=3);"; // When final String maskedQuery = QueryMask.getMaskedStatement(que...
public boolean hasAccess(Type type, UserGroupInformation ugi) { boolean access = acls.get(type).isUserAllowed(ugi); if (LOG.isDebugEnabled()) { LOG.debug("Checking user [{}] for: {} {} ", ugi.getShortUserName(), type.toString(), acls.get(type).getAclString()); } if (access) { Acces...
@Test public void testCustom() { final Configuration conf = new Configuration(false); for (KMSACLs.Type type : KMSACLs.Type.values()) { conf.set(type.getAclConfigKey(), type.toString() + " "); } final KMSACLs acls = new KMSACLs(conf); for (KMSACLs.Type type : KMSACLs.Type.values()) { A...
public static String getTypeName(final int type) { switch (type) { case START_EVENT_V3: return "Start_v3"; case STOP_EVENT: return "Stop"; case QUERY_EVENT: return "Query"; case ROTATE_EVENT: return "...
@Test public void getTypeNameInputPositiveOutputNotNull2() { // Arrange final int type = 12; // Act final String actual = LogEvent.getTypeName(type); // Assert result Assert.assertEquals("New_load", actual); }
@Override public MapTileList computeFromSource(final MapTileList pSource, final MapTileList pReuse) { final MapTileList out = pReuse != null ? pReuse : new MapTileList(); for (int i = 0; i < pSource.getSize(); i++) { final long sourceIndex = pSource.get(i); final int zoom = M...
@Test public void testOnePointModulo() { final MapTileList source = new MapTileList(); final MapTileList dest = new MapTileList(); final Set<Long> set = new HashSet<>(); final int border = 2; final MapTileListBorderComputer computer = new MapTileListBorderComputer(border, fal...
public Materialization create( final StreamsMaterialization delegate, final MaterializationInfo info, final QueryId queryId, final QueryContext.Stacker contextStacker ) { final TransformVisitor transformVisitor = new TransformVisitor(queryId, contextStacker); final List<Transform> tran...
@Test public void shouldBuildMaterializationWithCorrectParams() { // When: factory.create(materialization, info, queryId, contextStacker); // Then: verify(materializationFactory).create( eq(materialization), eq(TABLE_SCHEMA), any() ); }
public static GenericRecord rewriteRecord(GenericRecord oldRecord, Schema newSchema) { GenericRecord newRecord = new GenericData.Record(newSchema); boolean isSpecificRecord = oldRecord instanceof SpecificRecordBase; for (Schema.Field f : newSchema.getFields()) { if (!(isSpecificRecord && isMetadataFie...
@Test public void testDefaultValueWithSchemaEvolution() { GenericRecord rec = new GenericData.Record(new Schema.Parser().parse(EXAMPLE_SCHEMA)); rec.put("_row_key", "key1"); rec.put("non_pii_col", "val1"); rec.put("pii_col", "val2"); rec.put("timestamp", 3.5); GenericRecord rec1 = HoodieAvroUt...
@Override public String resolve(Method method, Object[] arguments, String spelExpression) { if (StringUtils.isEmpty(spelExpression)) { return spelExpression; } if (spelExpression.matches(PLACEHOLDER_SPEL_REGEX) && stringValueResolver != null) { return stringValueReso...
@Test public void placeholderSpelTest2() throws Exception { String testExpression = "${property:default}"; DefaultSpelResolverTest target = new DefaultSpelResolverTest(); Method testMethod = target.getClass().getMethod("testMethod", String.class); String result = sut.resolve(testMe...
public void mastersStartedCallback() { if (mExclusiveOnlyDeadlineMs == -1) { long exclusiveOnlyDurationMs = Configuration.getMs(PropertyKey.MASTER_BACKUP_STATE_LOCK_EXCLUSIVE_DURATION); mExclusiveOnlyDeadlineMs = System.currentTimeMillis() + exclusiveOnlyDurationMs; if (exclusiveOnlyDura...
@Test public void testExclusiveOnlyMode() throws Throwable { // Configure exclusive-only duration to cover the entire test execution. final long exclusiveOnlyDurationMs = 30 * 1000; Configuration.set(PropertyKey.MASTER_BACKUP_STATE_LOCK_EXCLUSIVE_DURATION, exclusiveOnlyDurationMs); // The sta...
public static <T> Write<T> write(String jdbcUrl, String table) { return new AutoValue_ClickHouseIO_Write.Builder<T>() .jdbcUrl(jdbcUrl) .table(table) .properties(new Properties()) .maxInsertBlockSize(DEFAULT_MAX_INSERT_BLOCK_SIZE) .initialBackoff(DEFAULT_INITIAL_BACKOFF) ...
@Test public void testComplexTupleType() throws Exception { Schema sizeSchema = Schema.of( Schema.Field.of("width", FieldType.INT64.withNullable(true)), Schema.Field.of("height", FieldType.INT64.withNullable(true))); Schema browserSchema = Schema.of( Schema...
@Override public int positionedRead(long position, byte[] buffer, int offset, int length) throws IOException { seek(position); return read(buffer, offset, length); }
@Test public void positionedRead() throws IOException, AlluxioException { AlluxioURI ufsPath = getUfsPath(); createFile(ufsPath, CHUNK_SIZE); try (FileInStream inStream = getStream(ufsPath)) { byte[] res = new byte[CHUNK_SIZE / 2]; assertEquals(CHUNK_SIZE / 2, inStream.positionedRead...
public static URI[] stringToURI(String[] str){ if (str == null) return null; URI[] uris = new URI[str.length]; for (int i = 0; i < str.length;i++){ try{ uris[i] = new URI(str[i]); }catch(URISyntaxException ur){ throw new IllegalArgumentException( "Failed to cre...
@Test (timeout = 30000) public void testStringToURI() { String[] str = new String[] { "file://" }; try { StringUtils.stringToURI(str); fail("Ignoring URISyntaxException while creating URI from string file://"); } catch (IllegalArgumentException iae) { assertEquals("Failed to create uri f...
public Properties getBrokerConfig(final String addr, final long timeoutMillis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException, UnsupportedEncodingException { RemotingCommand request = RemotingCommand.createRequestC...
@Test public void assertGetBrokerConfig() throws RemotingException, InterruptedException, MQBrokerException, UnsupportedEncodingException { mockInvokeSync(); setResponseBody("{\"key\":\"value\"}"); Properties actual = mqClientAPI.getBrokerConfig(defaultBrokerAddr, defaultTimeout); as...
@Override public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) { if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations() && (node.has("minItems") || node.has("maxItems")) && isApplicableType(field)) { ...
@Test public void testMaxAndMinLength() { when(config.isIncludeJsr303Annotations()).thenReturn(true); final int minValue = new Random().nextInt(); final int maxValue = new Random().nextInt(); JsonNode maxSubNode = Mockito.mock(JsonNode.class); when(subNode.asInt()).thenReturn...
@Override public Reader<E> createReader( Configuration config, FSDataInputStream stream, long fileLen, long splitEnd) throws IOException { // current version does not support splitting. checkNotSplit(fileLen, splitEnd); return new AvroParquetRecordReader<E>( ...
@Test void testCreateGenericReaderWithSplitting() { assertThatThrownBy( () -> createReader( AvroParquetReaders.forGenericRecord(schema), new Configuration(), ...
public static OTP generateOTP(byte[] secret, String algo, int digits, long period, long seconds) throws InvalidKeyException, NoSuchAlgorithmException { long counter = (long) Math.floor((double) seconds / period); return HOTP.generateOTP(secret, algo, digits, counter); }
@Test public void vectorsMatch() throws NoSuchAlgorithmException, InvalidKeyException { for (Vector vector : VECTORS) { byte[] seed = getSeed(vector.Algo); OTP otp = TOTP.generateOTP(seed, vector.Algo, 8, 30, vector.Time); assertEquals(vector.OTP, otp.toString()); ...
@Override public void handleTenantInfo(TenantInfoHandler handler) { // 如果禁用,则不执行逻辑 if (isTenantDisable()) { return; } // 获得租户 TenantDO tenant = getTenant(TenantContextHolder.getRequiredTenantId()); // 执行处理器 handler.handle(tenant); }
@Test public void testHandleTenantInfo_success() { // 准备参数 TenantInfoHandler handler = mock(TenantInfoHandler.class); // mock 未禁用 when(tenantProperties.getEnable()).thenReturn(true); // mock 租户 TenantDO dbTenant = randomPojo(TenantDO.class); tenantMapper.inser...
public static CreateSourceProperties from(final Map<String, Literal> literals) { try { return new CreateSourceProperties(literals, DurationParser::parse, false); } catch (final ConfigException e) { final String message = e.getMessage().replace( "configuration", "property" )...
@Test public void shouldFailIfInvalidWindowConfig() { // When: final Exception e = assertThrows( KsqlException.class, () -> CreateSourceProperties.from( ImmutableMap.<String, Literal>builder() .putAll(MINIMUM_VALID_PROPS) .put(WINDOW_TYPE_PROPERTY, n...
@Override public Optional<String> getUrlPathToJs() { return Optional.ofNullable(analytics) .map(WebAnalytics::getUrlPathToJs) .filter(path -> !path.startsWith("/") && !path.contains("..") && !path.contains("://")) .map(path -> "/" + path); }
@Test public void return_empty_if_no_analytics_plugin() { assertThat(new WebAnalyticsLoaderImpl(null).getUrlPathToJs()).isEmpty(); assertThat(new WebAnalyticsLoaderImpl(new WebAnalytics[0]).getUrlPathToJs()).isEmpty(); }
@VisibleForTesting static StreamExecutionEnvironment createStreamExecutionEnvironment(FlinkPipelineOptions options) { return createStreamExecutionEnvironment( options, MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()), options.getFlinkConfDir()); }
@Test public void shouldSetSavepointRestoreForRemoteStreaming() { String path = "fakePath"; FlinkPipelineOptions options = getDefaultPipelineOptions(); options.setRunner(TestFlinkRunner.class); options.setFlinkMaster("host:80"); options.setSavepointPath(path); StreamExecutionEnvironment sev =...
OperationNode createReadOperation( Network<Node, Edge> network, ParallelInstructionNode node, PipelineOptions options, ReaderFactory readerFactory, DataflowExecutionContext<?> executionContext, DataflowOperationContext operationContext) throws Exception { ParallelInstructi...
@Test public void testCreateReadOperation() throws Exception { ParallelInstructionNode instructionNode = ParallelInstructionNode.create(createReadInstruction("Read"), ExecutionLocation.UNKNOWN); when(network.successors(instructionNode)) .thenReturn( ImmutableSet.<Node>of( ...
public void handleStepStatus( MaestroTracingContext tracingContext, StepInstance.Status status, Throwable throwable) { if (tracingContext == null || status == null) { return; } if (StepInstance.Status.CREATED.equals(status)) { start(tracingContext, status.name()); } else if (status.isT...
@Test public void testHandleStepStatus() { MaestroTracingManager tm = new TestTracingManager(mockTracer); int finishCount = 0; for (StepInstance.Status s : StepInstance.Status.values()) { System.out.println("Testing " + s.name()); tm.handleStepStatus(defaultContext, s); verify(mockSpan, ...
@Override public V put(K key, V value, Duration ttl) { return get(putAsync(key, value, ttl)); }
@Test public void testKeySetByPatternTTL() { RMapCacheNative<String, String> map = redisson.getMapCacheNative("simple", StringCodec.INSTANCE); map.put("10", "100"); map.put("20", "200", Duration.ofMinutes(1)); map.put("30", "300"); assertThat(map.keySet("?0")).containsExactl...
@Udf public <T> List<T> slice( @UdfParameter(description = "the input array") final List<T> in, @UdfParameter(description = "start index") final Integer from, @UdfParameter(description = "end index") final Integer to) { if (in == null) { return null; } try { // ...
@Test public void shouldReturnNullOnNullInput() { // Given: final List<String> list = null; // When: final List<String> slice = new Slice().slice(list, 1, 2); // Then: assertThat(slice, nullValue()); }
@Override public boolean isTrusted(Address address) { if (address == null) { return false; } if (trustedInterfaces.isEmpty()) { return true; } String host = address.getHost(); if (matchAnyInterface(host, trustedInterfaces)) { retur...
@Test public void givenInterfaceRangeIsConfigured_whenMessageWithNonMatchingHost_thenDoNotTrust() throws UnknownHostException { AddressCheckerImpl joinMessageTrustChecker = new AddressCheckerImpl(singleton("127.0.0.1-100"), logger); Address address = createAddress("127.0.0.101"); assertFalse...
public List<QueuedCommand> getRestoreCommands(final Duration duration) { if (commandTopicBackup.commandTopicCorruption()) { log.warn("Corruption detected. " + "Use backup to restore command topic."); return Collections.emptyList(); } return getAllCommandsInCommandTopic( command...
@Test public void shouldFilterNullCommandsWhileRestoringCommands() { // Given: when(commandConsumer.poll(any(Duration.class))) .thenReturn(someConsumerRecords( record1, record2, new ConsumerRecord<>("topic", 0, 2, commandId2, null) )); when(commandConsum...
@SuppressWarnings("nullness") @VisibleForTesting public ProcessContinuation run( PartitionMetadata partition, RestrictionTracker<TimestampRange, Timestamp> tracker, OutputReceiver<DataChangeRecord> receiver, ManualWatermarkEstimator<Instant> watermarkEstimator, BundleFinalizer bundleFi...
@Test public void testQueryChangeStreamWithRestrictionFromAfterPartitionStart() { final Struct rowAsStruct = mock(Struct.class); final ChangeStreamResultSetMetadata resultSetMetadata = mock(ChangeStreamResultSetMetadata.class); final ChangeStreamResultSet resultSet = mock(ChangeStreamResultSet.cla...
public static Set<Integer> getIntegerSetOrNull(String property, JsonNode node) { if (!node.has(property) || node.get(property).isNull()) { return null; } return getIntegerSet(property, node); }
@Test public void getIntegerSetOrNull() throws JsonProcessingException { assertThat(JsonUtil.getIntegerSetOrNull("items", JsonUtil.mapper().readTree("{}"))).isNull(); assertThat( JsonUtil.getIntegerSetOrNull("items", JsonUtil.mapper().readTree("{\"items\": null}"))) .isNull(); assert...
@Override public MapperResult findConfigInfoBaseLikeFetchRows(MapperContext context) { final String dataId = (String) context.getWhereParameter(FieldConstant.DATA_ID); final String group = (String) context.getWhereParameter(FieldConstant.GROUP_ID); final String content = (String) context.get...
@Test void testFindConfigInfoBaseLikeFetchRows() { MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoBaseLikeFetchRows(context); assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE 1=1 AND tenant_id='' LIMIT " + s...
@Override public GenericRecordBuilder newRecordBuilder() { return new AvroRecordBuilderImpl(this); }
@Test(expectedExceptions = org.apache.pulsar.client.api.SchemaSerializationException.class) public void testFailDecodeWithoutMultiVersioningSupport() { GenericRecord dataForWriter = writerSchema.newRecordBuilder() .set("field1", SchemaTestUtils.TEST_MULTI_VERSION_SCHEMA_STRING) .set(...
@ApiOperation(value = "Update a user", tags = { "Users" }, notes = "All request values are optional. " + "For example, you can only include the firstName attribute in the request body JSON-object, only updating the firstName of the user, leaving all other fields unaffected. " + "When an attribut...
@Test public void testUpdateUser() throws Exception { User savedUser = null; try { User newUser = identityService.newUser("testuser"); newUser.setFirstName("Fred"); newUser.setLastName("McDonald"); newUser.setEmail("no-reply@flowable.org"); ...
@VisibleForTesting public void setSizeBasedWeight(boolean sizeBasedWeight) { this.sizeBasedWeight = sizeBasedWeight; }
@Test public void testOrderingUsingAppSubmitTime() { FairOrderingPolicy<MockSchedulableEntity> policy = new FairOrderingPolicy<>(); policy.setSizeBasedWeight(true); MockSchedulableEntity r1 = new MockSchedulableEntity(); MockSchedulableEntity r2 = new MockSchedulableEntity(); // R1, R2 ha...
public static <T> Inner<T> create() { return new Inner<>(); }
@Test @Category(NeedsRunner.class) public void addNestedCollectionField() { Schema nested = Schema.builder().addStringField("field1").build(); Schema schema = Schema.builder() .addArrayField("array", Schema.FieldType.row(nested)) .addIterableField("iter", Schema.FieldType.row...
public static SerializableFunction<Row, Mutation> beamRowToMutationFn( Mutation.Op operation, String table) { return (row -> { switch (operation) { case INSERT: return MutationUtils.createMutationFromBeamRows(Mutation.newInsertBuilder(table), row); case DELETE: return...
@Test public void testCreateInsertOrUpdateMutationFromRow() { Mutation expectedMutation = createMutation(Mutation.Op.INSERT_OR_UPDATE); Mutation mutation = beamRowToMutationFn(Mutation.Op.INSERT_OR_UPDATE, TABLE).apply(WRITE_ROW); assertEquals(expectedMutation, mutation); }
public double[][] test(DataFrame data) { DataFrame x = formula.x(data); int n = x.nrow(); int ntrees = trees.length; double[][] prediction = new double[ntrees][n]; for (int j = 0; j < n; j++) { Tuple xj = x.get(j); double base = b; for (int i...
@Test public void testAbaloneLAD() { test(Loss.lad(), "abalone", Abalone.formula, Abalone.train, 2.2958); }
@Override @CacheEvict(cacheNames = RedisKeyConstants.OAUTH_CLIENT, allEntries = true) // allEntries 清空所有缓存,因为可能修改到 clientId 字段,不好清理 public void updateOAuth2Client(OAuth2ClientSaveReqVO updateReqVO) { // 校验存在 validateOAuth2ClientExists(updateReqVO.getId()); // 校验 Client 未被占用 ...
@Test public void testUpdateOAuth2Client_success() { // mock 数据 OAuth2ClientDO dbOAuth2Client = randomPojo(OAuth2ClientDO.class); oauth2ClientMapper.insert(dbOAuth2Client);// @Sql: 先插入出一条存在的数据 // 准备参数 OAuth2ClientSaveReqVO reqVO = randomPojo(OAuth2ClientSaveReqVO.class, o -> ...
public static void mergeParams( Map<String, ParamDefinition> params, Map<String, ParamDefinition> paramsToMerge, MergeContext context) { if (paramsToMerge == null) { return; } Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream()) .forEach( name ...
@Test public void testMergeSubworkflowRestartWithMutableOnStart() throws IOException { DefaultParamManager defaultParamManager = new DefaultParamManager(JsonHelper.objectMapperWithYaml()); defaultParamManager.init(); Map<String, ParamDefinition> allParams = defaultParamManager.getDefaultPa...
public void scanNotActiveChannel() { Iterator<Map.Entry<String, ConcurrentHashMap<Channel, ClientChannelInfo>>> iterator = this.groupChannelTable.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, ConcurrentHashMap<Channel, ClientChannelInfo>> entry = iterator.next(); ...
@Test public void scanNotActiveChannel() throws Exception { producerManager.registerProducer(group, clientInfo); AtomicReference<String> groupRef = new AtomicReference<>(); AtomicReference<ClientChannelInfo> clientChannelInfoRef = new AtomicReference<>(); producerManager.appendProduc...
public static PrimitiveType fromPrimitiveString(String typeString) { String lowerTypeString = typeString.toLowerCase(Locale.ROOT); if (TYPES.containsKey(lowerTypeString)) { return TYPES.get(lowerTypeString); } Matcher fixed = FIXED.matcher(lowerTypeString); if (fixed.matches()) { return...
@Test public void fromPrimitiveString() { assertThat(Types.fromPrimitiveString("boolean")).isSameAs(Types.BooleanType.get()); assertThat(Types.fromPrimitiveString("BooLean")).isSameAs(Types.BooleanType.get()); assertThat(Types.fromPrimitiveString("timestamp")).isSameAs(Types.TimestampType.withoutZone());...
MethodSpec buildFunction(AbiDefinition functionDefinition) throws ClassNotFoundException { return buildFunction(functionDefinition, true); }
@Test public void testBuildFunctionConstantSingleValueReturn() throws Exception { AbiDefinition functionDefinition = new AbiDefinition( true, Arrays.asList(new NamedType("param", "uint8")), "functionName", ...
@Override public void export(RegisterTypeEnum registerType) { if (this.exported) { return; } if (getScopeModel().isLifeCycleManagedExternally()) { // prepare model for reference getScopeModel().getDeployer().prepare(); } else { // ensu...
@Test void testMethodConfigWithUnmatchedArgument() { Assertions.assertThrows(IllegalArgumentException.class, () -> { ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>(); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); ...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } if(new DefaultPathContainerService().isContainer(file)) { return PathAttributes.EMPTY; } ...
@Test public void testFind() throws Exception { final Path test = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final DriveFileIdProvider fileid = new DriveFileIdProvider(session); new DriveTouchFeature(session, f...
public Map<String, List<Host>> groups() { return this.groups(HostFilter.NONE); }
@Test public void testGroups() { final AbstractHostCollection c = new AbstractHostCollection() { }; final Host bookmarkGroupa1 = new Host(new TestProtocol(), "h", new Credentials("u")); bookmarkGroupa1.setLabels(Collections.singleton("a")); final Host bookmarkGroupA1 = new Ho...
public int boundedControlledPoll( final ControlledFragmentHandler handler, final long limitPosition, final int fragmentLimit) { if (isClosed) { return 0; } long initialPosition = subscriberPosition.get(); if (initialPosition >= limitPosition) { ...
@Test void shouldPollFragmentsToBoundedControlledFragmentHandlerWithMaxPositionAfterEndOfTerm() { final int initialOffset = TERM_BUFFER_LENGTH - (ALIGNED_FRAME_LENGTH * 2); final long initialPosition = computePosition( INITIAL_TERM_ID, initialOffset, POSITION_BITS_TO_SHIFT, INITIAL_T...
public static Exception lookupExceptionInCause(Throwable source, Class<? extends Exception>... clazzes) { while (source != null) { for (Class<? extends Exception> clazz : clazzes) { if (clazz.isAssignableFrom(source.getClass())) { return (Exception) source; ...
@Test void givenNoCauseAndExceptionIsWantedCauseClass_whenLookupExceptionInCause_thenReturnSelf() { assertThat(ExceptionUtil.lookupExceptionInCause(cause, RuntimeException.class)).isSameAs(cause); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest httpRequest) { HttpServletResponse httpResponse = (HttpServletResponse) response; try { chain.doFilter(new Servle...
@Test public void request_used_in_chain_do_filter_is_a_servlet_wrapper_when_service_call() throws Exception { underTest.doFilter(request("POST", "/context/service/call", "param=value"), mock(HttpServletResponse.class), chain); ArgumentCaptor<ServletRequest> requestArgumentCaptor = ArgumentCaptor.forClass(Serv...
@Override public boolean isSupported(TemporalUnit unit) { return offsetTime.isSupported(unit); }
@Test void isSupportedTemporalField() { for (ChronoField field : ChronoField.values()) { assertEquals(offsetTime.isSupported(field), zoneTime.isSupported(field)); } }
public String convert(ILoggingEvent le) { long timestamp = le.getTimeStamp(); return cachingDateFormatter.format(timestamp); }
@Test public void convertsDateWithSpecifiedLocaleLangAndCountry() { assertThat(convert(_timestamp, DATETIME_PATTERN, "UTC", "zh,CN"), matchesPattern(CHINESE_TIME_UTC)); }
public static Object getDefaultPrimitiveValue(Class clazz) { if (clazz == int.class) { return 0; } else if (clazz == boolean.class) { return false; } else if (clazz == long.class) { return 0L; } else if (clazz == byte.class) { return (byte)...
@Test public void getDefaultPrimitiveValue() throws Exception { Assert.assertEquals((short) 0, ClassUtils.getDefaultPrimitiveValue(short.class)); Assert.assertEquals(0, ClassUtils.getDefaultPrimitiveValue(int.class)); Assert.assertEquals(0l, ClassUtils.getDefaultPrimitiveValue(long.class)); ...
public static synchronized AbstractAbilityControlManager getInstance() { if (null == abstractAbilityControlManager) { initAbilityControlManager(); } return abstractAbilityControlManager; }
@Test void testGetInstance() { assertNotNull(NacosAbilityManagerHolder.getInstance()); }
@Override public void startWorker( StartWorkerRequest request, StreamObserver<StartWorkerResponse> responseObserver) { LOG.info( "Starting worker {} pointing at {}.", request.getWorkerId(), request.getControlEndpoint().getUrl()); LOG.debug("Worker request {}.", request); End...
@Test public void startWorker() { PipelineOptions options = PipelineOptionsFactory.create(); StartWorkerRequest request = StartWorkerRequest.getDefaultInstance(); StreamObserver<StartWorkerResponse> responseObserver = mock(StreamObserver.class); ExternalWorkerService service = new ExternalWorkerServic...
@SafeVarargs public static <T> Stream<T> of(T... array) { Assert.notNull(array, "Array must be not null!"); return Stream.of(array); }
@SuppressWarnings({"RedundantOperationOnEmptyContainer", "RedundantCollectionOperation"}) @Test public void streamTestEmptyListToIterator() { assertStreamIsEmpty(StreamUtil.of(new ArrayList<>().iterator())); }
public static HollowSchema parseSchema(String schema) throws IOException { StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(schema)); configureTokenizer(tokenizer); return parseSchema(tokenizer); }
@Test public void parsesMapSchemaWithPrimaryKey() throws IOException { String listSchema = "MapOfStringToTypeA Map<String, TypeA> @HashKey(value);\n"; HollowMapSchema schema = (HollowMapSchema) HollowSchemaParser.parseSchema(listSchema); Assert.assertEquals("MapOfStringToTypeA", schema.get...
public R execute(Retryable<R> retryable) throws ExecutionException { long endMs = time.milliseconds() + retryBackoffMaxMs; int currAttempt = 0; ExecutionException error = null; while (time.milliseconds() <= endMs) { currAttempt++; try { return re...
@Test public void testRuntimeExceptionFailureOnLastAttempt() { Exception[] attempts = new Exception[] { new IOException("pretend connect error"), new IOException("pretend timeout error"), new NullPointerException("pretend JSON node /userId in response is null") };...
@Override public void validate(ChangeContext context) { for (ClusterSpec.Id clusterId : context.previousModel().allClusters()) { Optional<NodeResources> currentResources = resourcesOf(clusterId, context.previousModel()); Optional<NodeResources> nextResources = resourcesOf(clusterId, ...
@Test void test_restart_action_count() { assertEquals(0, validate(model(1, 1, 1, 1), model(1, 1, 1, 1)).size()); assertEquals(1, validate(model(1, 1, 1, 1), model(2, 1, 1, 1)).size()); assertEquals(2, validate(model(1, 1, 1, 1), model(1, 2, 1, 1)).size()); assertEquals(3, validate(mo...
protected abstract PTransform<PCollection<KafkaRecord<byte[], byte[]>>, PCollection<Row>> getPTransformForInput();
@Test public void testRecorderDecoder() throws Exception { BeamKafkaTable kafkaTable = getBeamKafkaTable(); PCollection<Row> result = pipeline .apply(Create.of(generateEncodedPayload(1), generateEncodedPayload(2))) .apply(MapElements.via(new BytesToRecord())) .setC...
public DateTokenConverter<Object> getPrimaryDateTokenConverter() { Converter<Object> p = headTokenConverter; while (p != null) { if (p instanceof DateTokenConverter) { DateTokenConverter<Object> dtc = (DateTokenConverter<Object>) p; // only primary converters...
@Test public void nullTimeZoneByDefault() { FileNamePattern fnp = new FileNamePattern("%d{hh}", context); assertNull(fnp.getPrimaryDateTokenConverter().getZoneId()); }
public static MetadataCoderV2 of() { return INSTANCE; }
@Test public void testEncodeDecodeWithCustomLastModifiedMills() throws Exception { Path filePath = tmpFolder.newFile("somefile").toPath(); Metadata metadata = Metadata.builder() .setResourceId( FileSystems.matchNewResource(filePath.toString(), false /* isDirectory */)) ...
@VisibleForTesting SortedSet<Path> getDeadWorkerDirs(int nowSecs, Set<Path> logDirs) throws Exception { if (logDirs.isEmpty()) { return new TreeSet<>(); } else { Set<String> aliveIds = workerLogs.getAliveIds(nowSecs); return workerLogs.getLogDirs(logDirs, (wid) ->...
@Test public void testGetDeadWorkerDirs() throws Exception { Map<String, Object> stormConf = Utils.readStormConfig(); stormConf.put(SUPERVISOR_WORKER_TIMEOUT_SECS, 5); LSWorkerHeartbeat hb = new LSWorkerHeartbeat(); hb.set_time_secs(1); Map<String, LSWorkerHeartbeat> idToHb...
public void resolveAssertionConsumerService(AuthenticationRequest authenticationRequest) throws SamlValidationException { // set URL if set in authnRequest final String authnAcsURL = authenticationRequest.getAuthnRequest().getAssertionConsumerServiceURL(); if (authnAcsURL != null) { ...
@Test void resolveAcsUrlWithIndex2InMultiAcsMetadata() throws SamlValidationException { AuthnRequest authnRequest = OpenSAMLUtils.buildSAMLObject(AuthnRequest.class); authnRequest.setAssertionConsumerServiceIndex(2); AuthenticationRequest authenticationRequest = new AuthenticationRequest();...
@Override public void registerStore(StateStore store) { final String storeName = store.fqsn(); checkArgument(!stores.containsKey(storeName), String.format("Store %s has already been registered.", storeName)); stores.put(storeName, store); }
@Test public void testRegisterStoreTwice() { final String fqsn = "t/ns/store"; StateStore store = mock(StateStore.class); when(store.fqsn()).thenReturn(fqsn); this.stateManager.registerStore(store); try { this.stateManager.registerStore(store); fail("S...
@Override public Object[] extract(Tuple in) { Object[] output; if (order == null) { // copy the whole tuple output = new Object[in.getArity()]; for (int i = 0; i < in.getArity(); i++) { output[i] = in.getField(i); } } else { ...
@Test void testConvertFromTupleToArray() throws InstantiationException, IllegalAccessException { for (int i = 0; i < Tuple.MAX_ARITY; i++) { Tuple currentTuple = (Tuple) CLASSES[i].newInstance(); String[] currentArray = new String[i + 1]; for (int j = 0; j <= i; j++) { ...
@Override public Health check() { Platform.Status platformStatus = platform.status(); if (platformStatus == Platform.Status.UP && VALID_DATABASEMIGRATION_STATUSES.contains(migrationState.getStatus()) && !restartFlagHolder.isRestarting()) { return Health.GREEN; } return Health.builder...
@Test public void returns_RED_status_with_cause_if_platform_status_is_not_UP() { Platform.Status[] statusesButUp = Arrays.stream(Platform.Status.values()) .filter(s -> s != Platform.Status.UP) .toArray(Platform.Status[]::new); Platform.Status randomStatusButUp = statusesButUp[random.nextInt(status...
@ApiOperation(value = "Delete edge (deleteEdge)", notes = "Deletes the edge. Referencing non-existing edge Id will cause an error." + TENANT_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAuthority('TENANT_ADMIN')") @DeleteMapping(value = "/edge/{edgeId}") public void deleteEdge(@Parameter(description =...
@Test public void testDeleteEdge() throws Exception { Edge edge = constructEdge("My edge", "default"); Edge savedEdge = doPost("/api/edge", edge, Edge.class); Mockito.reset(tbClusterService, auditLogService); doDelete("/api/edge/" + savedEdge.getId().getId().toString()) ...
public final byte[] encode(String text) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); int offset = 0; while (offset < text.length()) { int codePoint = text.codePointAt(offset); // multi-byte encoding with 1 to 4 bytes ...
@Test void testPDFox4318() throws IOException { PDType1Font helveticaBold = new PDType1Font(FontName.HELVETICA_BOLD); assertThrows(IllegalArgumentException.class, () -> helveticaBold.encode("\u0080"), "should have thrown IllegalArgumentException"); helveti...
@Nullable public static Map<String, String> getLoggerInfo(String loggerName) { LoggerContext context = (LoggerContext) LogManager.getContext(false); Configuration config = context.getConfiguration(); if (!getAllConfiguredLoggers().contains(loggerName)) { return null; } LoggerConfig loggerCon...
@Test public void testGetLoggerInfo() { Map<String, String> rootLoggerInfo = LoggerUtils.getLoggerInfo(ROOT); assertNotNull(rootLoggerInfo); assertEquals(rootLoggerInfo.get("name"), ROOT); assertEquals(rootLoggerInfo.get("level"), "ERROR"); assertNull(rootLoggerInfo.get("filter")); Map<String...