focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public String getMethod() { return PATH; }
@Test public void testSetMyDefaultAdministratorRightsWithAllSet() { SetMyDefaultAdministratorRights setMyDefaultAdministratorRights = SetMyDefaultAdministratorRights .builder() .forChannels(true) .rights(ChatAdministratorRights .builder...
long getCapacity() { long capacity = 0L; for (FsVolumeImpl v : volumes) { try (FsVolumeReference ref = v.obtainReference()) { capacity += v.getCapacity(); } catch (IOException e) { // ignore. } } return capacity; }
@Test public void testGetCachedVolumeCapacity() throws IOException { conf.setBoolean(DFSConfigKeys.DFS_DATANODE_FIXED_VOLUME_SIZE_KEY, DFSConfigKeys.DFS_DATANODE_FIXED_VOLUME_SIZE_DEFAULT); long capacity = 4000L; DF usage = mock(DF.class); when(usage.getCapacity()).thenReturn(capacity); ...
public Object createEnum(String symbol, Schema schema) { return new EnumSymbol(schema, symbol); }
@Test void enumCompare() { Schema s = Schema.createEnum("Kind", null, null, Arrays.asList("Z", "Y", "X")); GenericEnumSymbol z = new GenericData.EnumSymbol(s, "Z"); GenericEnumSymbol z2 = new GenericData.EnumSymbol(s, "Z"); assertEquals(0, z.compareTo(z2)); GenericEnumSymbol y = new GenericData.En...
public static List<AclEntry> filterAclEntriesByAclSpec( List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); EnumMap<AclEntryScope, AclEntry>...
@Test public void testFilterAclEntriesByAclSpecEmptyAclSpec() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, USER, "bruce", READ_WRITE)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, ...
@Override public SchemaTransform from(PubsubReadSchemaTransformConfiguration configuration) { if (configuration.getSubscription() == null && configuration.getTopic() == null) { throw new IllegalArgumentException( "To read from Pubsub, a subscription name or a topic name must be provided"); } ...
@Test public void testReadRaw() throws IOException { PCollectionRowTuple begin = PCollectionRowTuple.empty(p); Schema rawSchema = Schema.of(Schema.Field.of("payload", Schema.FieldType.BYTES)); byte[] payload = "some payload".getBytes(StandardCharsets.UTF_8); try (PubsubTestClientFactory clientFactor...
public static FileCacheStore getInstance(String basePath, String cacheName) { return getInstance(basePath, cacheName, true); }
@Test void testPathIsFile() throws URISyntaxException, IOException { String basePath = getDirectoryOfClassPath(); String filePath = basePath + File.separator + "isFile"; new File(filePath).createNewFile(); Assertions.assertThrows(RuntimeException.class, () -> FileCacheStoreFactory.g...
@VisibleForTesting public static void addUserAgentEnvironments(List<String> info) { info.add(String.format(OS_FORMAT, OSUtils.OS_NAME)); if (EnvironmentUtils.isDocker()) { info.add(DOCKER_KEY); } if (EnvironmentUtils.isKubernetes()) { info.add(KUBERNETES_KEY); } if (EnvironmentUtil...
@Test public void userAgentEnvironmentStringDocker() { Mockito.when(EnvironmentUtils.isDocker()).thenReturn(true); Mockito.when(EC2MetadataUtils.getUserData()) .thenThrow(new SdkClientException("Unable to contact EC2 metadata service.")); List<String> info = new ArrayList<>(); UpdateCheckUtils...
@Override public synchronized DefaultConnectClient get( final Optional<String> ksqlAuthHeader, final List<Entry<String, String>> incomingRequestHeaders, final Optional<KsqlPrincipal> userPrincipal ) { if (defaultConnectAuthHeader == null) { defaultConnectAuthHeader = buildDefaultAuthHead...
@Test public void shouldReloadCredentialsOnFileCreation() throws Exception { // Given: when(config.getBoolean(KsqlConfig.CONNECT_BASIC_AUTH_CREDENTIALS_RELOAD_PROPERTY)).thenReturn(true); givenCustomBasicAuthHeader(); // no credentials file present // verify that no auth header is present ass...
public static FileMetadata fromJson(String json) { return JsonUtil.parse(json, FileMetadataParser::fromJson); }
@Test public void testMissingBlobs() { assertThatThrownBy(() -> FileMetadataParser.fromJson("{\"properties\": {}}")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot parse missing field: blobs"); }
public void execute(){ logger.debug("[" + getOperationName() + "] Starting execution of paged operation. maximum time: " + maxTime + ", maximum pages: " + maxPages); long startTime = System.currentTimeMillis(); long executionTime = 0; int i = 0; int exceptionsSwallowedCount = 0; int operationsCompleted =...
@Test(timeout = 1000L) public void execute_zerotime(){ CountingPageOperation op = new CountingPageOperation(Integer.MAX_VALUE,0L); op.execute(); assertEquals(0L, op.getCounter()); assertEquals(0L, op.getTimeToLastFetch()); }
public Optional<ViewDefinition> getViewDefinition(QualifiedObjectName viewName) { if (!viewDefinitions.containsKey(viewName)) { throw new PrestoException(VIEW_NOT_FOUND, format("View %s not found, the available view names are: %s", viewName, viewDefinitions.keySet())); } try { ...
@Test public void testGetViewDefinition() { Optional<ViewDefinition> viewDefinitionOptional = metadataHandle.getViewDefinition(QualifiedObjectName.valueOf("tpch.s1.t1")); assertTrue(viewDefinitionOptional.isPresent()); ViewDefinition viewDefinition = viewDefinitionOptional.get(); ...
@Override public String ping(RedisClusterNode node) { RedisClient entry = getEntry(node); RFuture<String> f = executorService.readAsync(entry, LongCodec.INSTANCE, RedisCommands.PING); return syncFuture(f); }
@Test public void testClusterPing() { RedisClusterNode master = getFirstMaster(); String res = connection.ping(master); assertThat(res).isEqualTo("PONG"); }
@Override public void addInterfaces(VplsData vplsData, Collection<Interface> interfaces) { requireNonNull(vplsData); requireNonNull(interfaces); VplsData newData = VplsData.of(vplsData); newData.addInterfaces(interfaces); updateVplsStatus(newData, VplsData.VplsState.UPDATING)...
@Test public void testAddInterfaces() { VplsData vplsData = vplsManager.createVpls(VPLS1, NONE); vplsManager.addInterfaces(vplsData, ImmutableSet.of(V100H1, V100H2)); vplsData = vplsStore.getVpls(VPLS1); assertNotNull(vplsData); assertEquals(vplsData.state(), UPDATING); ...
@Override public String getName() { return ANALYZER_NAME; }
@Test public void testGetName() { VersionFilterAnalyzer instance = new VersionFilterAnalyzer(); String expResult = "Version Filter Analyzer"; String result = instance.getName(); assertEquals(expResult, result); }
@Override public void define(Context context) { NewController controller = context.createController(CONTROLLER); controller.setDescription("Manage permission templates, and the granting and revoking of permissions at the global and project levels."); controller.setSince("3.7"); for (PermissionsWsActi...
@Test public void define_controller() { WebService.Context context = new WebService.Context(); underTest.define(context); WebService.Controller controller = context.controller("api/permissions"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertTha...
@Override protected Future<KafkaBridgeStatus> createOrUpdate(Reconciliation reconciliation, KafkaBridge assemblyResource) { KafkaBridgeStatus kafkaBridgeStatus = new KafkaBridgeStatus(); String namespace = reconciliation.namespace(); KafkaBridgeCluster bridge; try { bri...
@Test public void testCreateOrUpdateUpdatesCluster(VertxTestContext context) { ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(true); var mockBridgeOps = supplier.kafkaBridgeOperator; DeploymentOperator mockDcOps = supplier.deploymentOperations; PodDisruptionBudge...
public static Configuration loadConfiguration() { return loadConfiguration(new Configuration()); }
@Test void testInvalidConfiguration() { assertThatThrownBy(() -> GlobalConfiguration.loadConfiguration(tmpDir.getAbsolutePath())) .isInstanceOf(IllegalConfigurationException.class); }
public static IOException maybeExtractIOException( String path, Throwable thrown, String message) { if (thrown == null) { return null; } // walk down the chain of exceptions to find the innermost. Throwable cause = getInnermostThrowable(thrown.getCause(), thrown); // see i...
@Test public void testConnectExceptionExtraction() throws Throwable { intercept(ConnectException.class, "top", () -> { throw maybeExtractIOException("p1", sdkException("top", sdkException("middle", new ConnectException("bottom"))), null); ...
public static <S, T> RemoteIterator<T> mappingRemoteIterator( RemoteIterator<S> iterator, FunctionRaisingIOE<? super S, T> mapper) { return new MappingRemoteIterator<>(iterator, mapper); }
@Test public void testMapping() throws Throwable { CountdownRemoteIterator countdown = new CountdownRemoteIterator(100); RemoteIterator<Integer> it = mappingRemoteIterator( countdown, i -> i); verifyInvoked(it, 100, c -> counter++); assertCounterValue(100); extractStatistics(it); ...
public static String toJavaIdentifierString(String className) { // replace invalid characters with '_' return CharMatcher.forPredicate(Character::isJavaIdentifierPart).negate() .replaceFrom(className, '_'); }
@Test public void testToJavaIdentifierString() { assertEquals(toJavaIdentifierString("HelloWorld"), "HelloWorld"); assertEquals(toJavaIdentifierString("Hello$World"), "Hello$World"); assertEquals(toJavaIdentifierString("Hello#World"), "Hello_World"); assertEquals(toJavaIdentifier...
@Override public GetClusterNodeAttributesResponse getClusterNodeAttributes( GetClusterNodeAttributesRequest request) throws YarnException, IOException { if (request == null) { routerMetrics.incrGetClusterNodeAttributesFailedRetrieved(); String msg = "Missing getClusterNodeAttributes request."; ...
@Test public void testClusterNodeAttributes() throws Exception { LOG.info("Test FederationClientInterceptor : Get ClusterNodeAttributes request."); // null request LambdaTestUtils.intercept(YarnException.class, "Missing getClusterNodeAttributes request.", () -> interceptor.getClusterNodeAttribute...
@Override public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility( TypeSerializerSnapshot<T> oldSerializerSnapshot) { if (!(oldSerializerSnapshot instanceof AvroSerializerSnapshot)) { return TypeSerializerSchemaCompatibility.incompatible(); } AvroSerial...
@Test void removingAnOptionalFieldsIsCompatibleAsIs() { assertThat( AvroSerializerSnapshot.resolveSchemaCompatibility( FIRST_REQUIRED_LAST_OPTIONAL, FIRST_NAME)) .is(isCompatibleAfterMigration()); }
@Override public V fetch(final K key, final long time) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlyWindowStore<K, V>> stores = provider.stores(storeName, windowStoreType); for (final ReadOnlyWindowStore<K, V> windowStore : stores) { try { ...
@Test public void shouldNotGetValuesFromOtherStores() { otherUnderlyingStore.put("some-key", "some-value", 0L); underlyingWindowStore.put("some-key", "my-value", 1L); final List<KeyValue<Long, String>> results = StreamsTestUtils.toList(windowStore.fetch("some-key", ofEpochMilli(...
public static boolean isDubboProxyName(String name) { return name.startsWith(ALIBABA_DUBBO_PROXY_NAME_PREFIX) || name.startsWith(APACHE_DUBBO_PROXY_NAME_PREFIX) || name.contains(DUBBO_3_X_PARTIAL_PROXY_NAME); }
@Test public void testIsNotDubboProxyName() { assertFalse(DubboUtil.isDubboProxyName(ArrayList.class.getName())); }
public AppNamespace findPublicAppNamespace(String namespaceName) { List<AppNamespace> appNamespaces = appNamespaceRepository.findByNameAndIsPublic(namespaceName, true); if (CollectionUtils.isEmpty(appNamespaces)) { return null; } return appNamespaces.get(0); }
@Test @Sql(scripts = "/sql/appnamespaceservice/init-appnamespace.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/sql/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) public void testFindPublicAppNamespace() { List<AppNamespace> appNamespaceList = appNamespac...
public static boolean isNumber(String text) { final int startPos = findStartPosition(text); if (startPos < 0) { return false; } for (int i = startPos; i < text.length(); i++) { char ch = text.charAt(i); if (!Character.isDigit(ch)) { re...
@Test @DisplayName("Tests that isNumber returns false for floats") void isNumberFloats() { assertFalse(ObjectHelper.isNumber("12.34")); assertFalse(ObjectHelper.isNumber("-12.34")); assertFalse(ObjectHelper.isNumber("1.0")); assertFalse(ObjectHelper.isNumber("0.0")); }
@Override public void filter(ContainerRequestContext requestContext) { if (isInternalRequest(requestContext)) { log.trace("Skipping authentication for internal request"); return; } try { log.debug("Authenticating request"); BasicAuthCredential...
@Test public void testUnknownCredentialsFile() { JaasBasicAuthFilter jaasBasicAuthFilter = setupJaasFilter("KafkaConnect", "/tmp/testcrednetial"); ContainerRequestContext requestContext = setMock("Basic", "user", "password"); jaasBasicAuthFilter.filter(requestContext); verify(reques...
@Override public InetSocketAddress resolve(ServerWebExchange exchange) { List<String> xForwardedValues = extractXForwardedValues(exchange); if (!xForwardedValues.isEmpty()) { int index = Math.max(0, xForwardedValues.size() - maxTrustedIndex); return new InetSocketAddress(xForwardedValues.get(index), 0); } ...
@Test public void trustAllFallsBackOnEmptyHeader() { ServerWebExchange exchange = buildExchange(remoteAddressOnlyBuilder().header("X-Forwarded-For", "")); InetSocketAddress address = trustAll.resolve(exchange); assertThat(address.getHostName()).isEqualTo("0.0.0.0"); }
public TaskAcknowledgeResult acknowledgeCoordinatorState( OperatorInfo coordinatorInfo, @Nullable ByteStreamStateHandle stateHandle) { synchronized (lock) { if (disposed) { return TaskAcknowledgeResult.DISCARDED; } final OperatorID operatorId = c...
@Test void testAcknowledgeUnknownCoordinator() throws Exception { final PendingCheckpoint checkpoint = createPendingCheckpointWithCoordinators(new TestingOperatorInfo()); final TaskAcknowledgeResult ack = checkpoint.acknowledgeCoordinatorState(new TestingOperatorInfo...
public IterableOfProtosFluentAssertion<M> ignoringRepeatedFieldOrder() { return usingConfig(config.ignoringRepeatedFieldOrder()); }
@Test public void testFormatDiff() { expectFailureWhenTesting() .that(listOf(message1)) .ignoringRepeatedFieldOrder() .containsExactly(message2); expectThatFailure() .factValue("diff") .isEqualTo( "Differences were found:\n" + "modified: o_in...
@Override public String getContextualName(DubboClientContext context) { return super.getContextualName(context.getInvocation()); }
@Test void testGetContextualName() { RpcInvocation invocation = new RpcInvocation(); Invoker<?> invoker = ObservationConventionUtils.getMockInvokerWithUrl(); invocation.setMethodName("testMethod"); invocation.setServiceName("com.example.TestService"); DubboClientContext cont...
@Override public short getTypeCode() { return MessageType.TYPE_REG_RM; }
@Test public void getTypeCode() { RegisterRMRequest registerRMRequest = new RegisterRMRequest(); assertThat(MessageType.TYPE_REG_RM).isEqualTo(registerRMRequest.getTypeCode()); }
public static synchronized RealtimeSegmentStatsHistory deserialzeFrom(File inFile) throws IOException, ClassNotFoundException { if (inFile.exists()) { try (FileInputStream is = new FileInputStream(inFile); ObjectInputStream obis = new CustomObjectInputStream(is)) { RealtimeSegmentStatsHistory hi...
@Test public void testMultiThreadedUse() throws Exception { final int numThreads = 8; final int numIterations = 10; final long avgSleepTimeMs = 300; Thread[] threads = new Thread[numThreads]; final String tmpDir = System.getProperty("java.io.tmpdir"); File serializedFile = new File(tmpDi...
public static OsInfo getOsInfo() { return Singleton.get(OsInfo.class); }
@Test public void getOsInfoTest() { final OsInfo osInfo = SystemUtil.getOsInfo(); assertNotNull(osInfo); Console.log(osInfo.getName()); }
public synchronized String get() { ConfidentialStore cs = ConfidentialStore.get(); if (secret == null || cs != lastCS) { lastCS = cs; try { byte[] payload = load(); if (payload == null) { payload = cs.randomBytes(length / 2); ...
@Test public void hexStringShouldProduceHexString() { HexStringConfidentialKey key = new HexStringConfidentialKey("test", 8); assertTrue(key.get().matches("[A-Fa-f0-9]{8}")); }
@Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { return inject(statement, new TopicProperties.Builder()); }
@Test public void shouldPassThroughWithClauseToBuilderForCreateAs() { // Given: givenStatement("CREATE STREAM x WITH (kafka_topic='topic') AS SELECT * FROM SOURCE;"); final CreateSourceAsProperties props = ((CreateAsSelect) statement.getStatement()) .getProperties(); // When: injector.in...
public SearchQuery parse(String encodedQueryString) { if (Strings.isNullOrEmpty(encodedQueryString) || "*".equals(encodedQueryString)) { return new SearchQuery(encodedQueryString); } final var queryString = URLDecoder.decode(encodedQueryString, StandardCharsets.UTF_8); fina...
@Test void booleanValuesSupported() { final SearchQueryParser parser = new SearchQueryParser("name", Map.of( "name", SearchQueryField.create("title", SearchQueryField.Type.STRING), "gone", SearchQueryField.create("disabled", SearchQueryField.Ty...
@Inject public FileMergeCacheManager( CacheConfig cacheConfig, FileMergeCacheConfig fileMergeCacheConfig, CacheStats stats, ExecutorService cacheFlushExecutor, ExecutorService cacheRemovalExecutor, ScheduledExecutorService cacheSizeCalculateExe...
@Test(invocationCount = 10) public void testStress() throws ExecutionException, InterruptedException { CacheConfig cacheConfig = new CacheConfig().setBaseDirectory(cacheDirectory); FileMergeCacheConfig fileMergeCacheConfig = new FileMergeCacheConfig().setCacheTtl(new Duration(10, MIL...
public static long getSeed(String streamId, long masterSeed) { MessageDigest md5 = md5Holder.get(); md5.reset(); //'/' : make sure that we don't get the same str from ('11',0) and ('1',10) // We could have fed the bytes of masterSeed one by one to md5.update() // instead String str = streamId + ...
@Test public void testSeedGeneration() { long masterSeed1 = 42; long masterSeed2 = 43; assertTrue("Deterministic seeding", getSeed("stream1", masterSeed1) == getSeed("stream1", masterSeed1)); assertTrue("Deterministic seeding", getSeed("stream2", masterSeed2) == getSeed("stream2",...
public int accumulateSum(int... nums) { LOGGER.info("Source module {}", VERSION); var sum = 0; for (final var num : nums) { sum += num; } return sum; }
@Test void testAccumulateSum() { assertEquals(0, source.accumulateSum(-1, 0, 1)); }
@Override public String getProcessNamespace(String fingerprint) { return CachedDigestUtils.sha256Hex(fingerprint + agentIdentifier.getUuid() + workingDirectory); }
@Test public void shouldReturnDigestOfMaterialFingerprintConcatinatedWithAgentUUID() { AgentIdentifier agentIdentifier = mock(AgentIdentifier.class); String uuid = "agent-uuid"; when(agentIdentifier.getUuid()).thenReturn(uuid); String fingerprint = "material-fingerprint"; Str...
@Override public int start(int from) { Assert.notNull(this.text, "Text to find must be not null!"); final int limit = getValidEndIndex(); if(negative){ for (int i = from; i > limit; i--) { if (NumberUtil.equals(c, text.charAt(i), caseInsensitive)) { return i; } } } else{ for (int i = from...
@Test public void negativeStartTest(){ int start = new CharFinder('a').setText("cba123").setNegative(true).start(2); assertEquals(2, start); start = new CharFinder('2').setText("cba123").setNegative(true).start(2); assertEquals(-1, start); start = new CharFinder('c').setText("cba123").setNegative(true).sta...
public static List<Term> parse(Map<String, Object> map) { if (MapUtils.isEmpty(map)) { return Collections.emptyList(); } List<Term> terms = new ArrayList<>(map.size()); for (Map.Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); ...
@Test public void testChinese() { { List<Term> terms = TermExpressionParser.parse("name = 我"); assertEquals(terms.get(0).getTermType(), TermType.eq); assertEquals(terms.get(0).getValue(),"我"); } { List<Term> terms = TermExpressionParser.pars...
public static boolean isValidDateFormatToStringDate( String dateFormat, String dateString ) { String detectedDateFormat = detectDateFormat( dateString ); if ( ( dateFormat != null ) && ( dateFormat.equals( detectedDateFormat ) ) ) { return true; } return false; }
@Test public void testIsValidDateFormatToStringDateLocale() { assertTrue( DateDetector.isValidDateFormatToStringDate( SAMPLE_DATE_FORMAT_US, SAMPLE_DATE_STRING_US, LOCALE_en_US ) ); assertFalse( DateDetector.isValidDateFormatToStringDate( null, SAMPLE_DATE_STRING, LOCALE_en_US ) ); assertFalse( DateDetect...
public BitList<Invoker<T>> getInvokers() { return invokers; }
@Test void tagRouterRuleParseTest() { String tagRouterRuleConfig = "---\n" + "force: false\n" + "runtime: true\n" + "enabled: false\n" + "priority: 1\n" + "key: demo-provider\n" + "tags:\n" + " - name: tag1\n" ...
@Override public AssertionResult getResult(SampleResult response) { // no error as default AssertionResult result = new AssertionResult(getName()); result.setFailure(false); result.setFailureMessage(""); byte[] responseData = null; Document doc = null; try {...
@Test public void testAssertionBlankResult() throws Exception { result.setResponseData(" ", null); AssertionResult res = assertion.getResult(result); testLog.debug("isError() {} isFailure() {}", res.isError(), res.isFailure()); testLog.debug("failure message: {}", res.getFailureMessa...
static void unTarUsingJava(File inFile, File untarDir, boolean gzipped) throws IOException { InputStream inputStream = null; TarArchiveInputStream tis = null; try { if (gzipped) { inputStream = new GZIPInputStream(Files.newInputStream(inFile.toPath())); } else { ...
@Test(expected = IOException.class) public void testCreateArbitrarySymlinkUsingJava() throws IOException { final File simpleTar = new File(del, FILE); OutputStream os = new FileOutputStream(simpleTar); File rootDir = new File("tmp"); try (TarArchiveOutputStream tos = new TarArchiveOutputStream(os)) {...
@Override public void execute(Context context) { editionProvider.get().ifPresent(edition -> { if (!edition.equals(EditionProvider.Edition.COMMUNITY)) { return; } Map<String, Integer> filesPerLanguage = reportReader.readMetadata().getNotAnalyzedFilesByLanguageMap() .entrySet() ...
@Test public void adds_warning_and_measures_in_SQ_community_edition_if_there_are_c_files() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); reportReader.setMetadata(ScannerReport.Metadata.newBuilder() .putNotAnalyzedFilesByLanguage("C", 10) .build()); ...
public SecretStore load(SecureConfig secureConfig) { return doIt(MODE.LOAD, secureConfig); }
@Test public void testAlternativeImplementationInvalid() { SecureConfig secureConfig = new SecureConfig(); secureConfig.add("keystore.classname", "junk".toCharArray()); assertThrows(SecretStoreException.ImplementationNotFoundException.class, () -> { secretStoreFactory.load(secur...
public Properties getProperties() { return properties; }
@Test public void testUriWithSslEnabledPassword() throws SQLException { PrestoDriverUri parameters = createDriverUri("presto://localhost:8080/blackhole?SSL=true&SSLTrustStorePath=truststore.jks&SSLTrustStorePassword=password"); assertUriPortScheme(parameters, 8080, "https"); ...
static Map<String, String> toMap(List<Settings.Setting> settingsList) { Map<String, String> result = new LinkedHashMap<>(); for (Settings.Setting s : settingsList) { // we need the "*.file.suffixes" and "*.file.patterns" properties for language detection // see DefaultLanguagesRepository.populateFil...
@Test public void should_always_load_language_detection_properties() { assertThat(AbstractSettingsLoader.toMap(List.of( Setting.newBuilder() .setInherited(false) .setKey("sonar.xoo.file.suffixes") .setValues(Values.newBuilder().addValues(".xoo")).build(), Setting.newBuilder() ...
public static boolean testURLPassesExclude(String url, String exclude) { // If the url doesn't decode to UTF-8 then return false, it could be trying to get around our rules with nonstandard encoding // If the exclude rule includes a "?" character, the url must exactly match the exclude rule. // ...
@Test public void pathTraversalDetectedWhenWildcardsNotAllowed() throws Exception { AuthCheckFilter.ALLOW_WILDCARDS_IN_EXCLUDES.setValue(false); assertFalse(AuthCheckFilter.testURLPassesExclude("setup/setup-/../../log.jsp?log=info&mode=asc&lines=All","setup/setup-*")); assertFalse(AuthCheckF...
public static String parseInstanceIdFromEndpoint(String endpoint) { if (StringUtils.isEmpty(endpoint)) { return null; } return endpoint.substring(endpoint.lastIndexOf("/") + 1, endpoint.indexOf('.')); }
@Test public void testParseInstanceIdFromEndpoint() { assertThat(NameServerAddressUtils.parseInstanceIdFromEndpoint(endpoint3)).isEqualTo( "MQ_INST_123456789_BXXUzaee"); assertThat(NameServerAddressUtils.parseInstanceIdFromEndpoint(endpoint4)).isEqualTo( "MQ_INST_123456789_BX...
@Override protected void validateDataImpl(TenantId tenantId, TbResource resource) { validateString("Resource title", resource.getTitle()); if (resource.getTenantId() == null) { resource.setTenantId(TenantId.SYS_TENANT_ID); } if (!resource.getTenantId().isSysTenantId()) { ...
@Test void testValidateNameInvocation() { TbResource resource = new TbResource(); resource.setTitle("rss"); resource.setResourceType(ResourceType.PKCS_12); resource.setFileName("cert.pem"); resource.setResourceKey("19_1.0"); resource.setTenantId(tenantId); va...
@Override public SelLong assignOps(SelOp op, SelType rhs) { SelTypeUtil.checkTypeMatch(this.type(), rhs.type()); long another = ((SelLong) rhs).val; switch (op) { case ASSIGN: this.val = another; // direct assignment return this; case ADD_ASSIGN: this.val += another; ...
@Test(expected = UnsupportedOperationException.class) public void testInvalidAssignOpType() { orig.assignOps(SelOp.EQUAL, orig); }
@Deprecated public String javaUnbox(Schema schema) { return javaUnbox(schema, false); }
@Test void javaUnboxDateTime() throws Exception { SpecificCompiler compiler = createCompiler(); Schema dateSchema = LogicalTypes.date().addToSchema(Schema.create(Schema.Type.INT)); Schema timeSchema = LogicalTypes.timeMillis().addToSchema(Schema.create(Schema.Type.INT)); Schema timestampSchema = Logi...
@Bean public MetaDataHandler divideMetaDataHandler() { return new DivideMetaDataHandler(); }
@Test public void testDivideMetaDataHandler() { applicationContextRunner.run(context -> { MetaDataHandler handler = context.getBean("divideMetaDataHandler", MetaDataHandler.class); assertNotNull(handler); } ); }
@Override public void merge(ColumnStatisticsObj aggregateColStats, ColumnStatisticsObj newColStats) { LOG.debug("Merging statistics: [aggregateColStats:{}, newColStats: {}]", aggregateColStats, newColStats); LongColumnStatsDataInspector aggregateData = longInspectorFromStats(aggregateColStats); LongColum...
@Test public void testMergeNullWithNonNullValues() { ColumnStatisticsObj aggrObj = createColumnStatisticsObj(new ColStatsBuilder<>(long.class) .low(null) .high(null) .numNulls(0) .numDVs(0) .build()); ColumnStatisticsObj newObj = createColumnStatisticsObj(new ColStatsBu...
void visit(final PathItem.HttpMethod method, final Operation operation, final PathItem pathItem) { if (filter.accept(operation.getOperationId())) { final String methodName = method.name().toLowerCase(); emitter.emit(methodName, path); emit("id", operation.getOperationId()); ...
@Test public void shouldEmitCodeForOas32ParameterInPath() { final Builder method = MethodSpec.methodBuilder("configure"); final MethodBodySourceCodeEmitter emitter = new MethodBodySourceCodeEmitter(method); final OperationVisitor<?> visitor = new OperationVisitor<>( ...
@Override public String forDisplay() { return value; }
@Test public void shouldReturnStringValueForReporting() { assertThat(argument.forDisplay(), is("test")); }
public int getCheckUserAccessToQueueFailedRetrieved() { return numCheckUserAccessToQueueFailedRetrieved.value(); }
@Test public void testCheckUserAccessToQueueRetrievedFailed() { long totalBadBefore = metrics.getCheckUserAccessToQueueFailedRetrieved(); badSubCluster.getCheckUserAccessToQueueFailed(); Assert.assertEquals(totalBadBefore + 1, metrics.getCheckUserAccessToQueueFailedRetrieved()); }
public void processVerstrekkingAanAfnemer(VerstrekkingAanAfnemer verstrekkingAanAfnemer){ if (logger.isDebugEnabled()) logger.debug("Processing verstrekkingAanAfnemer: {}", marshallElement(verstrekkingAanAfnemer)); Afnemersbericht afnemersbericht = afnemersberichtRepository.findByOnzeRefere...
@Test public void testProcessAf01(){ String testBsn = "SSSSSSSSS"; Af01 testAf01 = TestDglMessagesUtil.createTestAf01(testBsn); VerstrekkingInhoudType inhoudType = new VerstrekkingInhoudType(); inhoudType.setAf01(testAf01); GeversioneerdType type = new GeversioneerdType(); ...
public static RawPrivateTransaction decode(final String hexTransaction) { final byte[] transaction = Numeric.hexStringToByteArray(hexTransaction); final TransactionType transactionType = getPrivateTransactionType(transaction); if (transactionType == TransactionType.EIP1559) { return...
@Test public void testDecodingSigned() throws Exception { final BigInteger nonce = BigInteger.ZERO; final BigInteger gasPrice = BigInteger.ONE; final BigInteger gasLimit = BigInteger.TEN; final String to = "0x0add5355"; final RawPrivateTransaction rawTransaction = ...
protected Request buildRequest(String url, String sender, String data) throws JsonProcessingException { if (sender == null || !WalletUtils.isValidAddress(sender)) { throw new EnsResolutionException("Sender address is null or not valid"); } if (data == null) { ...
@Test void buildRequestWhenPostSuccessTest() throws IOException { String url = "https://example.com/gateway/{sender}.json"; String sender = "0x226159d592E2b063810a10Ebf6dcbADA94Ed68b8"; String data = "0xd5fa2b00"; okhttp3.Request request = ensResolver.buildRequest(url, sender, data)...
@Override public ScalarOperator visitCaseWhenOperator(CaseWhenOperator operator, Void context) { return shuttleIfUpdate(operator); }
@Test void visitCaseWhenOperator() { CaseWhenOperator operator = new CaseWhenOperator(INT, null, null, ImmutableList.of()); { ScalarOperator newOperator = shuttle.visitCaseWhenOperator(operator, null); assertEquals(operator, newOperator); } { Scala...
@Override public void getConfig(StorServerConfig.Builder builder) { super.getConfig(builder); provider.getConfig(builder); }
@Test void testPortOverride() { StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder(); DistributorCluster cluster = parse("<cluster id=\"storage\" distributor-base-port=\"14065\">" + " <redundancy>3</redundancy>" + ...
public ExitStatus(Options options) { this.options = options; }
@Test void with_passed_scenarios() { createRuntime(); bus.send(testCaseFinishedWithStatus(Status.PASSED)); assertThat(exitStatus.exitStatus(), is(equalTo((byte) 0x0))); }
@Override public void execute(ComputationStep.Context context) { new PathAwareCrawler<>( FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) .buildFor( Iterables.concat(NewLinesAndConditionsCoverageFormula.from(newLinesRepository, reportReader), FORMULAS))) ...
@Test public void no_measure_for_PROJECT_component() { treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, ROOT_REF).build()); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.isEmpty()).isTrue(); }
@ApiOperation("更新功能按钮资源") @PutMapping("/{actionId}") public ApiResult update(@PathVariable Long actionId, @Validated @RequestBody ActionForm actionForm){ actionForm.setActionId(actionId); baseActionService.updateAction(actionForm); return ApiResult.success(); }
@Test void update() { }
public void triggerRun() { call( new PostRequest(path()) ); }
@Test public void triggerRun_whenTriggered_shouldNotFail() { assertThatNoException().isThrownBy(() ->gitlabSynchronizationRunService.triggerRun()); }
@Override public CompletableFuture<String> triggerSavepoint( @Nullable String targetDirectory, boolean cancelJob, SavepointFormatType formatType) { return state.tryCall( StateWithExecutionGraph.class, stateWithExecutionGraph -> { ...
@Test void testStopWithSavepointFailsInIllegalState() throws Exception { final AdaptiveScheduler scheduler = new AdaptiveSchedulerBuilder( createJobGraph(), mainThreadExecutor, EXECUTOR_RESOURCE.g...
@Deprecated public static String getJwt(JwtClaims claims) throws JoseException { String jwt; RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey( jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName()); // A JWT is a JWS and/...
@Test public void longlivedCcPetstoreScpString() throws Exception { JwtClaims claims = ClaimsUtil.getTestCcClaimsScopeScp("f7d42348-c647-4efb-a52d-4c5787421e73", "write:pets read:pets"); claims.setExpirationTimeMinutesInTheFuture(5256000); String jwt = JwtIssuer.getJwt(claims, long_kid, KeyU...
public String readWPString(int length) throws IOException { char[] chars = new char[length]; for (int i = 0; i < length; i++) { int c = in.read(); if (c == -1) { throw new EOFException(); } chars[i] = (char) c; } return new ...
@Test public void testReadString() throws Exception { try (WPInputStream wpInputStream = emptyWPStream()) { wpInputStream.readWPString(10); fail("should have thrown EOF"); } catch (EOFException e) { //swallow } }
public static <T, R> CheckedFunction0<R> andThen(CheckedFunction0<T> function, CheckedFunction2<T, Throwable, R> handler) { return () -> { try { return handler.apply(function.apply(), null); } catch (Throwable throwable) { return handler.apply(null...
@Test public void shouldRecoverFromResult() throws Throwable { CheckedFunction0<String> callable = () -> "Wrong Result"; CheckedFunction0<String> callableWithRecovery = VavrCheckedFunctionUtils.andThen(callable, (result, ex) -> { if(result.equals("Wrong Result")){ return...
public String run() throws IOException { Process process = new ProcessBuilder(mCommand).redirectErrorStream(true).start(); BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.defaultCharset())); try { // read the output...
@Test public void execCommandFail() throws Exception { mExceptionRule.expect(ShellUtils.ExitCodeException.class); // run a command that guarantees to fail String[] cmd = new String[]{"bash", "-c", "false"}; String result = new ShellCommand(cmd).run(); assertEquals("false\n", result); }
public String doGetConfig(HttpServletRequest request, HttpServletResponse response, String dataId, String group, String tenant, String tag, String isNotify, String clientIp) throws IOException, ServletException { return doGetConfig(request, response, dataId, group, tenant, tag, isNotify, clientIp, f...
@Test void testDoGetConfigNotExist() throws Exception { // if lockResult equals 0,cache item not exist. configCacheServiceMockedStatic.when(() -> ConfigCacheService.tryConfigReadLock(anyString())).thenReturn(0); MockHttpServletRequest request = new MockHttpServletRequest(); ...
public void tick() { // The main loop does two primary things: 1) drive the group membership protocol, responding to rebalance events // as they occur, and 2) handle external requests targeted at the leader. All the "real" work of the herder is // performed in this thread, which keeps synchroniz...
@Test public void testConnectorPausedRunningTaskOnly() { // even if we don't own the connector, we should still propagate target state // changes to the worker so that tasks will transition correctly when(herder.connectorType(anyMap())).thenReturn(ConnectorType.SOURCE); when(member....
public SendResult putMessageToRemoteBroker(MessageExtBrokerInner messageExt, String brokerNameToSend) { if (this.brokerController.getBrokerConfig().getBrokerName().equals(brokerNameToSend)) { // not remote broker return null; } final boolean isTransHalfMessage = TransactionalMessageU...
@Test public void testPutMessageToRemoteBroker_specificBrokerName_equals() throws Exception { escapeBridge.putMessageToRemoteBroker(new MessageExtBrokerInner(), BROKER_NAME); verify(topicRouteInfoManager, times(0)).tryToFindTopicPublishInfo(anyString()); }
public MetricsBuilder protocol(String protocol) { this.protocol = protocol; return getThis(); }
@Test void protocol() { MetricsBuilder builder = MetricsBuilder.newBuilder(); builder.protocol("test"); Assertions.assertEquals("test", builder.build().getProtocol()); }
List<String> liveKeysAsOrderedList() { return new ArrayList<String>(liveMap.keySet()); }
@Test public void empty0() { long now = 3000; tracker.removeStaleComponents(now); assertEquals(0, tracker.liveKeysAsOrderedList().size()); assertEquals(0, tracker.getComponentCount()); }
@NonNull @Override public String getId() { return ID; }
@Test public void getRepositoriesWithoutCredentialId() throws IOException, UnirestException { createCredential(BitbucketServerScm.ID); Map repoResp = new RequestBuilder(baseUrl) .crumb(crumb) .status(200) .jwtToken(getJwtToken(j.jenkins, authenticatedUser.getId(),...
@JsonIgnore public ValidationResult validate(@Nullable EventDefinitionDto oldEventDefinitionDto, EventDefinitionConfiguration eventDefinitionConfiguration) { final ValidationResult validation = new ValidationResult(); if (title().isEmpty()) { validat...
@Test public void testValidEventDefinition() { final ValidationResult validationResult = validate(testSubject); assertThat(validationResult.failed()).isFalse(); assertThat(validationResult.getErrors().size()).isEqualTo(0); }
@Override public boolean assign(final Map<ProcessId, ClientState> clients, final Set<TaskId> allTaskIds, final Set<TaskId> statefulTaskIds, final AssignmentConfigs configs) { final int numStandbyReplicas = configs.numStandbyReplic...
@Test public void shouldDistributeStandbyTasksOnLeastLoadedClientsWhenClientsAreNotOnDifferentTagDimensions() { final Map<ProcessId, ClientState> clientStates = mkMap( mkEntry(PID_1, createClientStateWithCapacity(PID_1, 3, mkMap(mkEntry(CLUSTER_TAG, CLUSTER_1), mkEntry(ZONE_TAG, ZONE_1)), TASK_0...
public static boolean isValidRule(GatewayFlowRule rule) { if (rule == null || StringUtil.isBlank(rule.getResource()) || rule.getResourceMode() < 0 || rule.getGrade() < 0 || rule.getCount() < 0 || rule.getBurst() < 0 || rule.getControlBehavior() < 0) { return false; } ...
@Test public void testIsValidRule() { GatewayFlowRule bad1 = new GatewayFlowRule(); GatewayFlowRule bad2 = new GatewayFlowRule("abc") .setIntervalSec(0); GatewayFlowRule bad3 = new GatewayFlowRule("abc") .setParamItem(new GatewayParamFlowItem() .setPar...
@Override protected FailureAnalysis analyze(Throwable rootFailure, ConfigDataMissingEnvironmentPostProcessor.ImportException cause) { String description; if (cause.missingPrefix) { description = "The spring.config.import property is missing a " + PolarisConfigDataLocationResolver.PREFIX + " entry"; } e...
@Test public void failureAnalyzerTest() { SpringApplication app = mock(SpringApplication.class); MockEnvironment environment = new MockEnvironment(); PolarisConfigDataMissingEnvironmentPostProcessor processor = new PolarisConfigDataMissingEnvironmentPostProcessor(); assertThatThrownBy(() -> processor.postProce...
@Override public TenantDO getTenantByName(String name) { return tenantMapper.selectByName(name); }
@Test public void testGetTenantByName() { // mock 数据 TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setName("芋道")); tenantMapper.insert(dbTenant);// @Sql: 先插入出一条存在的数据 // 调用 TenantDO result = tenantService.getTenantByName("芋道"); // 校验存在 assertPojoEquals...
public void setNeedClientAuth(Boolean needClientAuth) { this.needClientAuth = needClientAuth; }
@Test public void testSetNeedClientAuth() throws Exception { configuration.setNeedClientAuth(true); configuration.configure(configurable); assertTrue(configurable.isNeedClientAuth()); }
protected CompletableFuture<Void> scheduleJob(final Instant runAt, @Nullable final byte[] jobData) { return Mono.fromFuture(() -> scheduleJob(buildRunAtAttribute(runAt), runAt.plus(jobExpiration), jobData)) .retryWhen(Retry.backoff(8, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4))) .toFutu...
@Test void scheduleJob() { final TestJobScheduler scheduler = new TestJobScheduler(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), DynamoDbExtensionSchema.Tables.SCHEDULED_JOBS.tableName(), Clock.fixed(CURRENT_TIME, ZoneId.systemDefault())); assertDoesNotThrow(() -> scheduler.scheduleJo...
public InetSocketAddress updateConnectAddr( String hostProperty, String addressProperty, String defaultAddressValue, InetSocketAddress addr) { final String host = get(hostProperty); final String connectHostPort = getTrimmed(addressProperty, defaultAddressValue); if (host == null ||...
@Test public void testUpdateSocketAddress() throws IOException { InetSocketAddress addr = NetUtils.createSocketAddrForHost("host", 1); InetSocketAddress connectAddr = conf.updateConnectAddr("myAddress", addr); assertEquals(connectAddr.getHostName(), addr.getHostName()); addr = new InetSocketAddress(1...
@Override public Map<String, FailoverData> getFailoverData() { if (Boolean.parseBoolean(switchParams.get(FAILOVER_MODE_PARAM))) { return serviceMap; } return new ConcurrentHashMap<>(0); }
@Test void testGetFailoverDataForFailoverDisabled() { Map<String, FailoverData> actual = dataSource.getFailoverData(); assertTrue(actual.isEmpty()); }
public KafkaMetadataState computeNextMetadataState(KafkaStatus kafkaStatus) { KafkaMetadataState currentState = metadataState; metadataState = switch (currentState) { case KRaft -> onKRaft(kafkaStatus); case ZooKeeper -> onZooKeeper(kafkaStatus); case KRaftMigration -...
@Test public void testFromKRaftDualWritingToKRaftPostMigration() { Kafka kafka = new KafkaBuilder(KAFKA) .editMetadata() .addToAnnotations(Annotations.ANNO_STRIMZI_IO_KRAFT, "migration") .endMetadata() .withNewStatus() ....
@Override public List<ProductCategoryDO> getCategoryList(ProductCategoryListReqVO listReqVO) { return productCategoryMapper.selectList(listReqVO); }
@Test public void testGetCategoryList() { // mock 数据 ProductCategoryDO dbCategory = randomPojo(ProductCategoryDO.class, o -> { // 等会查询到 o.setName("奥特曼"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setParentId(PARENT_ID_NULL); }); productCa...
@Override public int compare(Object o1, Object o2) { if (o1 == null && o2 == null) { return 0; // o1 == o2 } if (o1 == null) { return -1; // o1 < o2 } if (o2 == null) { return 1; // o1 > o2 } return nonNullC...
@Test public void noNulls() { assertTrue("no Nulls", cmp.compare(1, 2) == 42); }
@Override public void clean() { COUNTER_MAP.clear(); GAUGE_MAP.clear(); HISTOGRAM_MAP.clear(); }
@Test public void testClean() throws Exception { prometheusMetricsRegister.clean(); Field field1 = prometheusMetricsRegister.getClass().getDeclaredField("COUNTER_MAP"); field1.setAccessible(true); Map<String, Counter> map1 = (Map<String, Counter>) field1.get(prometheusMetricsRegister...
@Override public List<? extends Instance> listInstances(String namespaceId, String groupName, String serviceName, String clusterName) throws NacosException { Service service = Service.newService(namespaceId, groupName, serviceName); if (!ServiceManager.getInstance().containSingleton(serv...
@Test void testListInstancesNonExistService() throws NacosException { assertThrows(NacosException.class, () -> { catalogServiceV2Impl.listInstances("A", "BB", "CC", "DD"); }); }
@CheckForNull @Override public Set<Path> branchChangedFiles(String targetBranchName, Path rootBaseDir) { return Optional.ofNullable((branchChangedFilesWithFileMovementDetection(targetBranchName, rootBaseDir))) .map(GitScmProvider::extractAbsoluteFilePaths) .orElse(null); }
@Test public void branchChangedFiles_should_not_fail_with_patience_diff_algo() throws IOException { Path gitConfig = worktree.resolve(".git").resolve("config"); Files.write(gitConfig, "[diff]\nalgorithm = patience\n".getBytes(StandardCharsets.UTF_8)); Repository repo = FileRepositoryBuilder.create(worktre...
public static DatabaseType getProtocolType(final DatabaseConfiguration databaseConfig, final ConfigurationProperties props) { Optional<DatabaseType> configuredDatabaseType = findConfiguredDatabaseType(props); if (configuredDatabaseType.isPresent()) { return configuredDatabaseType.get(); ...
@Test void assertGetProtocolTypeFromDataSource() throws SQLException { DataSource datasource = mockDataSource(TypedSPILoader.getService(DatabaseType.class, "PostgreSQL")); DatabaseConfiguration databaseConfig = new DataSourceProvidedDatabaseConfiguration(Collections.singletonMap("foo_ds", datasource...
@Override public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { if (hazelcastInstance instanceof HazelcastInstanceImpl impl) { instance = impl; localMember = instance.node.address.equals(address); logger = instance.node.getLogger(this.getClass().getName(...
@Test public void testSetHazelcastInstance() { MemberImpl member = new MemberImpl(address, MemberVersion.of("3.8.0"), true); assertNull(member.getLogger()); member.setHazelcastInstance(hazelcastInstance); assertNotNull(member.getLogger()); }
@Override public List<String> splitAndEvaluate() { try (ReflectContext context = new ReflectContext(JAVA_CLASSPATH)) { if (Strings.isNullOrEmpty(inlineExpression)) { return Collections.emptyList(); } return flatten(evaluate(context, GroovyUtils.split(handl...
@Test void assertEvaluateForExpressionPlaceHolder() { List<String> expected = createInlineExpressionParser("t_$->{[\"new$->{1+2}\",'old']}_order_$->{1..2}").splitAndEvaluate(); assertThat(expected.size(), is(4)); assertThat(expected, hasItems("t_new3_order_1", "t_new3_order_2", "t_old_order_...
public Iterable<InputChannel> inputChannels() { return () -> new Iterator<InputChannel>() { private final Iterator<Map<InputChannelInfo, InputChannel>> mapIterator = inputChannels.values().iterator(); private Iterator<InputChan...
@Test void testSingleInputGateInfo() { final int numSingleInputGates = 2; final int numInputChannels = 3; for (int i = 0; i < numSingleInputGates; i++) { final SingleInputGate gate = new SingleInputGateBuilder() .setSingleInputGate...