focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static void main(String[] args) throws Exception { // construct a new executor that will run async tasks var executor = new ThreadAsyncExecutor(); // start few async tasks with varying processing times, two last with callback handlers final var asyncResult1 = executor.startProcess(lazyval(10, 50...
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
public static SchemaPairCompatibility checkReaderWriterCompatibility(final Schema reader, final Schema writer) { final SchemaCompatibilityResult compatibility = new ReaderWriterCompatibilityChecker().getCompatibility(reader, writer); final String message; switch (compatibility.getCompatibility()) {...
@Test void validateSchemaPairMissingSecondField() { final List<Schema.Field> readerFields = list(new Schema.Field("oldfield2", STRING_SCHEMA, null, null)); final Schema reader = Schema.createRecord(null, null, null, false, readerFields); final SchemaCompatibility.SchemaPairCompatibility expectedResult = n...
@Override public void getClient(Request request, RequestContext requestContext, Callback<TransportClient> clientCallback) { URI uri = request.getURI(); debug(_log, "get client for uri: ", uri); if (!D2_SCHEME_NAME.equalsIgnoreCase(uri.getScheme())) { throw new IllegalArgumentException("Unsupp...
@Test (expectedExceptions = ServiceUnavailableException.class) @SuppressWarnings("deprecation") public void testGetClient() throws Exception { Map<String, LoadBalancerStrategyFactory<? extends LoadBalancerStrategy>> loadBalancerStrategyFactories = new HashMap<>(); Map<String, TransportClientFacto...
@Override public String toString() { return ", " + column; }
@Test void assertGeneratedKeyInsertColumnTokenTest() { assertThat(generatedKeyInsertColumnToken.toString(), is(", id")); }
@Override public String buildContext() { final String selector = ((Collection<?>) getSource()) .stream() .map(s -> ((ResourceDO) s).getTitle()) .collect(Collectors.joining(",")); return String.format("the resource [%s] is %s", selector, StringUtils.low...
@Test public void resourceCreateBuildContextTest() { BatchResourceCreatedEvent createdEvent = new BatchResourceCreatedEvent(Arrays.asList(one, two), "test-operator"); String context = String.format("the resource [%s] is %s", one.getTitle() + "," + two.getTitle(), StringUtils.lowerCa...
void prepareAndDumpMetadata(String taskId) { Map<String, String> metadata = new LinkedHashMap<>(); metadata.put("projectKey", moduleHierarchy.root().key()); metadata.put("serverUrl", server.getPublicRootUrl()); metadata.put("serverVersion", server.getVersion()); properties.branch().ifPresent(branch...
@Test public void dump_information_to_custom_path() { underTest.prepareAndDumpMetadata("TASK-123"); assertThat(properties.metadataFilePath()).exists(); assertThat(logTester.logs(Level.DEBUG)).contains("Report metadata written to " + properties.metadataFilePath()); }
protected String changeInboundMessage(String currentEnvelope){ return currentEnvelope; }
@Test public void changeEnvelopMessageInbound() throws IOException { Message message = new MessageImpl(); ByteArrayInputStream inputStream = new ByteArrayInputStream("Test".getBytes(StandardCharsets.UTF_8)); message.setContent(InputStream.class, inputStream); Exchange exchange = new ...
public List<T> findCycle() { resetState(); for (T vertex : graph.getVertices()) { if (colors.get(vertex) == WHITE) { if (visitDepthFirst(vertex, new ArrayList<>(List.of(vertex)))) { if (cycle == null) throw new IllegalStateException("Null cycle - this shou...
@Test void leading_nodes_are_stripped_from_cycle() { var graph = new Graph<Vertices>(); graph.edge(A, B); graph.edge(B, C); graph.edge(C, B); var cycleFinder = new CycleFinder<>(graph); assertTrue(cycleFinder.findCycle().containsAll(List.of(B, C, B))); }
public List<String[]> getPathHostMappings() { return pathHostMappings; }
@Test public void testHostMapping() { ExternalServiceConfig config = new ExternalServiceConfig(); assert config.getPathHostMappings().size() == 4; if (config.getPathHostMappings() != null) { for (String[] parts : config.getPathHostMappings()) { if ("/sharepoint"....
static PendingRestarts triggerPendingRestarts(Function<Set<String>, ServiceListResponse> convergenceChecker, BiConsumer<ApplicationId, Set<String>> restarter, ApplicationId id, ...
@Test void testMaintenance() { // Nothing happens with no pending restarts. assertSame(PendingRestarts.empty(), triggerPendingRestarts(hosts -> { fail("Should not be called"); return null; }, (id, hosts) -> { fail("Should not be called"); ...
public RuntimeOptionsBuilder parse(String... args) { return parse(Arrays.asList(args)); }
@Test void creates_html_formatter() { RuntimeOptions options = parser .parse("--plugin", "html:target/deeply/nested.html", "--glue", "somewhere") .build(); Plugins plugins = new Plugins(new PluginFactory(), options); plugins.setEventBusOnEventListenerPlugins(n...
public static boolean del(Path path) throws IORuntimeException { if (Files.notExists(path)) { return true; } try { if (isDirectory(path)) { Files.walkFileTree(path, DelVisitor.INSTANCE); } else { delFile(path); } } catch (IOException e) { throw new IORuntimeException(e); } return tru...
@Test @Disabled public void delDirTest(){ PathUtil.del(Paths.get("d:/test/looly")); }
@Around("@annotation(com.linecorp.flagship4j.javaflagr.annotations.ControllerFeatureToggle)") public Object processControllerFeatureToggleAnnotation(ProceedingJoinPoint joinPoint) throws Throwable { log.info("start processing controllerFeatureToggle annotation"); MethodSignature signature = (MethodS...
@Test public void processFlagrMethodWithControllerFeatureToggleTestWhenReturnedFlagKeyIsFalseFlagrApiNotFoundException() { String methodName = "methodWithControllerFeatureToggleWithoutVariantKey"; FlagrAnnotationTest flagrAnnotationTest = new FlagrAnnotationTest(); Method method = Arrays.str...
static String getRelativeFileInternal(File canonicalBaseFile, File canonicalFileToRelativize) { List<String> basePath = getPathComponents(canonicalBaseFile); List<String> pathToRelativize = getPathComponents(canonicalFileToRelativize); //if the roots aren't the same (i.e. different drives on a ...
@Test public void pathUtilTest13() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some"); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "dir2" + File.separatorChar); String path = PathUtil.getRelativeFile...
@Override public <Request extends RequestCommand> boolean serializeContent(Request request, InvokeContext invokeContext) throws SerializationException { if (request instanceof RpcRequestCommand) { RpcRequestCommand requestCommand = (RpcRequestCommand) request; RpcInvokeContex...
@Test public void serializeResponseContent() { String traceId = "traceId"; String rpcId = "rpcId"; RpcInternalContext.getContext().setAttachment("_trace_id", traceId); RpcInternalContext.getContext().setAttachment("_span_id", rpcId); RpcResponseCommand command = new RpcRespo...
private static void connectAllToAll( ExecutionJobVertex jobVertex, IntermediateResult result, JobVertexInputInfo jobVertexInputInfo) { // check the vertex input info is legal jobVertexInputInfo .getExecutionVertexInputInfos() .forEach( ...
@Test void testConnectAllToAll() throws Exception { int upstream = 3; int downstream = 2; // use dynamic graph to specify the vertex input info ExecutionGraph eg = setupExecutionGraph(upstream, downstream, POINTWISE, true); List<ExecutionVertexInputInfo> executionVertexInpu...
static Map<Integer, List<Integer>> parseReplicaAssignment(String replicaAssignmentList) { String[] partitionList = replicaAssignmentList.split(","); Map<Integer, List<Integer>> ret = new LinkedHashMap<>(); for (int i = 0; i < partitionList.length; i++) { List<Integer> brokerList = Ar...
@Test public void testParseAssignmentDuplicateEntries() { assertThrows(AdminCommandFailedException.class, () -> TopicCommand.parseReplicaAssignment("5:5")); }
@Override public Optional<SimpleLock> lock(LockConfiguration lockConfiguration) { if (lockConfiguration.getLockAtMostFor().compareTo(minimalLockAtMostFor) < 0) { throw new IllegalArgumentException( "Can not use KeepAliveLockProvider with lockAtMostFor shorter than " + minimal...
@Test void shouldFailForShortLockAtMostFor() { assertThatThrownBy(() -> provider.lock(new LockConfiguration(now(), "short", ofMillis(100), ZERO))) .isInstanceOf(IllegalArgumentException.class); }
@Override public int choosePartition(Message<?> msg, TopicMetadata metadata) { // If the message has a key, it supersedes the single partition routing policy if (msg.hasKey()) { return signSafeMod(hash.makeHash(msg.getKey()), metadata.numPartitions()); } return partition...
@Test public void testChoosePartitionWithKey() { String key1 = "key1"; String key2 = "key2"; Message<?> msg1 = mock(Message.class); when(msg1.hasKey()).thenReturn(true); when(msg1.getKey()).thenReturn(key1); Message<?> msg2 = mock(Message.class); when(msg2.has...
public static Slice add(Slice left, Slice right) { Slice result = unscaledDecimal(); add(left, right, result); return result; }
@Test public void testAdd() { assertEquals(add(unscaledDecimal(0), unscaledDecimal(0)), unscaledDecimal(0)); assertEquals(add(unscaledDecimal(1), unscaledDecimal(0)), unscaledDecimal(1)); assertEquals(add(unscaledDecimal(1), unscaledDecimal(1)), unscaledDecimal(2)); assertEquals...
public static RuleDescriptionSectionContextDto of(String key, String displayName) { return new RuleDescriptionSectionContextDto(key, displayName); }
@Test void equals_with_one_null_objet_should_return_false() { RuleDescriptionSectionContextDto context1 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME); assertThat(context1).isNotEqualTo(null); }
public CompletableFuture<Void> commitAsync(final Map<TopicPartition, OffsetAndMetadata> offsets) { if (offsets.isEmpty()) { log.debug("Skipping commit of empty offsets"); return CompletableFuture.completedFuture(null); } OffsetCommitRequestState commitRequest = createOffs...
@Test public void testAsyncCommitWhileCoordinatorUnknownIsSentOutWhenCoordinatorDiscovered() { CommitRequestManager commitRequestManager = create(false, 0); assertPoll(false, 0, commitRequestManager); Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>(); offsets.put(new ...
void appendValuesClause(StringBuilder sb) { sb.append("VALUES "); appendValues(sb, jdbcTable.dbFieldNames().size()); }
@Test void appendValuesClause() { MSSQLUpsertQueryBuilder builder = new MSSQLUpsertQueryBuilder(jdbcTable, dialect); StringBuilder sb = new StringBuilder(); builder.appendValuesClause(sb); String valuesClause = sb.toString(); assertThat(valuesClause).isEqualTo("VALUES (?, ?)...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test(description = "Responses with ref") public void testResponseWithRef() { Components components = new Components(); components.addResponses("invalidJWT", new ApiResponse().description("when JWT token invalid/expired")); OpenAPI oas = new OpenAPI() .info(new Info().descrip...
@Override public Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { if(containerService.isContainer(source)) { if(new SimplePathPredicate(sourc...
@Test public void testMoveFromEncryptedDataRoom() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room1 = new SDSDirectoryFeature(session, nodeid).createRoom( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type....
private int getVolumeReport(String[] argv, int i) throws IOException { ClientDatanodeProtocol datanode = getDataNodeProxy(argv[i]); List<DatanodeVolumeInfo> volumeReport = datanode .getVolumeReport(); System.out.println("Active Volumes : " + volumeReport.size()); for (DatanodeVolumeInfo info : v...
@Test(timeout = 30000) public void testGetVolumeReport() throws Exception { redirectStream(); final DFSAdmin dfsAdmin = new DFSAdmin(conf); for (int i = 0; i < cluster.getDataNodes().size(); i++) { resetStream(); final DataNode dn = cluster.getDataNodes().get(i); final String addr = Str...
public String getQuery() throws Exception { return getQuery(weatherConfiguration.getLocation()); }
@Test public void testBoxedQuery() throws Exception { WeatherConfiguration weatherConfiguration = new WeatherConfiguration(); weatherConfiguration.setLon("4"); weatherConfiguration.setLat("52"); weatherConfiguration.setRightLon("6"); weatherConfiguration.setTopLat("54"); ...
static Optional<File> getFileFromURL(URL retrieved) { logger.debug("getFileFromURL {}", retrieved); logger.debug("retrieved.getProtocol() {}", retrieved.getProtocol()); if (logger.isDebugEnabled()) { debugURLContent(retrieved); } logger.debug("retrieved.getPath() {}",...
@Test void getFileFromURL() throws IOException { URL url = getJarUrl(); assertThat(url).isNotNull(); Optional<File> retrieved = MemoryFileUtils.getFileFromURL(url); assertThat(retrieved).isNotNull().isPresent(); assertThat(retrieved.get()).isInstanceOf(MemoryFile.class); ...
public static void sortMessages(Message[] messages, final SortTerm[] sortTerm) { final List<SortTermWithDescending> sortTermsWithDescending = getSortTermsWithDescending(sortTerm); sortMessages(messages, sortTermsWithDescending); }
@Test public void testSortMessagesWithTie() { Message[] given = new Message[] { MESSAGES[2], TIE_BREAKER }; // Sort according to the whole list. Only the last element breaks the tie Message[] actual1 = given.clone(); MailSorter.sortMessages(actual1, POSSIBLE_TERMS); assertAr...
@Override public String toString() { return toHexString(); }
@Test public void shouldCreateFromHexString() { String value = "12FF841344567899"; ByteArray byteArray = new ByteArray(value); assertThat(byteArray.toString(), is(value.toLowerCase())); }
@Override public Tuple apply(Object input) { checkArgument(fieldsOrProperties != null, "The names of the fields/properties to read should not be null"); checkArgument(fieldsOrProperties.length > 0, "The names of the fields/properties to read should not be empty"); checkArgument(input != null, "The object ...
@Test void should_extract_tuples_from_fields_or_properties() { // GIVEN ByNameMultipleExtractor underTest = new ByNameMultipleExtractor("id", "age"); // WHEN Tuple result = underTest.apply(YODA); // THEN then(result).isEqualTo(tuple(1L, 800)); }
@Override public void store(Measure newMeasure) { saveMeasure(newMeasure.inputComponent(), (DefaultMeasure<?>) newMeasure); }
@Test public void shouldFailIfUnknownMetric() { InputFile file = new TestInputFileBuilder("foo", "src/Foo.php").build(); assertThatThrownBy(() -> underTest.store(new DefaultMeasure() .on(file) .forMetric(CoreMetrics.LINES) .withValue(10))) .isInstanceOf(UnsupportedOperationException.c...
static JarFileWithEntryClass findOnlyEntryClass(Iterable<File> jarFiles) throws IOException { List<JarFileWithEntryClass> jarsWithEntryClasses = new ArrayList<>(); for (File jarFile : jarFiles) { findEntryClass(jarFile) .ifPresent( entryClass -...
@Test void testFindOnlyEntryClassMultipleJarsWithMultipleManifestEntries() throws IOException { assertThatThrownBy( () -> { File jarFile = TestJob.getTestJobJar(); JarManifestParser.findOnlyEntryClass( ...
@Override public Collection<Identity> getIdentities() { if(null == proxy) { log.warn("Missing proxy reference"); return Collections.emptyList(); } if(log.isDebugEnabled()) { log.debug(String.format("Retrieve identities from proxy %s", proxy)); } ...
@Test(expected = AgentProxyException.class) public void testGetIdentities() throws Exception { assumeTrue(Factory.Platform.getDefault().equals(Factory.Platform.Name.mac)); final OpenSSHAgentAuthenticator authenticator = new OpenSSHAgentAuthenticator(StringUtils.EMPTY); final Collection<Ident...
@Override public ParamCheckResponse checkParamInfoList(List<ParamInfo> paramInfos) { ParamCheckResponse paramCheckResponse = new ParamCheckResponse(); if (paramInfos == null) { paramCheckResponse.setSuccess(true); return paramCheckResponse; } for (ParamInfo pa...
@Test void testCheckParamInfoForClusters() { ParamInfo paramInfo = new ParamInfo(); ArrayList<ParamInfo> paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); // Max Length String cluster = buildStringLength(65); paramInfo.setClusters(cluster + "," + cluster); ...
public static int getClusterControllerIndex(ConfigId configId) { Matcher matcher = CONTROLLER_INDEX_PATTERN.matcher(configId.s()); if (!matcher.matches()) { throw new IllegalArgumentException("Unable to extract cluster controller index from config ID " + configId); } return ...
@Test public void testGetClusterControllerIndexWithStandaloneClusterController() { ConfigId configId = new ConfigId("fantasy_sports/standalone/fantasy_sports-controllers/1"); assertEquals(1, VespaModelUtil.getClusterControllerIndex(configId)); }
public static UReturn create(UExpression expression) { return new AutoValue_UReturn(expression); }
@Test public void serialization() { SerializableTester.reserializeAndAssert(UReturn.create(ULiteral.stringLit("foo"))); }
public static CompositeEvictionChecker newCompositeEvictionChecker(CompositionOperator compositionOperator, EvictionChecker... evictionCheckers) { Preconditions.isNotNull(compositionOperator, "composition"); Preconditions.isNotNull(e...
@Test public void resultShouldReturnFalse_whenOneIsFalse_withAndCompositionOperator() { EvictionChecker evictionChecker1ReturnsTrue = mock(EvictionChecker.class); EvictionChecker evictionChecker2ReturnsFalse = mock(EvictionChecker.class); when(evictionChecker1ReturnsTrue.isEvictionRequired(...
public static <T> Write<T> write() { return Write.<T>builder(MutationType.WRITE).build(); }
@Test public void testWrite() { ArrayList<ScientistWrite> data = new ArrayList<>(); for (int i = 0; i < NUM_ROWS; i++) { ScientistWrite scientist = new ScientistWrite(); scientist.id = i; scientist.name = "Name " + i; scientist.department = "bio"; data.add(scientist); } ...
@Override public String rebootOnu(String target) { DriverHandler handler = handler(); NetconfController controller = handler.get(NetconfController.class); MastershipService mastershipService = handler.get(MastershipService.class); DeviceId ncDeviceId = handler.data().deviceId(); ...
@Test public void testValidRebootOnu() throws Exception { String reply; String target; for (int i = ZERO; i < VALID_REBOOT_TCS.length; i++) { target = VALID_REBOOT_TCS[i]; currentKey = i; reply = voltConfig.rebootOnu(target); assertNotNull("In...
@Override public void execute( RunConfiguration runConfiguration, ExecutionConfiguration executionConfiguration, AbstractMeta meta, VariableSpace variableSpace, Repository repository ) throws KettleException { DefaultRunConfiguration defaultRunConfiguration = (DefaultRunConfiguration) runCo...
@Test public void testExecuteLocalTrans() throws Exception { DefaultRunConfiguration defaultRunConfiguration = new DefaultRunConfiguration(); defaultRunConfiguration.setName( "Default Configuration" ); defaultRunConfiguration.setLocal( true ); TransExecutionConfiguration transExecutionConfiguration =...
@Override public FileSystem create(URI fsUri) throws IOException { checkNotNull(fsUri, "fsUri"); final String scheme = fsUri.getScheme(); checkArgument(scheme != null, "file system has null scheme"); // from here on, we need to handle errors due to missing optional // depen...
@Test public void testCreateHadoopFsWithMissingAuthority() throws Exception { final URI uri = URI.create("hdfs:///my/path"); HadoopFsFactory factory = new HadoopFsFactory(); try { factory.create(uri); fail("should have failed with an exception"); } catch (IO...
@Override public Map<String, Object> assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo, Set<String> authScopes) { Map<String, Object> result = newLinkedHashMap(); OAuth2Authentication authentication = accessToken.getAuthenticationHolder().getAuthentication(); result.put(ACTIVE, true); if (...
@Test public void shouldAssembleExpectedResultForAccessTokenWithoutExpiry() { // given OAuth2AccessTokenEntity accessToken = accessToken(null, scopes("foo", "bar"), null, "Bearer", oauth2AuthenticationWithUser(oauth2Request("clientId"), "name")); UserInfo userInfo = userInfo("sub"); Set<String> authScop...
public static long readUint32(ByteBuffer buf) throws BufferUnderflowException { return Integer.toUnsignedLong(buf.order(ByteOrder.LITTLE_ENDIAN).getInt()); }
@Test(expected = ArrayIndexOutOfBoundsException.class) public void testReadUint32ThrowsException1() { ByteUtils.readUint32(new byte[]{1, 2, 3}, 2); }
public List<Analyzer> getAnalyzers() { return getAnalyzers(AnalysisPhase.values()); }
@Test public void testGetExperimentalAnalyzers() { AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader(), getSettings()); List<Analyzer> result = instance.getAnalyzers(); String experimental = "CMake Analyzer"; boolean found = false; bo...
public List<QueryMetadata> sql(final String sql) { return sql(sql, Collections.emptyMap()); }
@Test public void shouldInferTopicWithValidArgs() { // Given: when(schemaInjector.inject(any())).thenAnswer(inv -> inv.getArgument(0)); // When: ksqlContext.sql("Some SQL", SOME_PROPERTIES); // Then: verify(topicInjector, times(2) /* once to validate, once to execute */) .inject(CFG_...
public static NetworkMultiplexer shared(Network net) { return new NetworkMultiplexer(net, true); }
@Test void testShared() { MockNetwork net = new MockNetwork(); MockOwner owner1 = new MockOwner(); MockOwner owner2 = new MockOwner(); NetworkMultiplexer shared = NetworkMultiplexer.shared(net); assertEquals(Set.of(shared), net.attached); assertEquals(Set.of(), net.re...
@Override public TradePriceCalculateRespBO calculatePrice(TradePriceCalculateReqBO calculateReqBO) { // 1.1 获得商品 SKU 数组 List<ProductSkuRespDTO> skuList = checkSkuList(calculateReqBO); // 1.2 获得商品 SPU 数组 List<ProductSpuRespDTO> spuList = checkSpuList(skuList); // 2.1 计算价格 ...
@Test public void testCalculatePrice() { // 准备参数 TradePriceCalculateReqBO calculateReqBO = new TradePriceCalculateReqBO() .setUserId(10L) .setCouponId(20L).setAddressId(30L) .setItems(Arrays.asList( new TradePriceCalculateReqBO....
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof Set)) return false; if (o instanceof RangeSet) { RangeSet integers = (RangeSet) o; return size == integers.size; } else { Set set = (Set) o; ...
@Test public void equals() throws Exception { RangeSet rs = new RangeSet(4); RangeSet rs2 = new RangeSet(5); // Verify equals both ways assertNotEquals(rs, rs2); assertNotEquals(rs2, rs); RangeSet rs3 = new RangeSet(4); assertEquals(rs3, rs); assertEquals(rs, rs3);...
public double calcOrientation(double lat1, double lon1, double lat2, double lon2) { return calcOrientation(lat1, lon1, lat2, lon2, true); }
@Test public void testOrientationExact() { assertEquals(90.0, Math.toDegrees(AC.calcOrientation(0, 0, 1, 0)), 0.01); assertEquals(45.0, Math.toDegrees(AC.calcOrientation(0, 0, 1, 1)), 0.01); assertEquals(0.0, Math.toDegrees(AC.calcOrientation(0, 0, 0, 1)), 0.01); assertEquals(-45.0, ...
@Override public void onNewResourcesAvailable() { checkDesiredOrSufficientResourcesAvailable(); }
@Test void testSchedulingWithSufficientResourcesAfterStabilizationTimeout() { Duration initialResourceTimeout = Duration.ofMillis(-1); Duration stabilizationTimeout = Duration.ofMillis(50_000L); WaitingForResources wfr = new WaitingForResources( ctx, ...
@Override protected <R> EurekaHttpResponse<R> execute(RequestExecutor<R> requestExecutor) { List<EurekaEndpoint> candidateHosts = null; int endpointIdx = 0; for (int retry = 0; retry < numberOfRetries; retry++) { EurekaHttpClient currentHttpClient = delegate.get(); Eu...
@Test public void testRequestsReuseSameConnectionIfThereIsNoError() throws Exception { when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(0)); when(requestExecutor.execute(clusterDelegates.get(0))).thenReturn(EurekaHttpResponse.status(200)); ...
public void runPickle(Pickle pickle) { try { StepTypeRegistry stepTypeRegistry = createTypeRegistryForPickle(pickle); snippetGenerators = createSnippetGeneratorsForPickle(stepTypeRegistry); // Java8 step definitions will be added to the glue here buildBackendWorl...
@Test void backends_are_asked_for_snippets_for_undefined_steps() { Backend backend = mock(Backend.class); when(backend.getSnippet()).thenReturn(new TestSnippet()); ObjectFactory objectFactory = mock(ObjectFactory.class); Runner runner = new Runner(bus, singletonList(backend), objectF...
public static PathSpecSet empty() { return EMPTY; }
@Test public void testEmpty() { PathSpecSet pathSpecSet = PathSpecSet.empty(); Assert.assertEquals(pathSpecSet.getPathSpecs(), Collections.emptySet()); Assert.assertFalse(pathSpecSet.isAllInclusive()); Assert.assertTrue(pathSpecSet.isEmpty()); Assert.assertEquals(pathSpecSet.toArray(), new PathSpe...
@Override public int deduceNumPartitions() { // for source rdd, the partitioner is None final Optional<Partitioner> partitioner = rddData.partitioner(); if (partitioner.isPresent()) { int partPartitions = partitioner.get().numPartitions(); if (partPartitions > 0) { return partPartition...
@Test public void testDeduceNumPartitions() { int numPartitions = 100; jsc.sc().conf().remove("spark.default.parallelism"); SQLConf.get().unsetConf("spark.sql.shuffle.partitions"); // rdd parallelize SQLConf.get().setConfString("spark.sql.shuffle.partitions", "5"); HoodieData<Integer> rddData...
public Optional<AbsoluteUnixPath> getAppRoot() { if (appRoot == null) { return Optional.empty(); } return Optional.of(AbsoluteUnixPath.fromPath(appRoot)); }
@Test public void testParse_appRoot() { War warCommand = CommandLine.populateCommand( new War(), "--target=test-image-ref", "--app-root=/path/to/app", "my-app.war"); assertThat(warCommand.getAppRoot()).hasValue(AbsoluteUnixPath.get("/path/to/app")); }
public Set<String> indexNamesForStreamsInTimeRange(final Set<String> streamIds, final TimeRange timeRange) { Set<String> dataStreamIndices = streamIds.stream() .filter(s -> s.startsWith(Stream.DATASTREAM_PREFIX)) .map(s -> s...
@Test void findsIndicesBelongingToStreamsInTimeRange() { final IndexRange indexRange1 = mockIndexRange("index1"); final IndexRange indexRange2 = mockIndexRange("index2"); final SortedSet<IndexRange> indexRanges = sortedSetOf(indexRange1, indexRange2); final IndexLookup sut = new Ind...
public WorkflowInstanceActionResponse stop( String workflowId, long workflowInstanceId, long workflowRunId, User caller) { return terminate( workflowId, workflowInstanceId, workflowRunId, Actions.WorkflowInstanceAction.STOP, caller); }
@Test public void testInvalidRunId() { when(instance.getWorkflowRunId()).thenReturn(2L); when(instance.getStatus()).thenReturn(WorkflowInstance.Status.IN_PROGRESS); AssertHelper.assertThrows( "run id has to be the latest one", MaestroBadRequestException.class, "Cannot STOP the work...
@Override public TransformResultMetadata getResultMetadata() { return _resultMetadata; }
@Test public void testArrayIndexOfAllLong() { ExpressionContext expression = RequestContextUtils.getExpression( String.format("array_indexes_of_long(%s, 1)", LONG_MV_COLUMN_2)); TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap); assertTrue(transformFunc...
public Certificate add(CvCertificate cert) { final Certificate db = Certificate.from(cert); if (repository.countByIssuerAndSubject(db.getIssuer(), db.getSubject()) > 0) { throw new ClientException(String.format( "Certificate of subject %s and issuer %s already exists", db.ge...
@Test public void shouldNotAddCertificateIfFirstButInvalidSignature() throws Exception { final byte[] der = readFixture("rdw/acc/cvca.cvcert"); der[461] = 2; ClientException thrown = assertThrows(ClientException.class, () -> service.add(mapper.read(der, CvCertificate.class))); asser...
@Override public DistroDataResponse handle(DistroDataRequest request, RequestMeta meta) throws NacosException { try { switch (request.getDataOperation()) { case VERIFY: return handleVerify(request.getDistroData(), meta); case SNAPSHOT: ...
@Test void testHandle() throws NacosException { Mockito.when(distroProtocol.onVerify(Mockito.any(), Mockito.anyString())).thenReturn(false); DistroDataRequest distroDataRequest = new DistroDataRequest(); distroDataRequest.setDataOperation(VERIFY); RequestMeta requestMeta = new Reques...
public void isEmpty() { if (actual == null) { failWithActual(simpleFact("expected an empty string")); } else if (!actual.isEmpty()) { failWithActual(simpleFact("expected to be empty")); } }
@Test public void stringIsEmpty() { assertThat("").isEmpty(); }
@Override public OverlayData createOverlayData(ComponentName remoteApp) { if (!OS_SUPPORT_FOR_ACCENT) { return EMPTY; } try { final ActivityInfo activityInfo = mLocalContext .getPackageManager() .getActivityInfo(remoteApp, PackageManager.GET_META_DATA); ...
@Test public void testGetRawColorsHappyPath() throws Exception { setupReturnedColors(R.style.HappyPathRawColors); final OverlayData overlayData = mUnderTest.createOverlayData(mComponentName); Assert.assertEquals(Color.parseColor("#ffcc9900"), overlayData.getPrimaryColor()); // notice: we also changin...
@Override public void addConfigListener(String dataId, ConfigurationChangeListener listener) { if (StringUtils.isBlank(dataId) || listener == null) { return; } configListenersMap.computeIfAbsent(dataId, key -> ConcurrentHashMap.newKeySet()) .add(listener); ...
@Test void addConfigListener() throws InterruptedException { logger.info("addConfigListener"); ConfigurationFactory.reload(); Configuration fileConfig = ConfigurationFactory.getInstance(); CountDownLatch countDownLatch = new CountDownLatch(1); String dataId = "service.disable...
public Map<String, Collection<Class<? extends ShardingSphereRule>>> getInUsedStorageUnitNameAndRulesMap() { Map<String, Collection<Class<? extends ShardingSphereRule>>> result = new LinkedHashMap<>(); for (ShardingSphereRule each : rules) { Optional<DataSourceMapperRuleAttribute> ruleAttribu...
@Test void assertGetInUsedStorageUnitNameAndRulesMapWhenRulesAreEmpty() { assertTrue(new RuleMetaData(Collections.emptyList()).getInUsedStorageUnitNameAndRulesMap().isEmpty()); }
static BytecodeExpression greaterThanOrEqual(BytecodeExpression left, BytecodeExpression right) { checkArgumentTypes(left, right); OpCode comparisonInstruction; OpCode noMatchJumpInstruction; Class<?> type = left.getType().getPrimitiveType(); if (type == int.class) { ...
@Test public void testGreaterThanOrEqual() throws Exception { assertBytecodeExpression(greaterThanOrEqual(constantInt(3), constantInt(7)), 3 >= 7, "(3 >= 7)"); assertBytecodeExpression(greaterThanOrEqual(constantInt(7), constantInt(3)), 7 >= 3, "(7 >= 3)"); assertBytecodeExpr...
public MultiMap<Value, T, List<T>> search() { if (matcher.isNegate()) { if (map.containsKey(matcher.getValue())) { return MultiMap.merge(map.subMap(map.firstKey(), true, matcher.getValue(), false), ...
@Test void testNegatedNullSearch() throws Exception { search = new ExactMatcherSearch<>(new ExactMatcher(KeyDefinition.newKeyDefinition().withId("value").build(), null, true), map); MultiMap<Value, Object, List<Object>> search1 = search...
public static Stream<MediaType> parseList(String mediaTypeList) { if (mediaTypeList == null || mediaTypeList.isEmpty()) throw CONTAINER.missingMediaType(); Matcher matcher = TREE_PATTERN.matcher(mediaTypeList); List<MediaType> list = new ArrayList<>(); while (true) { MediaType mediaTyp...
@Test public void testParseList() { List<MediaType> mediaTypes = MediaType.parseList("text/html, image/png,*/*").collect(Collectors.toList()); assertEquals(asList(MediaType.TEXT_HTML, MediaType.IMAGE_PNG, MediaType.MATCH_ALL), mediaTypes); Exceptions.expectException(EncodingException.class, () -> ...
@Override public void deleteCategory(Long id) { // 校验分类是否存在 validateProductCategoryExists(id); // 校验是否还有子分类 if (productCategoryMapper.selectCountByParentId(id) > 0) { throw exception(CATEGORY_EXISTS_CHILDREN); } // 校验分类是否绑定了 SPU Long spuCount = pro...
@Test public void testDeleteCategory_success() { // mock 数据 ProductCategoryDO dbCategory = randomPojo(ProductCategoryDO.class); productCategoryMapper.insert(dbCategory);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbCategory.getId(); // 调用 productCategoryService.de...
static JobManagerProcessSpec processSpecFromConfig(Configuration config) { return createMemoryProcessSpec(PROCESS_MEMORY_UTILS.memoryProcessSpecFromConfig(config)); }
@Test void testConfigJvmHeapMemory() { MemorySize jvmHeapSize = MemorySize.parse("50m"); Configuration conf = new Configuration(); conf.set(JobManagerOptions.JVM_HEAP_MEMORY, jvmHeapSize); JobManagerProcessSpec jobManagerProcessSpec = JobManagerProcessUtils.processS...
@VisibleForTesting Iterable<SnapshotContext> getSnapshots(Iterable<Snapshot> snapshots, SnapshotContext since) { List<SnapshotContext> result = Lists.newArrayList(); boolean foundSince = Objects.isNull(since); for (Snapshot snapshot : snapshots) { if (!foundSince) { if (snapshot.snapshotId(...
@Test public void testGetSnapshotContextsReturnsEmptyIterableWhenTableIsEmptyAndGivenSnapShotIsNull() { HiveIcebergStorageHandler storageHandler = new HiveIcebergStorageHandler(); Iterable<SnapshotContext> result = storageHandler.getSnapshots(Collections.emptyList(), null); assertThat(result.iterator().h...
public void writeUbyte(int value) throws IOException { if (value < 0 || value > 0xFF) { throw new ExceptionWithContext("Unsigned byte value out of range: %d", value); } write(value); }
@Test public void testWriteUbyte() throws IOException { writer.writeUbyte(0); writer.writeUbyte(1); writer.writeUbyte(0x12); writer.writeUbyte(0xFF); expectData(0x00, 0x01, 0x12, 0xFF); }
@Override public int choosePartition(Message msg, TopicMetadata metadata) { // if key is specified, we should use key as routing; // if key is not specified and no sequence id is provided, not an effectively-once publish, use the default // round-robin routing. if (msg.hasKey() || ms...
@Test public void testChoosePartitionWithoutKeySequenceId() { TopicMetadata topicMetadata = mock(TopicMetadata.class); when(topicMetadata.numPartitions()).thenReturn(5); Clock clock = mock(Clock.class); FunctionResultRouter router = new FunctionResultRouter(0, clock); for (...
@Override @DataPermission(enable = false) // 发送短信时,无需考虑数据权限 public Long sendSingleSmsToAdmin(String mobile, Long userId, String templateCode, Map<String, Object> templateParams) { // 如果 mobile 为空,则加载用户编号对应的手机号 if (StrUtil.isEmpty(mobile)) { AdminUserDO user = adminUserService.getUser...
@Test public void testSendSingleSmsToAdmin() { // 准备参数 Long userId = randomLongId(); String templateCode = randomString(); Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234") .put("op", "login").build(); // mock adminUser...
@Override public Message receive() { Message message = delegate.receive(); handleReceive(message); return message; }
@Test void receive_continues_parent_trace_single_header() throws Exception { ActiveMQTextMessage message = new ActiveMQTextMessage(); message.setStringProperty("b3", B3SingleFormat.writeB3SingleFormatWithoutParentId(parent)); receive(message); // Ensure the current span in on the message, not the pare...
@Override public double getDoubleValue() { checkValueType(DOUBLE); return measure.getDoubleValue(); }
@Test public void fail_with_ISE_when_not_double_value() { assertThatThrownBy(() -> { MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1)); measure.getDoubleValue(); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Value can not be converted to double b...
@Override public void commitJob(JobContext jobContext) throws IOException { Configuration conf = jobContext.getConfiguration(); syncFolder = conf.getBoolean(DistCpConstants.CONF_LABEL_SYNC_FOLDERS, false); overwrite = conf.getBoolean(DistCpConstants.CONF_LABEL_OVERWRITE, false); updateRoot = c...
@Test public void testAtomicCommitExistingFinal() throws IOException { TaskAttemptContext taskAttemptContext = getTaskAttemptContext(config); JobContext jobContext = new JobContextImpl(taskAttemptContext.getConfiguration(), taskAttemptContext.getTaskAttemptID().getJobID()); Configuration conf = jo...
@Override public String getName() { if (_distinctResult == 1) { return TransformFunctionType.IS_DISTINCT_FROM.getName(); } return TransformFunctionType.IS_NOT_DISTINCT_FROM.getName(); }
@Test public void testDistinctFromRightNull() throws Exception { ExpressionContext expression = RequestContextUtils.getExpression(String.format(_expression, INT_SV_COLUMN, INT_SV_NULL_COLUMN)); TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap); As...
@Override @SuppressWarnings("unchecked") public int run() throws IOException { RewriteOptions options = buildOptionsOrFail(); ParquetRewriter rewriter = new ParquetRewriter(options); rewriter.processBlocks(); rewriter.close(); return 0; }
@Test public void testRewriteCommandWithOverwrite() throws IOException { File file = parquetFile(); RewriteCommand command = new RewriteCommand(createLogger()); command.inputs = Arrays.asList(file.getAbsolutePath()); File output = new File(getTempFolder(), "converted.parquet"); command.output = ou...
public void save(final ScheduleTask scheduleTask) { String sql = "INSERT INTO schedule_task (task_id, execution_time, status) VALUES (:taskId, :executionTime, :status)"; MapSqlParameterSource parameters = new MapSqlParameterSource() .addValue("taskId", scheduleTask.getTaskId()) ...
@Test void 태스크를_저장한다() { // when & then Assertions.assertDoesNotThrow(() -> scheduleTaskJdbcRepository.save(스케줄_생성_진행중())); }
@Override public Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { if(containerService.isContainer(source)) { if(new SimplePathPredicate(sourc...
@Test public void testMoveBetweenEncryptedDataRooms() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room1 = new SDSDirectoryFeature(session, nodeid).createRoom( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.T...
@Udf(description = "Returns a new string with all occurences of oldStr in str with newStr") public String replace( @UdfParameter( description = "The source string. If null, then function returns null.") final String str, @UdfParameter( description = "The substring to replace." ...
@Test public void shouldHandleNull() { assertThat(udf.replace(null, "foo", "bar"), isEmptyOrNullString()); assertThat(udf.replace("foo", null, "bar"), isEmptyOrNullString()); assertThat(udf.replace("foo", "bar", null), isEmptyOrNullString()); }
Callable<Path> download(Path destDirPath, LocalResource rsrc, UserGroupInformation ugi) throws IOException { // For private localization FsDownload creates folder in destDirPath. Parent // directories till user filecache folder is created here. if (rsrc.getVisibility() == LocalResourceVisibility.PRIVA...
@Test(timeout = 10000) public void testUserCacheDirPermission() throws Exception { Configuration conf = new Configuration(); conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "077"); FileContext lfs = FileContext.getLocalFSFileContext(conf); Path fileCacheDir = lfs.makeQualified(new Path(base...
public boolean commitOffsetsSync(Map<TopicPartition, OffsetAndMetadata> offsets, Timer timer) { invokeCompletedOffsetCommitCallbacks(); if (offsets.isEmpty()) { // We guarantee that the callbacks for all commitAsync() will be invoked when // commitSync() completes, even if the u...
@Test public void testCommitOffsetIllegalGeneration() { // we cannot retry if a rebalance occurs before the commit completed client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE)); prepareOffsetCommitReques...
public ServiceBusConfiguration getConfiguration() { return configuration; }
@Test void testCreateEndpointWithAzureIdentity() throws Exception { final String uri = "azure-servicebus://testTopicOrQueue"; final String remaining = "testTopicOrQueue"; final String fullyQualifiedNamespace = "namespace.servicebus.windows.net"; final TokenCredential credential = new...
public void wrap(final byte[] buffer) { capacity = buffer.length; addressOffset = ARRAY_BASE_OFFSET; byteBuffer = null; wrapAdjustment = 0; if (buffer != byteArray) { byteArray = buffer; } }
@Test void shouldExposePositionAtWhichHeapByteBufferGetsWrapped() { final ByteBuffer wibbleByteBuffer = ByteBuffer.wrap(wibbleBytes); shouldExposePositionAtWhichByteBufferGetsWrapped(wibbleByteBuffer); }
@CanDistro @PutMapping("/beat") @TpsControl(pointName = "HttpHealthCheck", name = "HttpHealthCheck") @Secured(action = ActionTypes.WRITE) @ExtractorManager.Extractor(httpExtractor = NamingInstanceBeatHttpParamExtractor.class) public ObjectNode beat(@RequestParam(defaultValue = Constants.DEFAULT_NAME...
@Test void beat() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put( UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + "/beat") .param("namespaceId", TEST_NAMESPACE).param("serviceName...
@Override public Set<NodeHealth> readAll() { long clusterTime = hzMember.getClusterTime(); long timeout = clusterTime - TIMEOUT_30_SECONDS; Map<UUID, TimestampedNodeHealth> sqHealthState = readReplicatedMap(); Set<UUID> hzMemberUUIDs = hzMember.getMemberUuids(); Set<NodeHealth> existingNodeHealths...
@Test public void readAll_logs_map_sq_health_state_content_and_the_content_effectively_returned_if_TRACE() { logging.setLevel(Level.TRACE); Map<UUID, TimestampedNodeHealth> map = new HashMap<>(); UUID uuid = UUID.randomUUID(); NodeHealth nodeHealth = randomNodeHealth(); map.put(uuid, new Timestamp...
@VisibleForTesting void clearCurrentDirectoryChangedListenersWhenImporting( boolean importfile, JobMeta jobMeta ) { if ( importfile ) { jobMeta.clearCurrentDirectoryChangedListeners(); } }
@Test public void testClearCurrentDirectoryChangedListenersWhenNotImporting() { JobMeta jm = mock( JobMeta.class ); jobFileListener.clearCurrentDirectoryChangedListenersWhenImporting( false, jm ); verify( jm, times( 0 ) ).clearCurrentDirectoryChangedListeners(); }
@Override public AverageCounter createNewCounter() { return new AverageCounter(); }
@Test public void check_new_counter_class() { assertThat(BASIC_AVERAGE_FORMULA.createNewCounter().getClass()).isEqualTo(AverageFormula.AverageCounter.class); }
public static <K, V> WithKeys<K, V> of(SerializableFunction<V, K> fn) { checkNotNull( fn, "WithKeys constructed with null function. Did you mean WithKeys.of((Void) null)?"); return new WithKeys<>(fn, null); }
@Test public void testWithKeysGetName() { assertEquals("WithKeys", WithKeys.<Integer, String>of(100).getName()); }
public ServerHealthState trump(ServerHealthState otherServerHealthState) { int result = healthStateLevel.compareTo(otherServerHealthState.healthStateLevel); return result > 0 ? this : otherServerHealthState; }
@Test public void shouldNotTrumpWarningIfCurrentIsSuccess() { assertThat(WARNING_SERVER_HEALTH_STATE.trump(SUCCESS_SERVER_HEALTH_STATE), is(WARNING_SERVER_HEALTH_STATE)); }
public void start() { if (stateUpdaterThread == null) { if (!restoredActiveTasks.isEmpty() || !exceptionsAndFailedTasks.isEmpty()) { throw new IllegalStateException("State updater started with non-empty output queues. " + BUG_ERROR_MESSAGE); } ...
@Test public void shouldNotPausingNonExistTasks() throws Exception { stateUpdater.start(); when(topologyMetadata.isPaused(null)).thenReturn(true); verifyPausedTasks(); verifyRestoredActiveTasks(); verifyUpdatingTasks(); verifyExceptionsAndFailedTasks(); }
@Override public boolean put(PageId pageId, ByteBuffer page, CacheContext cacheContext) { LOG.debug("put({},{} bytes) enters", pageId, page.remaining()); if (mState.get() != READ_WRITE) { Metrics.PUT_NOT_READY_ERRORS.inc(); Metrics.PUT_ERRORS.inc(); return false; } int originPosition...
@Test public void evictBigPagesByPutSmallPage() throws Exception { mConf.set(PropertyKey.USER_CLIENT_CACHE_SIZE, String.valueOf(PAGE_SIZE_BYTES)); mCacheManager = createLocalCacheManager(); PageId bigPageId = pageId(-1, 0); assertTrue(mCacheManager.put(bigPageId, page(0, PAGE_SIZE_BYTES))); int sm...
public static int MAXIM(@NonNull final byte[] data, final int offset, final int length) { return CRC(0x8005, 0x0000, data, offset, length, true, true, 0xFFFF); }
@Test public void MAXIM_A() { final byte[] data = new byte[] { 'A' }; assertEquals(0xCF3F, CRC16.MAXIM(data, 0, 1)); }
@Override public void setConfiguration(final Path file, final LoggingConfiguration configuration) throws BackgroundException { final Path bucket = containerService.getContainer(file); try { final Storage.Buckets.Patch request = session.getClient().buckets().patch(bucket.getName(), ...
@Test(expected = NotfoundException.class) public void testWriteNotFound() throws Exception { new GoogleStorageLoggingFeature(session).setConfiguration( new Path(new AsciiRandomStringService().random(), EnumSet.of(Path.Type.directory)), new LoggingConfiguration(false) ); }
static Map<Integer, Schema.Field> mapFieldPositions(CSVFormat format, Schema schema) { List<String> header = Arrays.asList(format.getHeader()); Map<Integer, Schema.Field> indexToFieldMap = new HashMap<>(); for (Schema.Field field : schema.getFields()) { int index = getIndex(header, field); if (i...
@Test public void testHeaderWithComments() { String[] comments = {"first line", "second line", "third line"}; Schema schema = Schema.builder().addStringField("a_string").addStringField("another_string").build(); ImmutableMap<Integer, Schema.Field> want = ImmutableMap.of(0, schema.getField(...
public final boolean isDifficultyTransitionPoint(final int previousHeight) { return ((previousHeight + 1) % this.getInterval()) == 0; }
@Test public void isDifficultyTransitionPoint() { assertFalse(BITCOIN_PARAMS.isDifficultyTransitionPoint(2014)); assertTrue(BITCOIN_PARAMS.isDifficultyTransitionPoint(2015)); assertFalse(BITCOIN_PARAMS.isDifficultyTransitionPoint(2016)); }
@Override public void listenToCluster(final String clusterName, final LoadBalancerStateListenerCallback callback) { trace(_log, "listenToCluster: ", clusterName); // wrap the callback since we need to wait for both uri and cluster listeners to // onInit before letting the ...
@Test(groups = { "small", "back-end" }) public void testListenToCluster() throws URISyntaxException, InterruptedException { reset(); List<String> schemes = new ArrayList<>(); schemes.add("http"); assertFalse(_state.isListeningToCluster("cluster-1")); assertNull(_state.getClusterProperti...
@Override public void process(Exchange exchange) throws Exception { @SuppressWarnings("unchecked") Map<String, Object> body = exchange.getIn().getBody(Map.class); LdapOperation operation = endpoint.getOperation(); if (null == operation) { throw new UnsupportedOperationEx...
@Test public void testEmptyExchange() throws Exception { Exchange exchange = new DefaultExchange(context); assertThrows(UnsupportedOperationException.class, () -> ldapProducer.process(exchange)); }