id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
58881448_4
class HttpResponseHandler { public TrackerResponse handleResponse(InputStream in, Charset charset) { try (BEParser parser = new BEParser(in)) { return handleResponse(parser, charset); } catch (Exception e) { return TrackerResponse.exceptional(e); } } public ...
TrackerResponse trackerResponse = responseHandler.handleResponse( HttpResponseHandlerTest.class.getResourceAsStream("tracker_response_failure1"), defaultCharset); assertNotNull(trackerResponse); assertFalse(trackerResponse.isSuccess()); assertFalse(trackerResponse.getEr...
58921823_374
class SchedulerThriftInterface implements AnnotatedAuroraAdmin { @Override public Response createJob(JobConfiguration mutableJob) { SanitizedConfiguration sanitized; try { sanitized = SanitizedConfiguration.fromUnsanitized( configurationManager, IJobConfiguration.build(mutableJob)...
TaskConfig task = new TaskConfig() .setContactEmail("testing@twitter.com") .setExecutorConfig(new ExecutorConfig("aurora", "config")) // Arbitrary opaque data. .setNumCpus(1.0) .setRamMb(1024) .setDiskMb(1024) .setIsService(true) .setProduction(true) ...
58940073_8
class Validator extends AbstractGltfValidator { public ValidatorResult validate() { validateAsset(); ValidatorContext context = new ValidatorContext("glTF"); ValidatorResult validatorResult = new ValidatorResult(); validatorResult.add(validateScenes(context)); ...
GlTF gltf = new GlTF(); Scene scene = new Scene(); scene.addNodes("INVALID_ID"); gltf.addScenes("scene0", scene); Validator validator = new Validator(gltf); ValidatorResult validatorResult = validator.validate(); assertEquals(1, validatorResult.getErrors(...
58952547_5
class MovieDetailsPresenter implements MovieDetailsMVP.Presenter { @Override public void startPresenting(final MovieDetailsMVP.View movieDetailsView, long movieId) { MovieDetails movieDetails = movieDetailsUseCase.getMovieDetails(); if (movieDetails != null) { movieDetailsView.displ...
Exception exception = new Exception(); when(movieDetailsUseCase.getMovieDetails()).thenReturn(null); ArgumentCaptor<MovieDetailsUseCase.Listener> listenerCapture = ArgumentCaptor.forClass(MovieDetailsUseCase.Listener.class); presenter.startPresenting(view, ANY_MOVIE_ID); verify(...
58955752_148
class StopWord { public String removeTrailing(String text) { List<String> textList = Arrays.asList(text.split("\\s")); List<String> result = removeTrailing(textList); return Joiner.on(" ").join(result); } public StopWord(Path file); public StopWord(Path file, Charset charset); public void caseSensitive(...
assertArrayEquals(stopword.removeTrailing(new String[] { "the", "mountain", "the" }), new String[] { "the", "mountain" }); } }
58972818_285
class AssociateIdentifiersEvent extends Event { @Override public boolean isValid() { boolean isValid = true; if (ids.size() > AssociatedIdentifiers.MAX_IDS) { Logger.error("Associated identifiers exceeds %s", AssociatedIdentifiers.MAX_IDS); isValid = false; } ...
Map<String, String> ids = new HashMap<>(); for (int i = 0; i < 101; i++) { ids.put(UUID.randomUUID().toString(), "value"); } // Verify its invalid assertFalse(new AssociateIdentifiersEvent(new AssociatedIdentifiers(ids)).isValid()); } }
59044564_1496
class DataStorage extends Storage { void recoverTransitionRead(DataNode datanode, NamespaceInfo nsInfo, Collection<StorageLocation> dataDirs, StartupOption startOpt) throws IOException { if (this.initialized) { LOG.info("DataNode version: " + HdfsConstants.DATANODE_LAYOUT_VERSION + " and Na...
final int numLocations = 3; List<StorageLocation> locations = createStorageLocations(numLocations); // Prepare volumes storage.recoverTransitionRead(mockDN, nsInfo, locations, START_OPT); assertEquals(numLocations, storage.getNumStorageDirs()); // Reset DataStorage storage.unlockAll(); ...
59064722_9
class EventDispatcher { public CompletableFuture<?> dispatch(DispatchedEvent<Event> de) { EventHandler eventHandler = eventTypesAndHandlers.get(de.getEventType()); if (eventHandler != null) { CompletableFuture<Object> result = new CompletableFuture<>(); dispatchEvent(de, eventHandler, result, Opt...
whenEventHandlerDispatchReturning(CompletableFutureUtil.failedFuture(exception), CompletableFuture.completedFuture(null)); EventDeliveryExceptionHandlerWithState eventDeliveryExceptionHandlerWithState = mock(EventDeliveryExceptionHandlerWithState.class); when(exceptionHandlerManager.getEventHandler(excep...
59078087_56
class JobCoder { JobInvocation decodeIntentBundle(@NonNull Bundle bundle) { if (bundle == null) { Log.e(TAG, "Unexpected null Bundle provided"); return null; } Bundle taskExtras = bundle.getBundle(GooglePlayJobWriter.REQUEST_PARAM_EXTRAS); if (taskExtras == null) { return null; ...
Bundle bundle = new Bundle(); ContentUriTrigger uriTrigger = getContentUriTrigger(); Bundle encode = encodeContentUriJob(uriTrigger, coder); bundle.putBundle(GooglePlayJobWriter.REQUEST_PARAM_EXTRAS, encode); ArrayList<Uri> uris = new ArrayList<>(); uris.add(ContactsContract.AUTHORITY_URI); ...
59134921_5
class Logo { @Nullable public static String getUriFromSvgUri(@Nullable String iconUrl, int width, int height) { if (iconUrl == null || iconUrl.isEmpty()) { return null; } final Matcher matcher = LOGOS_REGEX.matcher(iconUrl); if (!matcher.matches()) { retu...
assertNull("Should retrun null when the SvgLogoUrl is null", Logo.getUriFromSvgUri(null, 150, 150)); assertNull("Should return null when the url doesn't contain $.svg", Logo.getUriFromSvgUri("abc", 150, 150)); final String inputUrl = "https://cdn.cliqz.com/brands-database/databas...
59199640_2
class OrderedContentTypeDetector implements ContentTypeDetector { @Override public FilterEngine.ContentType detect(final WebResourceRequest request) { FilterEngine.ContentType contentType; for (final ContentTypeDetector detector : detectors) { contentType = detector.detect(request); // ...
final OrderedContentTypeDetector regexFirst = new OrderedContentTypeDetector( new UrlFileExtensionTypeDetector(), new HeadersContentTypeDetector() ); final OrderedContentTypeDetector headersFirst = new OrderedContentTypeDetector( new HeadersContentTypeDetector(), new UrlFileE...
59326989_167
class LoopStep extends RefactorStep implements ProvidesValidations { @Override public Set<Step> refactor(Set<Step> steps) { // The rows that the loop iterates over List<Row> iterationRows = getIterationRows(steps); // The mode that the loop runs as, either 'parallel' or 'serial' String mode = ...
Set<Step> steps = Sets.newHashSet(); Map<String, Object> loopStepConfigMap = Maps.newHashMap(); loopStepConfigMap.put(LoopStep.MODE_PROPERTY, LoopStep.MODE_PARALLEL); loopStepConfigMap.put(LoopStep.SOURCE_PROPERTY, LoopStep.SOURCE_RANGE); loopStepConfigMap.put(LoopStep.RANGE_START_PROPERTY, 5); ...
59412136_1
class Driver implements java.sql.Driver { public boolean acceptsProperties(Properties info) throws SQLException { return Utility.validateRiakProperties( info ); } public Connection connect(String url, Properties info); public boolean acceptsURL(String url); public int getMajorVersion(); public int getMinorVer...
Properties info = new Properties(); info.setProperty("RiakUrl", "127.0.0.1"); info.setProperty("RiakPort", "8087"); assertTrue( _driver.acceptsProperties(info) ); } }
59419011_1
class ConnectorNov2016 implements Connector { @Override public Decoder.Response get(String caller, Transport.Target target, Pager pager, Map<String, ?> parameters) throws InterruptedException { String id = UUID.randomUUID().toString(); Encoder.Request request = encoder.get(caller, target, pager, parame...
Transport.Factory factory = Transport.defaultFactory(); Responder south = new DefaultResponder() { @Override public Response first(String state, Decoder.Pager p, Decoder.Parameters ps, Transport.Target t) { return DefaultResponse.fromData( merge(new HashMap<>(), Bank.ba...
59504997_948
class AclTransformation { 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); Enu...
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, MASK, ALL)) .add(aclEntry(ACCESS, OTHER, READ)) .add(aclEntry(DEFAULT, USE...
59521369_5
class Easter { static LocalDate sundayFor(Year year) { final int y = year.getValue(); final int a = y % 19; final int b = y / 100; final int c = y % 100; final int d = b / 4; final int e = b % 4; final int f = (b + 8) / 25; final int g = (b - f + 1) / 3; final int h = (19 * a + b - d - g + 15) % 30;...
assertThat(Easter.sundayFor(Year.of(year))).isEqualTo(easterDate.atYear(year)); } }
59553354_0
class DefaultGreeter implements Greeter { public String greet(final String name) { return "Hello " + name; } } class DefaultGreeterTest { @Test public void testGreet() {
final Greeter greeter = new DefaultGreeter(); Assert.assertEquals("Hello foo", greeter.greet("foo")); Assert.assertEquals("Hello bar", greeter.greet("bar")); } }
59553587_0
class TaskMapper { public static TaskModel transform(TaskEntity taskEntity) { TaskModel taskModel = null; if (taskEntity != null) { taskModel = new TaskModel(taskEntity.getTitle()); taskModel.setId(taskEntity.getId()); taskModel.setDeadline(taskEntity.getDeadline...
TaskEntity taskEntity = createEntity(); TaskModel taskModel = TaskMapper.transform(taskEntity); assertThat(taskModel, is(instanceOf(TaskModel.class))); assertThat(taskModel.getId(), is(FAKE_TASK_ID)); assertThat(taskModel.getTitle(), is(FAKE_TASK_TITLE)); assertThat(taskModel.getDeadlineMs()).i...
59571413_99
class Container { public Iterable<V> getValues() { return this.valueByKey.values(); } public Container(final Logger logger); public void setMode(final Mode mode); public boolean add(final K key, final V value); public void debug(); public void freeze(); public V get(final K k...
Assert.assertFalse(this.container.getValues().iterator().hasNext()); } }
59681438_17
class SamplesParser { public static List<CodeSample> getSamples(final File[] files, final String targetExtension) throws Exception { if (files == null) { throw new SampleParsingException( "Must provide a non-null set of files to parse"); } List<C...
File sampleFile = getSampleFile("NoContentSample.java"); assertTrue(SamplesParser.getSamples(sampleFile).isEmpty()); } }
59703501_2
class FetcherDefault extends AbstractExtensionPoint implements Fetcher, Function<Resource, FetchedData> { @Override public Iterator<FetchedData> fetch(Iterator<Resource> resources) throws Exception { return new StreamTransformer<>(resources, this); } public FetcherDefault(); @Override pu...
Iterator<FetchedData> stream = fetcher.fetch(resources.iterator()); List<FetchedData> list = new ArrayList<>(); stream.forEachRemaining(list::add); assertEquals(list.size(), resources.size()); for (FetchedData data : list) { if (data.getResource().getUrl().contains("...
59744695_73
class FactoryBase { @SuppressWarnings("unchecked") void finalizeChildren() { finalisedChildrenFlat = new ArrayList<>(); getFactoryMetadata().visitChildFactoriesAndViewsFlat(this, childUntyped->{ FactoryBase<?,R> child = (FactoryBase<?,R>)childUntyped; if (child!=null){ ...
ExampleFactoryA exampleFactoryA = new ExampleFactoryA(); ExampleFactoryB factory = new ExampleFactoryB(); exampleFactoryA.referenceAttribute.set(factory); exampleFactoryA.referenceListAttribute.add(factory); ((FactoryBase<?, ?>)exampleFactoryA).finalizeChildren(); Asser...
59800365_3
class ProjectServiceImpl implements ProjectService { @Override public List<Team> getTeams() { List<Team> teams = cacheClient.get(ServiceConstants.CACHE_KEY_TEAMS); if (teams == null) { teams = projectDao.getTeams(); cacheClient.set(ServiceConstants.CACHE_KEY_TEAMS, (Serializable) teams); ...
//TODO 修改该test case,先构建数据再恢复现场 // List<Team> teams = projectService.getTeams(); // Assert.assertEquals(4, teams.size()); } }
59834447_2
class SymbolsCache { public BuildMetadataEntry getEntry(@NotNull final String key, @NotNull final MetadataSource metadataSource) { Boolean missedSymbol = myMissedSymbols.getIfPresent(key); if (missedSymbol != null && missedSymbol) { LOG.debug("Symbol server does not...
// Given SymbolsCache symbolsCache = new SymbolsCache(myFixture.getEventDispatcher()); Mockery m = new Mockery(); String key = "key"; BuildMetadataEntry entry = m.mock(BuildMetadataEntry.class, key); String key2 = "key2"; BuildMetadataEntry entry2 = m.mock(BuildMetadataEntry.class, key2); ...
59881768_8
class GrowOnlyCounter implements CrdtCounter<Long, GrowOnlyCounter> { @Override public GrowOnlyCounter merge(GrowOnlyCounter other) { return new GrowOnlyCounter(this, other); } GrowOnlyCounter(Map<String, Long> counters); public GrowOnlyCounter(GrowOnlyCounter growOnlyCounter, Builder builder); pub...
Map<String, Long> node1Counter = new HashMap<>(); node1Counter.put("1", 3L); Map<String, Long> node2Counter = new HashMap<>(); node2Counter.put("2", 1L); Map<String, Long> node3Counter = new HashMap<>(); node3Counter.put("3", 2L); GrowOnlyCounter gCounter1 = new GrowOnlyCounter(nod...
59929488_16
class Reg { public String register(String uafMsg, String appFacetId) throws UafMsgProcessException, UafRequestMsgParseException, UafResponseMsgParseException { logger.info(" [UAF][1]Reg "); RegistrationResponse[] ret = new RegistrationResponse[1]; RegistrationResponse regResponse = proce...
InitConfig.getInstance().init(operParams.TEST_AAID, operParams.TestAttestCert, null, operParams, null); Reg reg = new Reg(); String regRequest = "[{\"header\":{\"upv\":{\"major\":1,\"minor\":0},\"op\":\"Reg\",\"appID\":\"https://uaf-test-1.noknoktest.com:8443/SampleApp/uaf/facets\",\"serverData\":\"IjycjPZYiWMaQ1...
59975597_1
class RxMemoization { public static <R> Func0<R> memoize(final Func0<R> func0) { return new Func0<R>() { private R value; @Override public R call() { if (null == value) { synchronized (this) { if (null == value...
final AtomicInteger count = new AtomicInteger(0); Func1<Integer, MyObject> memoized = RxMemoization.memoize(new Func1<Integer, MyObject>() { @Override public MyObject call(Integer integer) { count.incrementAndGet(); return INSTANCES.get(integer); ...
59981531_33
class FastDiag { public Set<Constraint> getPreferredDiagnosis(Set<Constraint> constraintsSetC, Boolean displayFastDiagSteps) throws DiagnosisException { this.displayfastDiagSteps = displayFastDiagSteps; if (constraintsSetC.isEmpty()) { if (progressCalback != null) { progressCalback.displayMessage("C...
Set<Constraint> constraintsSetC = new LinkedHashSet<Constraint>(); Set<Element> decisionsVar = new LinkedHashSet<Element>(); String fileName = UtilsForTest.getTestDataset1(constraintsSetC, decisionsVar); FastDiag fastDiag = new FastDiag(fileName, constraintsSetC, ConflictDetectionAlgorithm.FastDiag, null); ...
60020187_2
class AgeraCallAdapterFactory extends CallAdapter.Factory { @Override public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) { if (getRawType(returnType) != Supplier.class) { return null; } if (!(returnType instanceof ParameterizedType)) {...
Type reservoirType = new TypeToken<Supplier>() {}.getType(); try { factory.get(reservoirType, NO_ANNOTATIONS, retrofit); fail(); } catch (IllegalStateException e) { assertThat(e, hasMessage(containsString( "Supplier return type must be paramete...
60094068_126
class CrashReporterApiClient extends ApiClient { public ApiClientResult<Object> reportError(Throwable t) { Request request = generateCreateErrorReportRequest(t); try { Response response = httpClient.newCall(request).execute(); if (response.isSuccessful()) { response.close(); retur...
enqueueMockResponse(); apiClient.reportError(ANY_EXCEPTION); assertRequestSentTo("/errorReport"); } }
60111626_28
class Curses { public static String tputs(String cap, Object... params) { if (cap != null) { StringWriter sw = new StringWriter(); tputs(sw, cap, params); return sw.toString(); } return null; } private Curses(); public static void tputs(App...
assertEquals("{\033[3;4r", Curses.tputs("\\173\\E[%i%p1%d;%p2%dr", 2, 3)); } }
60127046_0
class ConfigMapper { public static ReadableMap toMap(Config config) { WritableMap out = Arguments.createMap(); WritableMap httpHeaders = Arguments.createMap(); if (config.getStationaryRadius() != null) { out.putDouble("stationaryRadius", config.getStationaryRadius()); } ...
Config config = Config.getDefault(); ReadableMap map = ConfigMapper.toMap(config); Assert.assertEquals(config.getStationaryRadius(), map.getDouble("stationaryRadius"), 0f); Assert.assertEquals(config.getDistanceFilter().intValue(), map.getInt("distanceFilter")); Assert.assertEqu...
60131932_2
class RxUi { public static <T> Function<Observable<T>, Disposable> ui(final Consumer<T> uiAction) { return new Function<Observable<T>, Disposable>() { @Override public Disposable apply(Observable<T> observable) { return observable .observeOn(m...
final AtomicBoolean wasCalledOnUiThread = new AtomicBoolean(true); // WHEN have UI action Consumer<String> uiAction = spy(new Consumer<String>() { @Override public void accept(String s) { if (!wasCalledOnUiThread.compareAndSet(true, Looper.getMainLooper()...
60171447_0
class MainViewPresenter extends Presenter { private void loadBitcoinPrice() { callback.showLoading(); loadBitcoinPriceUseCase.execute( value -> callback.setData((List<BitcoinPriceViewModel>) value), throwable -> callback.showError(throwable.getMessage()), () -> callback.hideLoading() ...
mainViewPresenter.onStart(); verify(mainViewCallback).showLoading(); verify(loadBitcoinPriceUseCase).execute(any(Action1.class), any(Action1.class), any(Action0.class)); } }
60241390_28
class ProcessorFactory { static StatusProcessor produce(SuiteStatusResult suiteStatusResult, String reportUrl, RedirectWriter redirectWriter, RunnerTerminator runnerTerminator) { StatusProcessor processor = null; if (suiteStatusResult != null) { switch (suiteStatusResult.getStatus()) { ca...
SuiteStatusResult nullSuiteStatus = null; StatusProcessor processor = ProcessorFactory .produce(nullSuiteStatus, REPORT_URL, null, runnerTerminator); assertThat(processor, is(nullValue())); } }
60259028_1
class ServicesManager implements DataSource { @Override public Observable<List<WeatherConditionEntity>> getWeatherConditionEntities() { Map<String, String> params = new android.support.v4.util.ArrayMap<>(2); params.put("search", Constants.SEARCH_ALL_COND); params.put("key", Constants.WE...
assertNotNull(mServicesManger); TestSubscriber<List<WeatherConditionEntity>> testSubscriber = TestSubscriber.create(new GetWeatherConditionsDelegate()); mServicesManger.getWeatherConditionEntities().subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.as...
60270542_0
class ImgurMvpPresenter extends BasePresenter<ImgurMvpView> { public void refreshTopics() { imgurApi.defaultTopics() .map(TopicResponse::getData) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .compose(view().bind()) .compose(view().injectProgress()) .subscribe(topics -> ...
// given TopicResponse response = new TopicResponse(); List<Topic> topics = Lists.newArrayList(new Topic(), new Topic(), new Topic()); response.setData(topics); given(imgurApi.defaultTopics()).willReturn(Observable.just(response)); // when presenter.refreshTopics(); // then proxy.advanceBy(1, TimeUn...
60296811_2
class Diacetyl { public static void butterForTests(Object... instancesWithViews) { Diacetyl diacetyl = new Diacetyl(); for (Object instanceWithViews : instancesWithViews) { diacetyl.bindForTests(instanceWithViews); } } private void bindForTests(Object instanceWithViews)...
Diacetyl.butterForTests(exampleClass); assertThat(exampleClass.nonNulView.getText()).isEqualTo("preset"); } }
60379785_24
class UserWS { @RequestMapping(value = "/api/users", method = RequestMethod.GET) public List<User> getUsers(@RequestParam(value = "username", required = false) String username) { List<User> users = userRepository.findAll( where(ifParamNotNull(usernameEquals(username))) ...
List<User> users = userClient.getUsers(null); assertFalse(users.isEmpty()); for (User user : users) { logger.debug("{}: {}", user.getUsername(), authoritiesToString(user.getAuthorities())); } } }
60384641_0
class CDPlayer implements MediaPlayer { public void play() { cd.play(); } @Autowired public CDPlayer(CompactDisc cd); @Rule public final StandardOutputStreamLog log; @Autowired private MediaPlayer player; @Autowired private CompactDisc cd; } class CDPlayerTest { @R...
player.play(); assertEquals("Playing Hello by Adele.", log.getLog()); } }
60395071_0
class ShotsRepository implements ShotsDataSource { private void getListShotsFromRemote(final int filterId, final LoadListShotsCallback callback){ mShotsRemoteDataSource.getListShots(filterId,new LoadListShotsCallback() { @Override public void onListShotsLoaded(List<Shots> shotsList)...
shotsRepository.refreshShots(); shotsRepository.getListShots(0,loadListShotsCallback); verify(shotsRemoteDataSource).getListShots(eq(0),loadListShotsCallbackArgumentCaptor.capture()); loadListShotsCallbackArgumentCaptor.getValue().onListShotsLoaded(new ArrayList<Shots>()); verify...
60416700_305
class NsClientReceiverDelegate { boolean calculateStatus(final EventChargingState ev) { boolean chargingOnly = SP.getBoolean(R.string.key_ns_chargingonly, false); boolean newAllowedState = true; if (!ev.isCharging() && chargingOnly) { newAllowedState = false; } ...
PowerMockito.mockStatic(SP.class); // wifiOnly = false // allowRoaming = false as well when(SP.getBoolean(anyInt(), anyBoolean())).thenReturn(false); when(SP.getString(anyInt(), anyString())).thenReturn(""); EventNetworkChange ev = new EventNetworkChange(); ev.set...
60432093_1
class RxGuava { public static <T> Observable<T> fromIterator(final ListenableFuture<Iterator<T>> futureIterator) { return fromIterator(futureIterator, MoreExecutors.sameThreadExecutor()); } public static Observable<T> fromIterable(final ListenableFuture<? extends Iterable<T>> futureIterable); public stati...
Iterator<Integer> iter = Arrays.asList(1,2,3).iterator(); SettableFuture<Iterator<Integer>> future = SettableFuture.create(); Executors.newSingleThreadScheduledExecutor().schedule(()->future.set(iter), 100, TimeUnit.MILLISECONDS); CountDownLatch latch = new CountDownLatch(3); AtomicReference<String>...
60435184_1
class LoginViewModel implements ViewModel { public void onClickLoginButton(@SuppressWarnings("unused") View view) { navigator.startCustomTab(AnnictClient.getOAuthUrl()); } @Inject public LoginViewModel(PageNavigator navigator); @Override public void destroy(); private LoginViewModel log...
loginViewModel.onClickLoginButton(null); verify(navigator, times(1)).startCustomTab(AnnictClient.getOAuthUrl()); } }
60450885_34
class DefaultReactiveRepository extends DefaultRepository<E> implements ReactiveRepository<E, K> { @Override public Mono<Integer> insertBatch(Publisher<? extends Collection<E>> data) { return Flux.from(data) .filter(CollectionUtils::isNotEmpty) .flatMap(e -> doInsert(e)....
List<TestEntity> list = Flux.range(0, 100) .map(i -> { TestEntity entity = new TestEntity(); entity.setId("test_" + i); entity.setName("test_" + i); if (i < 10) { entity.setState((byte) 1); ...
60524334_3
class BlankConstraint extends Constraint<Object> { @NonNull @Override public Set<Violation> validate() throws UnsupportedException { final Set<Violation> violations = new HashSet<>(); final String value = getStringFromObject(object, propertyName); if (null != value && 0 != value.tr...
assertNotEmpty("is invalid with String", new BlankConstraint(NOT_BLANK, PROPERTY_NAME).validate()); assertNotEmpty("is invalid with EditText", new BlankConstraint(generateEditText(NOT_BLANK), PROPERTY_NAME).validate()); assertNotEmpty("is invalid with Spinner", new Blan...
60536546_10
class RequirementsChecker { RequirementsReport checkRequirements() { boolean result = true; List<RequirementReport> requirementsReports = new ArrayList<>(mRequirements.size()); for (Requirement requirement : mRequirements) { RequirementReport report = requirement.check(); ...
final RequirementsChecker checker = new RequirementsChecker(Arrays.asList( new FulfilledRequirement(), new FulfilledRequirement(), new FulfilledRequirement() )); assertThat(checker.checkRequirements().isFulfilled()).isTrue(); } }
60561103_1
class EasyOkCallback implements Callback { public abstract void failure(Throwable t)public abstract void failure(Throwable t); public abstract void failure(Throwable t)public EasyOkCallback(); public abstract void failure(Throwable t)public abstract void success(@NonNull Response response); public abstract void fai...
Request request = new Request.Builder() .url("https://www.google.com/404") .build(); client.newCall(request).enqueue(new EasyOkCallback() { @Override public void success(@NonNull Response response) { Assert.fail("call should have f...
60573613_135
class ItemUtils { public static List<Integer> toItemList(final String itemsString) { if (Strings.isNullOrEmpty(itemsString)) { return Collections.emptyList(); } String[] items = itemsString.split(DELIMITER); List<Integer> result = new ArrayList<>(items.length); f...
assertThat(ItemUtils.toItemList(""), is(Collections.EMPTY_LIST)); } }
60578004_96
class SensitiveInfoUtils { public static List<String> filterSensitiveIps(final List<String> result) { final Map<String, String> fakeIpMap = new HashMap<String, String>(); final String fakeIpSample = "ip"; final AtomicInteger step = new AtomicInteger(); Function<String, String> func ...
List<String> content = new ArrayList<String>(); content.add("/simpleElasticDemoJob/servers"); content.add("/simpleElasticDemoJob/leader"); assertThat(SensitiveInfoUtils.filterSensitiveIps(content), is(content)); } }
60598401_25
class MaterialHandlerService implements IMaterialHandlerService { @Override public String checkPipelineForTriggerMaterials(PipelineDefinition pipelineDefinition) { List<String> triggerMaterials = new ArrayList<>(); List<MaterialDefinition> materialDefinitions = (List<MaterialDef...
// Arrange PipelineDefinition pipelineDefinition = new PipelineDefinition(); List<MaterialDefinition> materialDefinitions = new ArrayList<>(); GitMaterial gitMaterial = new GitMaterial(); gitMaterial.setName(MATERIAL_ONE); gitMaterial.setPollingForChanges(true); m...
60642785_0
class UtilMethods { static String extractYoutubeID(String url) { String pattern = "(?<=youtu.be/|youtube.com/watch\\?v=|/videos/|embed/)[^#&\\?]*"; Pattern compiledPattern = Pattern.compile(pattern); Matcher matcher = compiledPattern.matcher(url); if (matcher.find()) { r...
assertEquals(UtilMethods.extractYoutubeID("youtube.com/watch?v=oGHWghMfbEU"), "oGHWghMfbEU"); assertEquals(UtilMethods.extractYoutubeID("https://youtube.com/watch?v=oGHWghMfbEU"), "oGHWghMfbEU"); assertEquals(UtilMethods.extractYoutubeID("https://www.youtube.com/watch?v=oGHWghMfbEU"), "oGHWghMfb...
60648293_3
class KafkaBinderMetrics implements MeterBinder, ApplicationListener<BindingCreatedEvent> { @Override public void bindTo(MeterRegistry registry) { this.scheduler = Executors.newScheduledThreadPool(this.binder.getTopicsInUse().size()); for (Map.Entry<String, KafkaMessageChannelBinder.TopicInformation> topicInfo...
List<PartitionInfo> partitions = partitions(new Node(0, null, 0)); topicsInUse.put(TEST_TOPIC, new TopicInformation(null, partitions, false)); metrics.bindTo(meterRegistry); assertThat(meterRegistry.getMeters()).isEmpty(); } }
60648780_0
class SnomedCtIdentifier { public long namespaceIdentifier() { if (releaseIdentifier() == 1) { int len = _id.length(); return Long.valueOf(_id.substring(len-10, len-3)); } return 0; } public SnomedCtIdentifier(long id); private boolean _isValid(); public boolean isValidConcept(); public boolean is...
assertEquals(989121L, new SnomedCtIdentifier(999999990989121104L).namespaceIdentifier()); assertEquals(1, new SnomedCtIdentifier(1290000001117L).namespaceIdentifier()); assertEquals(1, new SnomedCtIdentifier(40000001132L).namespaceIdentifier()); } }
60648874_18
class Topping { void updateColor(@ColorInt int color){ this.previousColor = this.color; this.color = color; } Topping(int id); public int getId(); public int getColor(); public int getPreviousColor(); @Override public boolean equals(Object o); @Override public int ha...
int newColor = -123456; mToppingMock.updateColor(newColor); int color = mToppingMock.getColor(); int prevColor = mToppingMock.getPreviousColor(); assertThat(color, is(newColor)); assertThat(prevColor, is(MOCK_DEFAULT_COLOR)); } }
60683863_130
class ReflectUtils { public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { String signature = clazz.getName() + "." + methodName; if(parameterTypes != null && parameterTypes.length > 0){...
try { ReflectUtils.findMethodByMethodSignature(TestedClass.class, "notExsited", null); fail(); } catch (NoSuchMethodException expected) { assertThat(expected.getMessage(), containsString("No such method ")); assertThat(expected.getMessage(), containsString("i...
60686962_118
class NetPlan extends NetworkElement { public void removeAllMulticastTreesUnused(double toleranceTrafficAndCapacityValueToConsiderUnusedTree, NetworkLayer... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); ...
np.removeAllMulticastTreesUnused(0.1 , lowerLayer); assertEquals(np.getNumberOfMulticastTrees(lowerLayer) , 2); } }
60701545_222
class TransformTask extends StreamBasedTask implements Context { @TaskAction void transform(final IncrementalTaskInputs incrementalTaskInputs) throws IOException, TransformException, InterruptedException { final ReferenceHolder<List<TransformInput>> consumedInputs = ReferenceHolder.empty()...
// create a stream and add it to the pipeline File jarFile = new File("jar file"); TransformStream projectClass = OriginalStream.builder() .addContentType(DefaultContentType.CLASSES) .addScope(Scope.PROJECT) .setJar(jarFile) .setDep...
60737153_13
class AuthenticationClient { public boolean isLoggedIn() { return loginStatus; } public AuthenticationClient(String sessionUrl, String keyUrl); public AuthenticationClient(String sessionUrl, String keyUrl, Client httpClient); public AuthenticationClient(SymphonyClientConfig symphonyClie...
assertEquals(false, authenticationClient.isLoggedIn()); } }
60773713_1
class ConsecutiveDaysAccumulateFunction implements AccumulateFunction { @Override public void init(Serializable context) throws Exception { ConsecutiveDaysBuckets buckets = (ConsecutiveDaysBuckets) context; buckets.buckets = new HashMap<>(); } @Override public void accumulate(Serializa...
ConsecutiveDaysAccumulateFunction f = new ConsecutiveDaysAccumulateFunction(); ConsecutiveDaysAccumulateFunction.ConsecutiveDaysBuckets buckets = new ConsecutiveDaysAccumulateFunction.ConsecutiveDaysBuckets(); f.init(buckets); Assert.assertNotNull(buckets.buckets); Assert.assertE...
60780272_2
class QuerySegmenterDefaultImpl implements QuerySegmenter { @Override public List<TypedSegment> segment(String query) { List<TypedSegment> typedSegments = new ArrayList<TypedSegment>(); String[] segments = query.split("\\s+"); // Evaluate segments from left to right for (int i = 0; i < segments....
String query = "pizza campbell park"; List<TypedSegment> segments = segmenter.segment(query); assertEquals(1, segments.size()); TypedSegment segment = segments.get(0); assertEquals(AreaTypedSegment.TYPE, segment.getType()); assertEquals("Campbell Park", segment.getLabel()); assertEquals("c...
60794667_81
class BasicNeuralNet implements NeuralNet, Serializable { public double[] getOutput() { if (currentNetOutput == null) { return new double[netOutputDim]; } return currentNetOutput; } public BasicNeuralNet(int[] netTopology, double biasInput, Class<? extends...
double[] zeroArray = new double[NET_TOPOLOGY[NET_TOPOLOGY.length - 1]]; Arrays.fill(zeroArray, 0); assertTrue("Network output is not as expected.", Arrays.equals(zeroArray, neuralNet.getOutput())); } }
60851319_52
class LdapUtils { public static String escapeCommonName(final String name) { if (name == null) { return null; } final StringBuilder buf = new StringBuilder(name.length() + 5); for (int i = 0; i < name.length(); i++) { final char ch = name.charAt(i); if (",=+<>#;\\\"".indexOf(ch) >...
assertNull(LdapUtils.escapeCommonName(null)); assertEquals("", LdapUtils.escapeCommonName("")); assertEquals("\\,", LdapUtils.escapeCommonName(",")); assertEquals("\\,\\=\\+\\<\\>\\#\\;\\\\\\\"", LdapUtils.escapeCommonName(",=+<>#;\\\"")); } }
60913395_10
class PrayerDownloader { Observable<PrayerContext> getPrayerTimes(String code) { return getCurrentPrayerTimesByCode(code) .zipWith(getNextPrayerTimesByCode(code), mPrayerContextCreator); } @Inject PrayerDownloader(DateTimeHelper helper, PrayerClient client, ...
String code = "ext-153"; PrayerDownloader d = new PrayerDownloader( mDateHelper, mPrayerClient, mPrayerCache, mInterfacePreferences ); when(mLocation.getLatitude()) .thenReturn(3.28011); when(mLoca...
60923411_3
class CredentialStore { synchronized void setNewAccessToken(@NonNull String accessToken, int expiresIn) { if(accessToken.length() == 0) throw new IllegalArgumentException("accessToken.isEmpty()"); this.accessToken = accessToken; this.expiresIn = expiresIn; this.tokenAc...
credentialStore.authenticate(accessToken, refreshToken, expiresIn, new Date(1000)); credentialStore.setNewAccessToken(accessToken, expiresIn); assertEquals(credentialStore.getAuthStatus(), CredentialStore.AUTHENTICATED); assertTrue(credentialStore.getTokenAcquisitionTime().getTime() != n...
60963516_8
class BookingEarningsCalculator extends EarningsCalculator { public float calculateEarnings(Collection<? extends BookingBean> bookings) { if (isPaymentDone()) { bookings = bookings.stream().filter(b -> b.isPaymentDone()).collect(Collectors.toCollection(LinkedHashSet::new)); } if...
c = new BookingEarningsCalculator(); BookingBean b = BookingBeanTest.newInstance(LocalDate.of(2012, 02, 02), LocalDate.of(2012, 2, 5)); b.setPaymentDone(true); b.setGrossEarningsExpression("30"); float result = c.calculateEarnings(b); assertThat(result, is(30f)); } }
61105758_18
class LocalRegionCache implements RegionCache { void cleanup() { final int maxSize = evictionConfig.getMaxSize(); final long timeToLive = evictionConfig.getTimeToLive().toMillis(); boolean limitSize = maxSize > 0 && maxSize != Integer.MAX_VALUE; if (limitSize || timeToLive > 0) { ...
MapConfig mapConfig = mock(MapConfig.class); Config config = mock(Config.class); when(config.findMapConfig(eq(CACHE_NAME))).thenReturn(mapConfig); com.hazelcast.config.EvictionConfig maxSizeConfig = mock(com.hazelcast.config.EvictionConfig.class); when(mapConfig.getEvictionConf...
61323364_6
class CityDetailPresenter implements CityDetailContract.Presenter { @Override public void openCity(int cityId) { //mView.showProgressBar(true); mSubscriptions.clear(); Subscription subscription = mRepository .getForecast(cityId, mView.isNetworkAvailable()) ...
when(mRepository.getForecast(54353, false)).thenReturn(Observable.just(new ArrayList<>())); when(mView.getResources()).thenReturn(mResources); when(mResources.getString(R.string.error)).thenReturn("Error"); mPresenter.openCity(54353); verify(mRepository).getForecast(54353, false)...
61433804_1
class ServiceResourceUtil implements Serializable { public void patchServiceName(Set<HasMetadata> entities) { if(isPatchingDisabled()) { return; } Map<String, Service> services = patchServiceIfInvalidName(entities); Map<String, Route> routes = patchRouteWithService(ent...
// GIVEN envVars.set(ServiceResourceUtil.K8S_PIPELINE_SERVICE_PATCH, "disabled"); Set<HasMetadata> entities = getEntitiesFromResource("/services/invalidservice1.yaml"); ServiceResourceUtil util = new ServiceResourceUtil(); // WHEN util.patchServiceName(entities); ...
61441349_0
class Utils { @Nullable @CheckResult public static byte[] toByteArray(@Nullable Byte[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_PRIMITIVE_BYTES; } else { byte[] result = new byte[array.length]; for (int i = 0, size = array.length...
final byte[] expected = new byte[]{0x55, 0x66, 0x14}; assertThat(toByteArray(new Byte[]{0x55, 0x66, 0x14})).isEqualTo(expected); } }
61508446_420
class ReadOnlyByteBuf extends AbstractDerivedByteBuf { @Override public ByteBuf unwrap() { return buffer; } public ReadOnlyByteBuf(ByteBuf buffer); @Override public boolean isReadOnly(); @Override public boolean isWritable(); @Override public boolean isWritable(int numBytes); ...
ByteBuf buf = buffer(1); assertSame(buf, unmodifiableBuffer(buf).unwrap()); } }
61520679_0
class PrisonSortableMines extends PrisonSorter { @Override public Set<Mine> getSortedSet() { TreeSet<Mine> mines = new TreeSet<>( new PrisonSortComparableMines() ); List<Mine> unsortedMines = PrisonMines.getInstance().getMineManager().getMines(); mines.addAll( unsortedMines ); return mines; } } clas...
Mine a = new Mine(); a.setName( "A" ); Mine b = new Mine(); b.setName( "b" ); Mine c = new Mine(); c.setName( "C" ); List<Mine> unsortedList = new ArrayList<>(); unsortedList.add( b ); unsortedList.add( c ); unsortedList.add( a ); assertEquals( "b", unsortedList.get( 0 ).getName() ); asser...
61523190_2
class StringingT1 implements IStringingOperator { @Override public OpResult performOperator(Integer[] tour, Integer toString, int neighbourhoodSize, IDistanceCalculator distanceCalculator) { int counterNull = 0; int counterNotNull = 0; int[] neigbourHoodJ = Util.getNeighbourhoodIndexesFromValue(tour, toString...
Map<Integer, Integer[]> correct = buildIsCorrect(); StringingT1 stringT1 = new StringingT1(); double[][] tour = getSimpleTour(); for (int i = 0; i < tour.length; i++) { // int i = 1; int valueToRemoveInsert = i; Integer[] intTour = remove(transform(tour), valueToRemoveInsert); // test // intTou...
61565876_55
class InjectorImpl implements Injector { @Override public <T> void registerProvider(Class<T> clazz, Provider<? extends T> provider) { checkNotNull(clazz, "Class may not be null"); checkNotNull(provider, "Provider may not be null"); try { for (Handler handler : config.getHand...
// given / when InjectorException ex = assertThrows(InjectorException.class, () -> injector.registerProvider(null, mock(Provider.class))); // then assertThat(ex.getMessage(), containsString("may not be null")); } }
61610584_3
class RepositoriesPresentationModel implements Serializable, Parcelable { public void setRepositories(List<Repository> repositories) { this.repositories = repositories; } public RepositoriesPresentationModel(String username); protected RepositoriesPresentationModel(Parcel in); public St...
assertNull(model.getRepositories()); model.setRepositories(TestMocks.REPOSITORIES); assertEquals(TestMocks.REPOSITORIES, model.getRepositories()); } }
61638949_0
class JsonConsumer { public String greet(String name) { // TODO // try adding a second field (e.g. gender) with a random value // the test now fails because we send more than specified which should result in a contract change return target.path("/greet") .request(APPLICA...
final JsonConsumer consumer = new JsonConsumer(mockProvider.getUrl()); final String result = consumer.greet("Michael"); assertEquals("{\"greeting\":\"Hello, Michael!\"}", result); } }
61667990_279
class PaginationHelper { public Map<String, Object> paginate(String jsonKey, List<T> list, String filter, String timezoneOffset, String sort, int page, int perPage) { Map<String, Object> response = new HashMap<>(); paginationFilter.replaceFilter(filter, time...
Object[][] objectDefinitions = new Object[][]{ {"A", 22}, {"B", 23}, {"Z", 10}, {"D", 12}, {"E", 13}, {"C", 42}, {"Z", 11}, {"E", 12}, {"X", 35}, {"X", ...
61691853_5
class CacheUtil { public static String getLocalPath(String remotePath, Configuration conf, int generationNumber) { checkState(generationNumber != UNKONWN_GENERATION_NUMBER, "generationNumber is " + UNKONWN_GENERATION_NUMBER); final String absLocation = getDirectory(remotePath, conf); return String.form...
String localRelPath = "testbucket/123/4566/789"; String remotePath = "s3://" + localRelPath; CacheConfig.setCacheDataDirPrefix(conf, cacheTestDirPrefix); CacheConfig.setCacheDataDirSuffix(conf, "/fcache/"); CacheConfig.setMaxDisks(conf, 1); createCacheDirectoriesForTest(conf); String local...
61705055_7
class QImageMogr2UrlBuilder { public QImageMogr2UrlBuilder thumbnailEdgeeMin(int width, int height){ thumbnail = "!" + width + "x" + height + "r"; return this; } QImageMogr2UrlBuilder(String host); public String getHost(); public QImageMogr2UrlBuilder autoOrient(); public QI...
final String result = QImage.createMogr(HOST) .thumbnailEdgeeMin(200, 400) .toUrl(); final String r = HOST + "?imageMogr2/thumbnail/!200x400r"; assertEquals(r, result); } }
61705166_2
class UrlTokenizer extends Tokenizer { protected List<String> splitUrl(String url) { return splitUrl(url, true); } public UrlTokenizer(); @Override public final boolean incrementToken(); protected List<String> splitUrl(String url, boolean includeParams); private String join(String[] ...
// given String url = "129136207330/good-times-only?one=two&three=four"; // when List<String> splits = urlTokenizer.splitUrl(url); // then assertTrue(splits.contains("129136207330")); assertTrue(splits.contains("129136207330/good-times-only")); assertTru...
61706237_8
class ListenToValueEventsOnSubscribe implements ObservableOnSubscribe<T> { @Override public void subscribe(@NonNull ObservableEmitter<T> emitter) throws Exception { final ValueEventListener eventListener = query.addValueEventListener(new RxValueListener<>(emitter, marshaller)); emitter.setCance...
final DataSnapshot expectedKeyData = mock(DataSnapshot.class); when(expectedKeyData.getKey()).thenReturn(EXPECTED_KEY); Query query = mock(Query.class); doAnswer(new Answer<ValueEventListener>() { @Override public ValueEventListener answer(InvocationOnMock invo...
61731745_2
class XMLKatalog { public int findeEintragnummer(String titel){ int nummer = -1; String tmp =""; ArrayList<String> tmpList = this.getTitles(); for(int i = 0; i<tmpList.size(); i++){ tmp = tmpList.get(i); if(tmp.equals(titel)) nummer = i; } ret...
String titel = "Zweite Aufgabe!"; assertEquals(1, test.findeEintragnummer(titel)); } }
61744742_256
class MetricName extends BasicPath<MetricName> implements Comparable<MetricName>, Path { public static MetricName valueOf(String... path) { return CACHE.apply(new PathArray(path)); } private MetricName(PathArray path); public static MetricName valueOf(List<String> path); } class MetricName...
assertEquals("foo", MetricName.valueOf("foo").configString().toString()); assertEquals("'99'", MetricName.valueOf("99").configString().toString()); assertEquals("'\\r'", MetricName.valueOf("\r").configString().toString()); assertEquals("'3'.'14159'", MetricName.valueOf("3", "14159").conf...
61803076_1
class BayesianNetwork { public boolean isValid() { for (N n: nodes) { if (!n.isValid()) return false; } return true; } public BayesianNetwork(String name); public void add(N n); public void addAll(Collection<N> nns); public boolean containsNode(N n); public N getVariable(String id); publi...
NodeCategorical nGender = new NodeCategorical(null, "gender"); nGender.addDomain("male", "female"); nGender.setProbabilities(0.55, "male"); nGender.setProbabilities(0.45, "female"); assertEquals(0.55, nGender.getProbability("male"), 1e-5); assertEquals(0.45, nGender.getProbability("female"), 1e-5)...
61822650_48
class NoteQueryParameters extends TimelineQueryParameters { public boolean isDiscussionIndependentFilter() { boolean isContinious = !this.isRetrieveOnlyFollowedItems() && !this.isFavorites() && !this.isNotificationFeed(); if (isContinious) { isContinious = !this.isFeedFi...
// create the query parameters NoteQueryParameters noteQueryParameters = new NoteQueryParameters(); // check the defaults Assert.assertFalse(noteQueryParameters.isFavorites()); Assert.assertFalse(noteQueryParameters.isFollowingFeedAndUnfiltered()); Assert.assertTrue(note...
61826847_14
class DisplayUtil { public static String getTooltipText(GraphEntity entity) { Map<String, Object> properties = entity.getPropertyContainer().getProperties(); String start = "<p width=\"" + LABEL_TEXT_WIDTH + "px\"><b>"; String typesRepresentation = entity.isTypesSingle() ? entity.getTypes(...
properties.put(FIRST_KEY, FIRST_VALUE); assertThat(DisplayUtil.getTooltipText(node)) .containsSubsequence(FIRST_KEY, FIRST_VALUE); } }
61872305_0
class CachedStorage implements Storage { @Override public boolean contains(@NonNull String id) throws IOException { return local.contains(id) || remote.contains(id); } public CachedStorage( @NonNull Storage remote, @NonNull Storage local ); public CachedStorag...
MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setResponseCode(404)); // remote doesn't contain TEST_NAME_1 (before save) server.enqueue(new MockResponse()); // remote contains TEST_NAME_1 (after save) server.enqueue(new MockResponse().setResponseCode(404)...
61942185_0
class WechatPrepayService { static WechatPrepayResponseDto getPrepay(WechatPrepayData prepayData, String hostEndpoint) throws Exception { Assert.isNotNull(hostEndpoint); WechatPrepayRequestDto prepayDto = new WechatPrepayRequestDto( prepayData.getAppId(), prepayData.getMchId(), prep...
Assert.assertNotNull(prepayData); WechatPrepayResponseDto responseDto = WechatPrepayService.getPrepay(prepayData, ""); Assert.assertNotNull(responseDto); Assert.assertEquals("SUCCESS", responseDto.getReturn_code()); Assert.assertNotNull(responseDto.getPrepay_id()); Asser...
61947614_6
class IncomingMessageQueue { public synchronized void addMessage(Peer sourcePeer, int messageType, int dependencyId, ByteBuf content) { if (checkDependency(dependencyId)) { byte[] contentBytes = new byte[content.readableBytes()]; content.readBytes(contentBytes); message...
messageQueue.addMessage(stubPeer, MESSAGE_ID, 2, stubContent); messageQueue.addMessage(stubPeer, OTHER_MESSAGE_ID, 1, stubContent); InOrder inOrder = Mockito.inOrder(processorsService); inOrder.verify(processorsService).getMessageProcessor(OTHER_MESSAGE_ID); inOrder.verify(proce...
61971175_2
class SpanRecorder extends AbstractClosable { void record(Record record) { MutableSpan span = spanMap.get(record.traceId()); if (span == null) { MutableSpan newSpan = new MutableSpan(record.traceId(), Time$.MODULE$.now()); MutableSpan prev = spanMap.putIfAbsent(record.traceId(), newSpan); s...
recorder.record( new Record(root, Time.fromMilliseconds(TODAY), new FancyAnnotation(), empty()) ); assertThat(mapAsJavaMap(stats.counters())).containsExactly( entry(seq("record", "unhandled", FancyAnnotation.class.getName()), 1L) ); } }
62021204_1
class ListenerHandlerFinder extends AbstractHandlerFinder { @Override public Map<Class<?>, Set<EventHandler>> findAllHandlers(Object listener) { Map<Class<?>, Set<EventHandler>> methodsInListener = new HashMap<Class<?>, Set<EventHandler>>(); Class clazz = listener.getClass(); Type[] typ...
Sub listener = new Sub(); Map<Class<? >, Set<EventHandler>> map = new ListenerHandlerFinder().findAllHandlers(listener); assertTrue(map.containsKey(SimpleEvent.class)); Collection<EventHandler> handlers = map.get(SimpleEvent.class); assertTrue(handlers.size() == 1); Iter...
62054952_6
class NetworkMapper { public List<com.nilhcem.droidconat.data.app.model.Speaker> toAppSpeakers(@Nullable List<Speaker> from) { if (from == null) { return null; } return stream(from).map(speaker -> new com.nilhcem.droidconat.data.app.model.Speaker( speaker.getId(...
// Given Speaker speaker1 = new Speaker(1, "speaker1", "title1", "bio1", "website1", "twitter1", "github1", "photo1"); Speaker speaker2 = new Speaker(2, "speaker2", "title2", "bio2", "website2", "twitter2", "github2", "photo2"); List<Speaker> speakers = Arrays.asList(speaker1, speaker2);...
62104898_5
class CachedSearcher implements Searcher { @Override public Result search(Query query) { return search(query, 1); } public CachedSearcher(GoogleSearcher searcher); @Override public Result search(Query query, int pages); public Result cache(); private String expected; private...
Assert.assertEquals(expected, actual.next()); } }
62117812_546
class ConcurrentSortedLongPairSet implements LongPairSet { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('{'); final AtomicBoolean first = new AtomicBoolean(true); longPairSets.forEach((key, longPairSet) -> { longPairSet.forEa...
LongPairSet set = new ConcurrentSortedLongPairSet(16); set.add(0, 0); set.add(1, 1); set.add(3, 3); final String toString = "{[0:0], [1:1], [3:3]}"; System.out.println(set.toString()); assertEquals(set.toString(), toString); } }
62138020_46
class PeppolCompatibilityValidator implements IAS4ProfileValidator { @Override public void validatePMode (@Nonnull final IPMode aPMode, @Nonnull final ErrorList aErrorList) { ValueEnforcer.isTrue (aErrorList.isEmpty (), () -> "Errors in global PMode validation: " + aErrorList.toString ()); try { ...
m_aPMode.getLeg1 ().getSecurity ().setPModeAuthorize (ETriState.UNDEFINED); VALIDATOR.validatePMode (m_aPMode, m_aErrorList); assertTrue ("Errors: " + m_aErrorList.toString (), m_aErrorList.containsAny (x -> x.getErrorText (LOCALE).contains ("mandatory"))); } }
62155865_1
class ImmutableModule { @ImmutableExecutorDecorator Task provideTask(final Task task) { return new TaskDecorator(new DummyExecutor(), task); } } class ImmutableModuleTest { @Test public void givenANonNullDecoratedObject_ShouldExecute() {
final MockTask task = new MockTask(); new ImmutableModule().provideTask(task).invoke(); assertTrue(task.isInvoke); } }
62156481_25
class EncryptedFileSystem extends DelegatingFileSystem { @Override public boolean rename(Path src, Path dst) throws IOException { // Copy key material first so the encrypted file always has key material in the key store even if the // put or rename fails KeyMaterial keyMaterial = keySto...
when(mockFs.rename(path, newPath)).thenReturn(true); doThrow(new IllegalArgumentException()).when(mockKeyStore).remove(anyString()); assertThat(mockedEfs.rename(path, newPath)).isTrue(); } }
62161266_1
class TokenProvider { public boolean validateToken(String authToken) { try { Jwts.parser().setSigningKey(key).parseClaimsJws(authToken); return true; } catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) { log.info("Invalid JWT signature....
String unsupportedToken = createUnsupportedToken(); boolean isTokenValid = tokenProvider.validateToken(unsupportedToken); assertThat(isTokenValid).isEqualTo(false); } }
62177795_129
class MetadataUtils { public static cern.c2mon.server.common.metadata.Metadata parseMetadataConfiguration(Properties properties, cern.c2mon.server.common.metadata.Metadata currentMetadata) { return Optional.ofNullable(properties.getProperty("metadata")) .map(Metadata::fromJSON) .map(newMetadata -...
Metadata currentMetadata = new Metadata(); String currentKey = "currentKey"; currentMetadata.addMetadata(currentKey, "value1"); cern.c2mon.shared.client.metadata.Metadata clientMetadata = new cern.c2mon.shared.client.metadata.Metadata(); String newClientKey = "newClientKey"; clientMetadata.addMe...
62209334_34
class GtfsZipFile { public Path extractStopsFile() throws IOException { return extractFile(STOPS_FILE_NAME); } public GtfsZipFile(Path gtfsZip); public void extractFile(String fileName, Path extractTo); private Path extractFile(String fileName); InputStream getFileInStream(ZipFile zipFile, String ...
// Prepare Path zipFile = Paths.get( "src/test/resources/siri_client/gtfs/data/GtfsWorkspaceTest/ftpWorkspace/israel-public-transportation.zip"); GtfsZipFile gtfsZipFile = new GtfsZipFile(zipFile); // Execute Path actual = gtfsZipFile.extractStopsFile(); // Test assertNotNull(actual)...