id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
34633211_2
class JJJVMInterpreter implements JJJVMConstants { public static Object invoke(final JJJVMClass caller, final JJJVMObject instance, final JJJVMMethod methodToInvoke, final Object[] args, final Object[] stack, final Object[] vars) throws Throwable { final int methodFlags = methodToInvoke.getFlags(); if ((meth...
final JSEProviderImpl provider = new JSEProviderImpl(this); final JJJVMClass testKlazz = loadClassFromClassPath(provider, "com/igormaznitsa/jjjvm/testclasses/TestIssue"); final JJJVMMethod append = testKlazz.findMethod("trampoline", "()Ljava/lang/String;"); String res = (String) append.invoke(null, new ...
34667720_0
class WebLogParser { public static Map<String, Mapper> loadRegistry(Model model) { List<Resource> rs = model.listResourcesWithProperty(RDF.type, LSQ.WebAccessLogFormat).toList(); Map<String, Mapper> result = rs.stream() .filter(r -> r.hasProperty(LSQ.pattern)) .collect(Coll...
// Note: using a '-' for numResponseBytes //String expected = "140.203.154.206 - - [16/May/2014:00:29:09 +0100] \"GET http://localhost:8890/sparql?default-graph-uri=&query=SELECT+%3Fparty+%3Fpage++WHERE+%0D%0A%7B+SERVICE+%3Chttp%3A%2F%2Fdbpedia-subset.system.ip.address%3A8891%2Fsparql%3E+%7B+%3Chttp%3A%...
34685629_7
class VerigreenNeededLogic { public VerigreenNeeded isVerigreenNeeded( final String parentBranchName, final String branchNameToVerify, final String commitId, final String committer) { String reason = ""; boolean ans; boolean shouldRejectCommit = true; ans= (VerigreenMap.get("_protectedBranches"...
VerigreenNeeded verigreenNeeded = CollectorApi.getVerigreenNeededLogic().isVerigreenNeeded( protectedBranch, branch, "", "user1"); Assert.assertEquals(true, verigreenNeeded.getVerigre...
34685800_68
class EclipseCdtFormatterStepImpl { public String format(String raw) throws Exception { //The 'kind' can be set to CodeFormatter.K_UNKNOWN, since it is anyway ignored by the internal formatter TextEdit edit = codeFormatter.format(CodeFormatter.K_UNKNOWN, raw, 0, raw.length(), 0, SpotlessEclipseFramework.LINE_DELI...
String output = format(CPP_FORMATTED.replace("int main() {", "int main() "), config -> {}); assertTrue("Incomplete CPP not formatted on best effort basis.", output.contains("int main()" + LINE_DELIMITER)); } }
34793185_127
class TerminationTreeItemContent implements IsElement { public void setExistingValue(Object value, TerminationConfigOption terminationConfigOption) { TerminationManager operation = terminationManagerMap.get(terminationConfigOption); if (operation != null) { ...
terminationTreeItemContent.setExistingValue("0", TerminationConfigOption.BEST_SCORE_LIMIT); verify(view).setBestScoreLimit("0"); } }
34809191_909
class VaadinConnectController { @PostMapping(path = "/{endpoint}/{method}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<String> serveEndpoint( @PathVariable("endpoint") String endpointName, @PathVariable("method") String methodName, @R...
String inputId = "2222"; String expectedResult = String.format("{\"id\":\"%s\"}", inputId); BridgeMethodTestEndpoint.InheritedClass testEndpoint = new BridgeMethodTestEndpoint.InheritedClass(); String testMethodName = "testMethodFromInterface"; ResponseEntity<String> response = c...
34813674_8
class trityp { public static int type(int Side1, int Side2, int Side3) { int tri_out; // tri_out is output from the routine: // Triang = 1 if triangle is scalene // Triang = 2 if triangle is isosceles // Triang = 3 if triangle is equilateral // Triang...
Assert.assertEquals(trityp.type(1,1,0), 4); } }
34819120_17
class IntrabandProxyUtil { protected static void serializerWrite( MethodNodeGenerator methodNodeGenerator, Type type) { String owner = _SERIALIZER_TYPE.getInternalName(); if (type.getSort() <= Type.DOUBLE) { String name = TextFormatter.format( type.getClassName(), TextFormatter.G); methodNodeGenera...
MethodNode methodNode = new MethodNode( Opcodes.ACC_PUBLIC, "name", "()V", null, null); MethodNodeGenerator methodNodeGenerator = new MethodNodeGenerator( methodNode); InsnList insnList = methodNode.instructions; for (Type type : _types) { IntrabandProxyUtil.serializerWrite(methodNodeGenerator, type...
34824538_140
class VisualRecognition extends BaseService { public ServiceCall<ImageDetailsList> addImages(AddImagesOptions addImagesOptions) { com.ibm.cloud.sdk.core.util.Validator.notNull( addImagesOptions, "addImagesOptions cannot be null"); com.ibm.cloud.sdk.core.util.Validator.isTrue( (addImagesOption...
server.enqueue(jsonResponse(imageDetailsList)); AddImagesOptions options = new AddImagesOptions.Builder() .addImagesFile(fileWithMetadata) .addImageUrl(IMAGE_URL) .collectionId(COLLECTION_ID) .trainingData(TRAINING_DATA) .build(); ImageDet...
34839383_1797
class InternalCacheBuilder { public InternalCache create() throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { synchronized (InternalCacheBuilder.class) { InternalDistributedSystem internalDistributedSystem = findInternalDistributedSystem() .orElseGet(th...
InternalDistributedSystem singletonSystem = singletonSystem(); InternalCache constructedCache = constructedCache(); InternalCacheConstructor cacheConstructor = constructorOf(constructedCache); InternalCacheBuilder internalCacheBuilder = new InternalCacheBuilder( new Properties(), new CacheConf...
34881325_6
class Acacia { public static void stopService(Object aService) { for (Class<?> myInterface : aService.getClass().getInterfaces()) { Service serviceAnnotation = myInterface.getAnnotation(Service.class); if (serviceAnnotation != null) { try ...
TestServiceOnWorkerThread serviceInterface = Acacia.createService( Robolectric.application, TestServiceOnWorkerThread.class); Acacia.stopService(serviceInterface); assertTrue(shadowOf(androidService).isStoppedBySelf()); Class<? extends ServiceConnection> unboundConn = ...
34915443_3
class JSources extends JNode { List<JPackage> getHierarchyPackages(List<JavaPackage> packages) { Map<String, JPackage> pkgMap = new HashMap<String, JPackage>(); for (JavaPackage pkg : packages) { addPackage(pkgMap, new JPackage(pkg)); } // merge packages without classes boolean repeat; do { repeat =...
List<JavaPackage> packages = Arrays.asList( newPkg("a.p1"), newPkg("a.b.c.p2"), newPkg("a.b.c.p3"), newPkg("d.e"), newPkg("d.f.a") ); List<JPackage> out = sources.getHierarchyPackages(packages); assertEquals(out.size(), 2); assertEquals(out.get(0).getName(), "a"); assertEquals(out.get(0...
34915498_11
class HostnameCollapser extends AbstractPathCollapser implements StringCollapser { @Override public <T> Map<String, Collection<T>> collapse(Map<String, Collection<T>> input) { Map<PathName, Collection<T>> inputMap = new HashMap<PathName, Collection<T>>(input.size()); for (Map.Entry<Str...
final HostnameCollapser collapser = new HostnameCollapser(2); List<String> output = new ArrayList<String>(collapser.collapse(nullMap(Arrays.asList( "http://a.example.com:8080", "'none'" ))).keySet()); Collections.sort(output); ...
34951729_3
class DurationCalculator { public long calculateNewDuration(ViscosityInterpolator viscosity, long timesAnimationViewed, long currentDuration) { if (currentDuration == 0) { Log.e("duration was zero"); return 0; } if (timesAnimationViewed == 0) { Log.v("fir...
int timesTransitionViewed = 1; long currentDuration = 50L; calc.calculateNewDuration(mockViscosity, timesTransitionViewed, currentDuration); verify(mockViscosity).calculateDuration(currentDuration, timesTransitionViewed); } }
34964793_1
class FlexibleFactory { @SuppressWarnings("ConstantConditions") public static <T> T create(@NonNull Class<T> itemClass, @Nullable Object... constructorParams) { if (itemClass == null) { throw new IllegalArgumentException("Unknown model class " + itemClass); } try { ...
HeaderModel header = new HeaderModel("H1"); HeaderHolder headerHolder = FlexibleFactory.create(HeaderHolder.class, header); ItemModel item = new ItemModel("I1", "H2"); ItemHolder itemHolder = FlexibleFactory.create(ItemHolder.class, item, headerHolder); assertNotNull(itemHolder...
34966186_14
class MinioClient { public static Builder builder() { return new Builder(); } private MinioClient( HttpUrl baseUrl, String region, boolean isAwsHost, boolean isAcceleratedHost, boolean isDualStackHost, boolean useVirtualStyle, String accessKey, String secretK...
MinioClient.builder().endpoint("https://s3.amazonaws.com.cn").build(); Assert.fail("exception should be thrown"); } }
34971364_6
class Log4JModel { public ImmutableList<Logger> getLoggers() { if (loggers == null) { final Map<String, String> loggerEntries = filterKeys(log4jProperties, startsWith("log4j.logger.")); loggers = FluentIterable.from(loggerEntries.entrySet()) ...
Properties props = new Properties(); props.setProperty("log4j.logger.foo.bar.baz", "debug"); props.setProperty("log4j.additivity.foo.bar.baz", "true"); Log4JModel model = new Log4JModel(props); List<Logger> loggers = model.getLoggers(); assertThat(loggers.size(), is(1)...
34997568_22
class ComposeMatchers { public static <T, U> Matcher<T> hasFeatureValue(Function<T, U> featureFunction, U featureValue) { return hasFeature(featureFunction, equalTo(featureValue)); } private ComposeMatchers(); @SafeVarargs public static ConjunctionMatcher<T> compose(Matcher<? super T>... matchers); @SafeVar...
Matcher<String> actual = hasFeatureValue("x", String::length, 1); assertThat(actual.matches("y"), is(true)); } }
35024150_72
class GitHubBranchHashChangedEvent extends GitHubBranchEvent { @Override public GitHubBranchCause check(@Nonnull GitHubBranchDecisionContext context) throws IOException { GHBranch remoteBranch = context.getRemoteBranch(); GitHubBranch localBranch = context.getLocalBranch(); TaskListener...
commonExpectations(); assertThat( event.check(newGitHubBranchDecisionContext() .withLocalBranch(null) .withBranchTrigger(trigger) .withLocalRepo(localRepo) .withRemoteBranch(null) ...
35031753_0
class XPathResourceBuilderMojo extends AbstractMojo { protected String extractFileContent(final String filename) throws IOException { final StringBuilder sb = new StringBuilder(); String temp = ""; final BufferedReader bufferedReader = new BufferedReader( new FileReader(filename)); try { while (temp...
// assertEquals("line1 line 2", this.mojo.extractFileContent("someFoldersomeFile.txt")); } }
35107906_2
class RedmineGovernorRecorder { public void redmineReportEntries(@Observes After event) { final Method testMethod = event.getTestMethod(); final TestClass testClass = event.getTestClass(); final String redmineServerURL = redmineGovernorConfigurationInstance.get().getServer(); fina...
After after = new After(new FakeTestClass(), getMethod("dummyTest")); redmineGovernorRecorder.redmineReportEntries(after); verify(propertyReportEvent, times(2)).fire(propertyReportEventArgumentCaptor.capture()); List<PropertyReportEvent> propertyReportEvents = propertyReportEventArgum...
35126129_18
class SequenceUtil { public static boolean checkIfLimitReached(long currentValue, long minValue, long maxValue, long incrementBy, long cacheSize) throws SQLException { long nextValue = 0; boolean increasingSeq = incrementBy > 0 ? true : false; // advance currentValue while check...
assertFalse(SequenceUtil.checkIfLimitReached(5, MIN_VALUE, MAX_VALUE, -2/* incrementBy */, CACHE_SIZE)); } }
35132359_23
class FhirSystemDaoDstu1 extends BaseFhirSystemDao<List<IResource>> { @Transactional(propagation = Propagation.REQUIRED) @Override public List<IResource> transaction(List<IResource> theResources) { ourLog.info("Beginning transaction with {} resources", theResources.size()); long start = System.currentTimeMillis...
InputStream bundleRes = FhirSystemDaoDstu1Test.class.getResourceAsStream("/bundle-dstu1.xml"); Bundle bundle = ourFhirContext.newXmlParser().parseBundle(new InputStreamReader(bundleRes)); List<IResource> res = bundle.toListOfResources(); ourSystemDao.transaction(res); Patient ...
35148114_22
class GNConverter { public LexicalResource getLexicalResource() { return lexicalResource; } public GNConverter(GermaNet germaNet, LexicalResource lexicalResource, MetaData alignmentMeta, String resourceVersion, String dtd_version); public void toLMF(); public void toLMF(Lexicon wordNetLexicon); private void...
LexicalResource lr = gnConverter.getLexicalResource(); for(Lexicon lexicon : lr.getLexicons()) { for(LexicalEntry le : lexicon.getLexicalEntries()) { for(Sense sense : le.getSenses()){ List<SemanticLabel> semanticLabels = sense.getSemanticLabels(); assertTrue("Sense does not ha...
35152638_32
class ClassNameBuilder extends IdentifierBuilder { public TypeSpec interfaceSpec(ResourceObject resource, OntGenerationConfig config) throws RepositoryException { return TypeSpec.interfaceBuilder(className(resource, config)).build(); } private ClassNameBuilder(ObjectConnection connection); p...
TypeSpec typeSpec = ClassNameBuilder.forObjectRepository(anno4j.getObjectRepository()) .interfaceSpec(person, config); assertEquals("MyPerson", typeSpec.name); } }
35174991_12
class FileUtils { public static boolean isLocaleFile(String url) { return url != null && url.startsWith(LOCALE_FILE_SCHEME); } private FileUtils(); public static boolean isAbsolute(String url); @NonNull @Contract(pure = true) public static String getCsvFolderName(); private final St...
assertThat(FileUtils.isLocaleFile(localURL)).isTrue(); } }
35185022_110
class VCDiffFileBasedCoder { public static void main(String[] argv) throws Exception { // TODO: JCommander has an issue with boolean arity. Rewrite allow_vcd_target. List<String> newArgv = new LinkedList<String>(Arrays.asList(argv)); ListIterator<String> i = newArgv.listIterator(); ...
VCDiffFileBasedCoder.main(new String[] { "encode", "-interleaved", "-checksum", "-dictionary", dictionaryFile.getCanonicalPath(), "-target", targetFile.getCanonicalPath(), "-delta", deltaFile.getCanonicalPath() ...
35185761_9
class NoxItemCatalog extends Observable { void load(int position, boolean useCircularTransformation) { if (isDownloading(position)) { return; } NoxItem noxItem = noxItems.get(position); if ((noxItem.hasUrl() && !isBitmapReady(position)) || noxItem.hasResourceId() && !isDrawableReady(pos...
List<NoxItem> noxItems = new LinkedList<NoxItem>(); noxItems.add(new NoxItem(ANY_URL)); noxItems.add(new NoxItem(ANY_URL_2)); NoxItemCatalog noxItemCatalog = givenOneNoxItemCatalog(noxItems); noxItemCatalog.load(0, USE_CIRCULAR_TRANSFORMATION); noxItemCatalog.load(1, USE_CIRCULAR_TRANSFORMATION...
35204049_41
class CuratorFactory { @VisibleForTesting void enhanceBuilderWithSecurityParameters(HAConfiguration.ZookeeperProperties zookeeperProperties, CuratorFrameworkFactory.Builder builder) { ACLProvider aclProvider = getAclProvider(zookeeperProperties); ...
when(zookeeperProperties.hasAcl()).thenReturn(true); when(zookeeperProperties.getAcl()).thenReturn("sasl:myclient@EXAMPLE.COM"); when(zookeeperProperties.hasAuth()).thenReturn(false); CuratorFactory curatorFactory = new CuratorFactory(configuration) { @Override pr...
35204051_5
class AnnouncementPresenter extends BasePresenter<AnnouncementMvpView> { public void loadAllAnnouncement(int pageNumber) { checkViewAttached(); compositeDisposable.add(mDataManager.getAllAnnouncement( getAnnouncementQueryOptions(pageNumber)) .observeOn(AndroidSchedul...
when(dataManager.getAllAnnouncement(option)).thenReturn( Observable.<Announcements>error(new RuntimeException())); announcementPresenter.loadAllAnnouncement(1); verify(announcementMvpView, never()).showSnackBar(R.string.no_more_announcement_available); verify(announce...
35211795_48
class FixedRateTimerActionScheduler implements ActionScheduler { @Override public void schedule(final Action action) { if (actionTimerTasks.containsKey(action)) { Logger.v("Already contains action, aborting schedule"); return; } TimerTask taskToExecute = new Tim...
scheduler.schedule(anyAction); timerTask.run(); verify(anyAction).perform(); } }
35228936_18
class TweetQuery { public static String queryOR(final String... conditions) { return Arrays.stream(conditions) .filter(s -> null != s && !s.isEmpty()) .collect(Collectors.collectingAndThen( Collectors.toList(), l -> l.isEmpty()...
assertEquals("@Devoxx", TweetQuery.queryOR("@Devoxx")); } }
35240600_15
class AttributeMethodExtractor { public static Map<String, Method> setters(Class<? extends AnnotatedFileAttributeView> type) { return find(type, Extractor.SETTER); } private AttributeMethodExtractor(); public static Map<String, Method> getters(Class<? extends AnnotatedFileAttributes> type); ...
Map<String, Method> attrs = AttributeMethodExtractor.setters( AnnotatedDosFileAttributeView.class); assertHasAttribute(attrs, "lastModifiedTime"); assertHasAttribute(attrs, "lastAccessTime"); assertHasAttribute(attrs, "creationTime"); } }
35242391_26
class SpotifyOAuthFragment extends BaseOAuthFragment { @Override public String getLoginUrl() { return SpotifyHelper.AUTHORIZE_URL; } @Override public String getScope(); @Override public String getTokenUrl(); @Override public String getClientId(); @Override public String getClientSe...
assertEquals("https://accounts.spotify.com/authorize", fragment.getLoginUrl()); } }
35256352_0
class NationalPlayer { public BigInteger getId() { return id; } public String getFirstName(); public String getLastName(); public Country getCountry(); public int getCareerGoals(); public int getWorldRanking(); public NationalPlayer withCountry(Country country); public NationalPlayer withCareerG...
BigInteger indiaPlayerId = null; BigInteger usaPlayerId = null; BigInteger italyPlayerId = null; // Save all three players savePlayer(indiaPlayer); savePlayer(usaPlayer); savePlayer(italyPlayer); indiaPlayerId = indiaPlayer.getId(); System.out.println("Indian Player Id:" + ...
35263104_171
class ProjectEntity { public boolean pledgeGoalAchieved() { return this.status == ProjectStatus.FULLY_PLEDGED; } public ProjectEntity(UserEntity creator, Project project, FinancingRoundEntity financingRound); @Deprecated /** * @deprecated DO NOT use this one, due to this causes problems in AT...
assertThat(projectEntity.pledgeGoalAchieved(), is(false)); } }
35282952_14
class ErrorEditText extends TextInputEditText { public void setFieldHint(int hint) { setFieldHint(getContext().getString(hint)); } public ErrorEditText(Context context); public ErrorEditText(Context context, AttributeSet attrs); public ErrorEditText(Context context, AttributeSet attrs, ...
mView = (CardEditText) Robolectric.setupActivity(TestActivity.class) .findViewById(R.id.bt_card_form_card_number); mView.setFieldHint(R.string.bt_form_hint_cvv); assertEquals("CVV", ((TextInputLayout) mView.getParent().getParent()).getHint()); assertEquals("CVV", mView....
35297180_1412
class GroupCreationWorkflow implements IsWidget { public void clear() { view.clearNotifications(); createEntity.clear(); groupUsersAssignment.clear(); group = null; } @Inject public GroupCreationWorkflow(final ClientUserSystemManager userSystemManager, ...
tested.group = group; tested.clear(); assertNull(tested.group); verify(createEntity, times(1)).clear(); verify(groupUsersAssignment, times(1)).clear(); verify(view, times(1)).clearNotifications(); verify(view, ...
35303409_0
class NotesStore extends Store { public ObservableList<String> getNotes() { return FXCollections.unmodifiableObservableList(notes); } public NotesStore(); private void processAddNoteAction(AddNoteAction action); private NotesStore store; } class NotesStoreTest { private NotesStore stor...
// given assertThat(store.getNotes()).isEmpty(); // when Dispatcher.getInstance().dispatch(new AddNoteAction("something")); // then assertThat(store.getNotes()).contains("something"); } }
35358657_14
class SystemFileSystem extends AbstractFileSystem { @Override public void deleteRecursively(File file) throws IOException { deleteRecursively(file.toPath()); } @Inject public SystemFileSystem(); @Override public File getTemporaryDirectory(String prefix); @Override public File getTemporaryDirectory(S...
File file = touchAndCreate(tempDir, "file"); File copy = new File(tempDir, "bar"); Files.write("Contents!", file, UTF_8); fs.copyFile(file, copy); fs.deleteRecursively(tempDir); assertThat(tempDir.exists()).isFalse(); assertThat(file.exists()).isFalse(); assertThat(copy.exists()).isFalse...
35370551_26
class IterableUtil { public static <T> Iterable<T> createReverseIterable(List<T> list) { // When the list is empty we can use the "forward" iterable (i.e. the // list itself) also as the reverseIterable as it will do nothing. if (list.size() == 0) { return list; } return new ReverseIterable<T>(list); }...
List<String> list = new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); Iterable<String> iterable = IterableUtil.createReverseIterable(list); Iterator<String> iter = iterable.iterator(); assertTrue(iter.hasNext()); assertEquals("C", iter.next()); assertTrue(iter.hasNext()); assert...
35402802_2
class HasBinary { private HasBinary() {private HasBinary() {} private HasBinary() {private HasBinary(); private HasBinary() {public static boolean hasBinary(Object data); private HasBinary() {private static boolean _hasBinary(Object obj); } class HasBinaryTest { @Test public void anArrayContainsByteArray...
JSONArray arr = new JSONArray("[1, null, 2]"); arr.put(1, "asdfasdf".getBytes(Charset.forName("UTF-8"))); assertTrue(HasBinary.hasBinary(arr)); } }
35448780_79
class Formatter { public void formatSource(CharSource input, CharSink output) throws FormatterException, IOException { // TODO(cushon): proper support for streaming input/output. Input may // not be feasible (parsing) but output should be easier. output.write(formatSource(input.read())); } pub...
assertThat( new Formatter() .formatSource( "class T {\n" + " // MOE: one long incredibly" + " unbroken sentence moving from topic to topic so that no-one had a" + " chance to interrupt;\n" ...
35467512_14
class MLUtils { public static String getDate() { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); Date date = new Date(); return dateFormat.format(date); } public static SamplePoints getSample(String path, String dataType, int sampleSize, boolean containsHeader)...
String date = MLUtils.getDate(); Assert.assertEquals(date.contains("-"), true); Assert.assertEquals(date.contains("_"), true); Assert.assertEquals(!date.contains(":"), true); } }
35482585_91
class SesameValueConverter { Value toSesameValue(Assertion assertion, cz.cvut.kbss.ontodriver.model.Value<?> val) throws SesameDriverException { switch (assertion.getType()) { case DATA_PROPERTY: return SesameUtils.createDataPropertyLiteral(val.getValue(), language(assertion), v...
final String value = "hodnota v cestine"; final Assertion dpAssertion = Assertion.createDataPropertyAssertion(PROPERTY, false); final Value res = converter.toSesameValue(dpAssertion, value(value)); assertTrue(res instanceof Literal); final Literal literal = (Literal) res; ...
35511757_73
class Finder implements Closeable { public List<NGramModel> find(String aGram) { return find(aGram.split(" ")); } public Finder(File aIndexFolder, File nGramFolder); private boolean checkForIndex(File aIndexFolder); public BigInteger freq(String aUnigram); public BigInteger getUn...
File index = testContext.getTestOutputFolder(); // Create index LuceneIndexer indexer = new LuceneIndexer(source, index, 2); indexer.index(); try (Finder f = new Finder(index, jWeb1T)) { // Search and check if data is correct List<NGramModel> result = f....
35532096_199
class FunctionDesc implements ProtoObject<FunctionDescProto>, Cloneable, GsonObject, Comparable<FunctionDesc> { public String toJson() { return CatalogGsonHelper.toJson(this, FunctionDesc.class); } public FunctionDesc(); public FunctionDesc(String signature, Class<? extends Function> clazz, Functi...
FunctionDesc desc = new FunctionDesc("sum", TestSum.class, FunctionType.GENERAL, CatalogUtil.newSimpleDataType(Type.INT4), CatalogUtil.newSimpleDataTypeArray(Type.INT4, Type.INT8)); String json = desc.toJson(); FunctionDesc fromJson = CatalogGsonHelper.fromJson(json, FunctionDesc.class); ass...
35550196_35
class CasMerge { public CasMergeOperationResult mergeSpanAnnotation(SourceDocument aDocument, String aUsername, AnnotationLayer aAnnotationLayer, CAS aTargetCas, AnnotationFS aSourceFs, boolean aAllowStacking) throws AnnotationException { if (existsSameAt(aTargetCas, aSo...
CAS jcas = createJCas().getCas(); Type type = jcas.getTypeSystem().getType(POS.class.getTypeName()); AnnotationFS clickedFs = createPOSAnno(jcas, "NN", 0, 0); CAS mergeCas = createJCas().getCas(); AnnotationFS existingFs = mergeCas.createAnnotation(type, 0, 0); Feature p...
35592079_0
class CargaIndicadorController { @Asynchronous @TransactionAttribute(TransactionAttributeType.NEVER) public void carregaIndicadores(DadosCargaIndicador carga) { String nomeGrupoIndicador = carga.getGrupoIndicador(); String nomeIndicador = carga.getIndicador(); String focoIndicador = carga.getFocoIndicador(); ...
Estado e = new Estado(ESTADO); estadoService.salvar(e); Municipio m1 = new Municipio("", MUNICIPIO1, e); Municipio m2 = new Municipio("", MUNICIPIO2, e); Municipio m3 = new Municipio("", MUNICIPIO3, e); municipioService.salvar(m1); municipioService.salvar(m2); municipioService.salvar(m3); Area are...
35592576_45
class ESHttpJsonUnmarshaller implements ESHttpUnmarshaller { @Override public final Object unmarshal(final DeserializerRegistry registry, final SerializedDataType dataType, final EnhancedMimeType mimeType, final Object data) { if (data == null) { return null; } ...
// PREPARE final SerializedDataType dataType = new SerializedDataType(MyEvent.TYPE.asBaseType()); final EnhancedMimeType mimeType = new EnhancedMimeType( "application/xml; version=1; encoding=utf-8; transfer-encoding=base64"); final DeserializerRegistry registry = create...
35604995_0
class RxPresso implements IdlingResource { public <T> With<T> given(Observable<T> observable) { RxMock mock = Observable.from(mocks).filter(provides(observable)).toBlocking().first(); final With<T> with = new With<>(mock, observable); pendingResources.add(with); with.registerIdleTra...
Observable<Integer> foo = mockedRepo.foo(3); rxPresso.given(foo) .withEventsFrom(SingleEvent.onNext(42)) .expect(any(Integer.class)); Integer result = foo.toBlocking().first(); assertThat(result).isEqualTo(42); } }
35617147_0
class UimaAsExecutionEngine implements TaskExecutionEngine { @Override public String run(Task aConfiguration) throws ExecutionException, LifeCycleException { if (!(aConfiguration instanceof UimaTask)) { throw new ExecutionException("This engine can only execute [" + UimaTask.class.getName() + "]"); } ...
File repo = new File("target/repository"); FileUtils.deleteQuietly(repo); ((FileSystemStorageService) storageService).setStorageRoot(repo); assertNotNull(executionService); assertNotNull(contextFactory); AnalysisEngineDescription desc = createEngineDescription(DummyAE.class); DefaultUimaTask cfg = new ...
35632860_1
class HeaderChunk { void readHeader(InputStream is) throws IOException { int headerRead = 0; while (headerRead < HEADER_SIZE) { final int bytesRead = is.read(header, headerRead, HEADER_SIZE - headerRead); if (bytesRead < 0) { throw new EOFException("Failed to read header."); } ...
try { headerChunk.readHeader(new ByteArrayInputStream(new byte[1])); fail("Incomplete header"); } catch (IOException e) { // everything is OK } } }
35640235_1
class GitHubInteractor { public Observable<SearchResult> searchUsers(final String query) { return Observable.concat(cachedResults(query), networkResults(query)).first(); } public GitHubInteractor(Retrofit retrofit, LruCache<String, SearchResult> cache); private Observable<SearchResult> cachedResults(Str...
SearchItem item = new SearchItem(); item.setLogin("octocat"); item.setAvatarUrl("https://avatars.githubusercontent.com/u/583231?v\u003d3"); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .ad...
35662043_58
class OutputRateCalculator { public void start() { maxRateProvider.start(); } public OutputRateCalculator(ConfigFactory configFactory, MaxRateProvider maxRateProvider); public OutputRateCalculationResult recalculateRate(SendCounters counters, ...
//given OutputRateCalculationScenario scenario = new OutputRateCalculationScenario(calculator); // when scenario.start(10).fastForwardWithSuccesses(10); // then scenario.verifyFinalResult(MAX_RATE, OutputRateCalculator.Mode.NORMAL); } }
35675774_45
class StringLibrary { public static String unique(String string) { return string.intern(); } public static String quoted(String string); public static List<String> split(String chainedStrings, Character character); public static List<String> split(String chainedStrings, String splittingReg...
String a = "abcdjjq"; String b = a + ""; String c = a + ""; assertTrue(a.equals(b)); assertTrue(b.equals(c)); assertTrue(a.equals(c)); assertFalse(a == b); assertFalse(b == c); assertFalse(a == c); assertTrue(a == unique(a)); assertTrue(a == unique(b)); assertTrue(a == unique(c)); } }
35680131_188
class FieldsTypeUtils { static PredicateLeaf.Type toType(Fields fields) { Type type = fields.getType(0); if (type.equals(Double.class)) { return PredicateLeaf.Type.FLOAT; } else if (type.equals(Long.class)) { return PredicateLeaf.Type.LONG; } else if (type.equals(Integer.class)) { ...
Fields fields = new Fields("A", Integer.class); PredicateLeaf.Type fieldsType = toType(fields); assertThat(fieldsType, is (PredicateLeaf.Type.LONG)); } }
35686068_24
class IdentifiableToIdConverter implements Converter { public boolean canConvert(final Class type) { return type.isAssignableFrom(this.type); } public IdentifiableToIdConverter( final Class<Identifiable<?>> type, final Mapper mapper, final ReflectionProvider reflectionProvider, ...
converter = new IdentifiableToIdConverter(User.class); assertTrue(converter.canConvert(User.class)); } }
35702140_29
class WebSocketNativeBalancingHandler extends WebSocketHandlerAdapter { public void setNextHandler(WebSocketHandler handler) { this.nextHandler = handler; handler.setListener(new WebSocketHandlerListener() { @Override public void connectionOpened(WebSocketChannel c...
Mockery context = new Mockery(); final WebSocketHandler nextHandler = context.mock(WebSocketHandler.class); final WebSocketHandlerListener listener = context.mock(WebSocketHandlerListener.class); final WrappedByteBuffer message = new WrappedByteBuffer("test message".getBytes()); ...
35720847_0
class Utils { public static String printTimeDelay(final long timeInMilliseconds) { final Duration duration = new Duration(timeInMilliseconds); final Period period = duration.toPeriod().normalizedStandard(PeriodType.time()); return TIME_FORMATTER.print(period); } private Utils(); public static bo...
assertEquals("34:17:36.789",Utils.printTimeDelay(123456789L)); } }
35725078_25
class ArgCheck { static public long requireStrictlyPostive(long l) throws IllegalArgumentException { return requireStrictlyPostive(l, "long value must be strictly positive"); } private ArgCheck(); static public T requireNonNull(T obj); static public T requireNonNull(T obj, String errMsg)...
ArgCheck.requireStrictlyPostive(1); try { ArgCheck.requireStrictlyPostive(0); Assert.fail("Should have thrown an NPE"); } catch (IllegalArgumentException e) { } try { ArgCheck.requireStrictlyPostive(-1); Assert.fail("Should have thr...
35728528_2
class ExpressionEvaluator { public final Atom evaluate(final String expression) { return evaluate(Expression.parse(expression)); } public ExpressionEvaluator(); public final Atom evaluate(final Expression expression); public final Atom evaluate(final Expression expression, final EvaluationContext context); ...
assertEquals(new BigDecimal(18), evaluator.evaluate("8 + 10").getValue()); assertEquals(new BigDecimal(-2), evaluator.evaluate("8 - 10").getValue()); assertNotEquals(new BigDecimal(21), evaluator.evaluate("7 * 2 + 1").getValue()); } }
35757620_109
class ReceiptPrinter { public String printReceipt(Receipt receipt) { StringBuilder result = new StringBuilder(); for (ReceiptItem item : receipt.getItems()) { String receiptItem = presentReceiptItem(item); result.append(receiptItem); } for (Discount discount ...
receipt.addProduct(toothbrush, 1, 0.99, 0.99); Approvals.verify(new ReceiptPrinter(40).printReceipt(receipt)); } }
35772318_4
class DiscountManagerBean implements DiscountManager { @Override public double findDiscount(Member member) { double discount = 0.0; MembershipLevel ml = membershipLevelManager.findByMemberId(member.getId()); if (ml != null) { switch (ml.getType()) { case SILVER: discount = 0.05; break; cas...
membershipLevel.setType(MembershipLevelType.BRONZE); double discount = bean.findDiscount(member); assertEquals(0.0, discount, 0.0); } }
35775200_12
class WeekUtils { static String[] getWeekdayNames(Locale locale, int day, boolean useThreeLetterAbbreviation){ DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(locale); String[] dayNames = dateFormatSymbols.getShortWeekdays(); if (dayNames == null) { throw new Illegal...
String[] expectedWeekDays = {"Fri", "Sat", "Sun", "Mon", "Tue", "Wed", "Thu"}; String[] actualWeekDays = WeekUtils.getWeekdayNames(Locale.ENGLISH, Calendar.FRIDAY, true); assertArrayEquals(expectedWeekDays, actualWeekDays); } }
35814909_26
class AsyncBuilder { @NonNull @VisibleForTesting @UiThread ExecutorService getFileExecutorService(@NonNull final ImmutableValue<IThreadType> threadTypeImmutableValue) { Log.v(TAG, "getFileExecutorService()"); if (fileExecutorService == null) { Log.d(TAG, "Creating default f...
asyncBuilder .setFileExecutorService(executorService) .build(); assertEquals(executorService, asyncBuilder.getFileExecutorService(new ImmutableValue<>())); } }
35841129_7
class BigdataSailFactory { @Deprecated // We are getting rid of this, right? public static String testServiceEndpointUrl(final String serviceEndpoint) { return normalizeEndpoint(serviceEndpoint); } public static BigdataSailRemoteRepository connect(final String host, final int port); public static Big...
String serviceEndpoint = Config.DEFAULT_ENDPOINT + "/namespace/NAMESPACE"; String normalizedServiceURL = BigdataSailFactory.testServiceEndpointUrl(serviceEndpoint); assertEquals(remoteRepositoryNamespaceUrl, normalizedServiceURL); } }
35880827_3
class DiskBasedCache implements Cache { @Override public synchronized void put(String key, Entry entry) { pruneIfNeeded(entry.data.length); File file = getFileForKey(key); try { FileOutputStream fos = new FileOutputStream(file); CacheHeader e = new CacheHeader(ke...
Cache.Entry e = new Cache.Entry(); e.data = new byte[8]; e.serverDate = 1234567L; e.lastModified = 13572468L; e.ttl = 9876543L; e.softTtl = 8765432L; e.etag = "etag"; e.responseHeaders = new HashMap<String, String>(); e.responseHeaders.put("fruit",...
35882684_4
class HeaderSpanSizeLookup extends GridLayoutManager.SpanSizeLookup { @Override public int getSpanSize(int position) { boolean isHeaderOrFooter = adapter.isHeaderPosition(position) || adapter.isFooterPosition(position); return isHeaderOrFooter ? layoutManager.getSpanCount() : 1; } public Header...
HeaderSpanSizeLookup headerSpanSizeLookup = new HeaderSpanSizeLookupBuilder().withAdapter( new HeaderRecyclerViewAdapterBuilder().withHeader(givenAHeader()) .withItems(givenSomeItems()) .build()) .withGridLayoutManager(new GridLayoutManagerBuilder().withSpanCount(THREE_ROWS)....
35888585_0
class GoogleProvider implements Provider<GooglePluginSettings> { @Override public boolean authorize(GooglePluginSettings pluginSettings, User user) { String username = user.getUsername(); if (isNotBlank(pluginSettings.getAllowedDomains())) { String allowedDomains = pluginSettings.g...
GooglePluginSettings googlePluginSettings = new GooglePluginSettings(); googlePluginSettings.setAllowedDomains("foo.com, bar.com"); assertFalse(new GoogleProvider().authorize(googlePluginSettings, new User("", null, null))); assertFalse(new GoogleProvider().authorize(googlePluginSetting...
35890978_8
class ObjectGraphMeasurer { public static Footprint measure(Object rootObject) { return measure(rootObject, Predicates.alwaysTrue()); } private ObjectGraphMeasurer(); public static Footprint measure(Object rootObject, Predicate<Object> objectAcceptor); static final Object oneEnumField; static final...
ObjectGraphMeasurer.Footprint footprint = ObjectGraphMeasurer.measure(weakRef); assertEquals(new ObjectGraphMeasurer.Footprint(2, 1, 0, NO_PRIMITIVES), footprint); } }
35917780_17
class MeteredConfigurationSource implements ConfigurationSource { @Override public void init() { Timer.Context context = initTimer.time(); try { delegate.init(); } finally { context.stop(); } } public MeteredConfigurationSource(MetricRegistry metricRegistry, String metricPrefix, ...
doThrow(new IllegalStateException("")).when(delegate).init(); assertThatThrownBy(() -> delegate.init()).isExactlyInstanceOf(IllegalStateException.class); } }
35952836_21
class Compiler { public CompilerExecutor newExecutor() { return new CompilerExecutor(this); } public Compiler(FormatterTable formatterTable, PredicateTable predicateTable); public FormatterTable formatterTable(); public PredicateTable predicateTable(); public CompiledTemplate compile(String template...
CodeLimiter limiter = new NoopCodeLimiter(); Context ctx = COMPILER.newExecutor() .template("#{@}#") .json("123") .codeLimiter(limiter) .execute(); // Instructions: root text var text assertEquals(limiter.instructionCount(), 4); assertEquals(ctx.buffer().toString(), "...
35973998_8
class ExpandableRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { @UiThread public void notifyParentRangeChanged(int parentPositionStart, int itemCount) { int flatParentPositionStart = getFlatParentPosition(parentPositionStart); int flatParentPosition = flatParentPosition...
Parent<Object> firstChangedParent = generateParent(false, 3); Parent<Object> secondChangedParent = generateParent(false, 3); assertEquals(25, mExpandableRecyclerAdapter.getItemCount()); verifyParentItemsMatch(mBaseParents.get(4), true, 10); verifyParentItemsMatch(mBaseParents.ge...
36014107_0
class ProjectBaseDir implements Serializable { public static String getProjectBaseDir() { String uri; try { RepoAgent ra = Engine.getRepoAgent(); uri = ra.getAbsoluteURIFromProjectRelativeURI(""); } catch (NoClassDefFoundError e) { if (projectBaseDir == null) { System.err.println("The project base ...
/* ProjectBaseDir test = new ProjectBaseDir(); String baseDir = test.getProjectBaseDir(); assertNotNull(baseDir); File projectBaseDir = new File(baseDir); assertTrue(projectBaseDir.exists()); assertTrue(projectBaseDir.isDirectory()); */ } }
36020033_54
class AnnotationsGenerateFn extends AppFunction { public void run (Parameters p, PrintStream output) throws Exception { String annotationTypeString = null; String[] annotationTypes = null; String index = null; //- Support print to file if (p.isString ("outputFile")) { boolean append = p.g...
ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream (); PrintStream printStream = new PrintStream (byteArrayStream); File nuthinDocFile = FileUtility.createTemporary (); nuthinDocFile.deleteOnExit(); String nuthinDocFilePath = nuthinDocFile.getAbsolutePath (); StreamUtil.copyStri...
36039997_0
class RedisSession extends StandardSession { @Override public void removeAttribute(String name) { super.removeAttribute(name); if (!saveOnChange()) { this.dirty = true; if (log.isTraceEnabled()) { log.trace("Marking session as dirty. Attr [" + name + "] w...
RedisSession rs = session(); rs.removeAttribute("foo"); Assert.assertTrue(rs.isDirty()); rs.clearDirty(); rs.removeAttribute("foo"); Assert.assertTrue(rs.isDirty()); rs.removeAttribute("foo"); Assert.assertTrue(rs.isDirty()); } }
36044977_7
class UnBloomFilter { public boolean containsOrAdd(@NotNull X element) { HashCode code = HASH_FUNC.hashBytes(asBytes.apply(element)); Object prev = array.getAndSet(code.asInt() & sizeMask, element); total++; if ((prev == null || !element.equals(prev))) { hit++; ...
UnBloomFilter<String> filter = new UnBloomFilter<>(32, (String x) -> x.getBytes()); String twentyNineId = "abc"; String thirtyId = "def"; String thirtyThreeId = "ghi"; assertFalse("nothing should be contained at all", filter.containsOrAdd(twentyNineId)); ...
36057427_3
class ApiDeserializer { public <T extends BasicMessage> BasicMessageWithExtraData<T> deserialize(String nameAndJson) { String[] nameAndJsonArray = fromHawkularFormat(nameAndJson); String name = nameAndJsonArray[0]; String json = nameAndJsonArray[1]; // The name is the actual name o...
// tests that this can extract the JSON even if more data follows in the stream ApiDeserializer ad = new ApiDeserializer(); String nameAndJson = EchoRequest.class.getName() + "={\"echoMessage\":\"msg\"}"; String extra = "This is some extra data"; String nameAndJsonPlusExtra = na...
36073969_3
class OozieScheduling { public static void writeCoordinator(Schedule schedule, SchedulableJobManager manager, OutputStream output) throws IOException { XmlStreamWriter streamWriter = WriterFactory.newXmlWriter(output); PrettyPrintX...
ByteArrayOutputStream output = new ByteArrayOutputStream(); SchedulableJobManager manager = JobManagers.createSchedulable(testSchedule, new AppContext(new Configuration())); OozieScheduling.writeCoordinator(testSchedule, manager, output); Document coord = XMLUtil.toDom(output); XPath xpa...
36094718_1
class BrandingMojo extends AbstractNbmMojo { static String[] getLocale(String name) { String suffix = ""; int dot = name.indexOf( "."); if (dot > -1) { //remove file extension suffix = name.substring( dot ); name = name.substring( 0, dot); } String lo...
assertEquals("en_us", BrandingMojo.getLocale( "aaa_en_us.properties")[1]); assertEquals("en_us_ca", BrandingMojo.getLocale( "aaa_en_us_ca.properties")[1]); assertEquals("en_us_ca", BrandingMojo.getLocale( "aa_en_us_ca.properties")[1]); assertEquals("en_us_ca", BrandingMojo.getLocale( "bb...
36096924_12
class SSLUtils { public static boolean isSSL(String urlString) { Preconditions.checkArgument(StringUtils.isNotEmpty(urlString)); return urlString.startsWith("https://"); } public static SSLContext getSSLContext(ClientConfig config); @VisibleForTesting static TrustManager getTrustManager(ClientConfig c...
assertTrue(SSLUtils.isSSL("https://localhost:7187")); assertFalse(SSLUtils.isSSL("http://localhost:7187")); } }
36107965_0
class EsapiDigester implements Digester { @Override public boolean check(String clearText, String cryptedText) { return cryptedText.equals(digest(clearText)); } public EsapiDigester(boolean useClasspath, String esapiResourceDir); @Override public String digest(String clearText); } ...
EsapiDigester digester = new EsapiDigester(true, "esapi"); String clearText = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; System.out.println("clearText="+clearText); System.out.println("clearText.length="+clearText.length()); ...
36161058_0
class Toast { private static android.widget.Toast createOrUpdateToastFromToastBean(android.widget.Toast toast, @NonNull ToastBean bean) { int duration; if (bean.mDuration == android.widget.Toast.LENGTH_SHORT) { duration = android.widget.Toast.LENGTH_SHORT; } else { d...
mockStatic(Toast.class); PowerMockito.doReturn(null).when(Toast.class, "createOrUpdateToastFromToastBean", any(android.widget.Toast.class), any(Toast.ToastBean.class)); Method m = PowerMockito.method(Toast.class,"createOrUpdateToastFromToastBean",android.widget.Toast.class,Toast.ToastBean.class...
36174393_1
class Mvc { public static MvcGraph graph() { if (graph == null) { graph = new MvcGraph(); try { graph.getRootComponent().register(new Object() { @Provides @EventBusC public EventBus eventBusC() { ...
Mvc.graph().inject(this); when(uiThreadRunnerMock.isOnUiThread()).thenReturn(false); eventBusV.post(""); verify(uiThreadRunnerMock, times(2)).isOnUiThread(); verify(uiThreadRunnerMock, times(1)).post(any(Runnable.class)); } }
36211133_1357
class Gamma { public static double logGamma(double x) { double ret; if (Double.isNaN(x) || (x <= 0.0)) { ret = Double.NaN; } else if (x < 0.5) { return logGamma1p(x) - FastMath.log(x); } else if (x <= 2.5) { return logGamma1p((x - 0.5) - 0.5); ...
Assert.assertTrue(Double.isNaN(Gamma.logGamma(0.0))); } }
36250547_9
class TrailStatisticsImpl implements TrailStatistics { @Override public boolean equals(final Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final TrailStatisticsImpl other = (TrailStatisticsImpl) obj; return Objects.equals(th...
final TrailStatistics stats1 = getStats(); assertFalse(stats1.equals(null)); } }
36268631_0
class ReceiverController { @RequestMapping("/{payloadType}/count") public ReceiveCount findReceiveCount(@PathVariable("payloadType") PayloadType payloadType) { return receiveCountService.findReceiveCount(payloadType); } @RequestMapping(method = RequestMethod.POST, value = "/receive") public vo...
// Relies on pre-existing mock data injected via Liquibase in the "test" profile ResultActions actions = mockMvc.perform( get("/" + PayloadType.TEST1 + "/count")); MvcResult result = actions.andExpect( status().isOk()) .andReturn(); String...
36283221_43
class DefaultPrefixFunctionFactory implements PrefixFunctionFactory { @Override public PrefixFunction getInstance(String pattern) { final int[] prefixes = new int[pattern.length()]; prefixes[0] = 0; int length = 0; for (int i = 1; i < pattern.length(); i++) { final c...
final PrefixFunction function = getFactory().getInstance(pattern); assertThat(function, is(notNullValue())); for (int i = 0; i < prefixes.length; i++) { int prefix = prefixes[i]; assertThat(function.prefix(i), is(prefix)); } } }
36284770_2
class IdentifierBrowserBean implements IdentifierBrowser { @Override public Long getObjectId(String identifier) { DigitalObject object = digitalObjectDao.getDigitalObject(identifier); if (object != null) { return object.getId(); } return null; } @Override pu...
Long tested = identifierBrowser.getObjectId("oai:darceo.psnc.pl:0"); Assert.assertNull(tested); } }
36288389_95
class EducationTypeParametersExtractor extends AbstractParametersExtractor<EducationType> { @Override public Map<String, Object> getParameters(final EducationType entity, final Map<String, Object> parameters) { addParameter(entity.getName(), "name", parameters); addParameter(entity.getAbbrName(), "abbrName", pa...
// Given unit.setActive(false); unit.setSecurity(false); EducationType entity = new EducationType(); Map<String, Object> expected = new HashMap<String, Object>(); // When Map<String, Object> actual = unit.getParameters(entity); // Then assertEquals(expected, actual); } }
36297446_3
class AstrixContextImpl implements Astrix, AstrixApplicationContext { @Override public <T> T getBean(Class<T> beanType) { return getBean(beanType, null); } public AstrixContextImpl(Modules modules, AstrixApplicationDescriptor applicationDescriptor); void register(ApiProviderClass apiProvider); void regist...
TestAstrixConfigurer astrixConfigurer = new TestAstrixConfigurer(); astrixConfigurer.registerApiProvider(HelloBeanLibrary.class); AstrixContextImpl AstrixContext = (AstrixContextImpl) astrixConfigurer.configure(); HelloBeanImpl beanA = AstrixContext.getBean(HelloBeanImpl.class); HelloBeanImpl beanB = AstrixC...
36303657_32
class JdbcInventory extends JdbcHelper implements Inventory { @Override public List<InventoryVector> getMissing(List<InventoryVector> offer, long... streams) { for (long stream : streams) { offer.removeAll(getCache(stream).keySet()); } return offer; } public JdbcIn...
InventoryVector newIV = getObjectMessage(1, 200, getGetPubkey()).getInventoryVector(); List<InventoryVector> offer = new LinkedList<>(); offer.add(newIV); offer.add(inventoryVector1); List<InventoryVector> missing = inventory.getMissing(offer, 1, 2); assertEquals(1, missi...
36345024_7
class BoundGoro extends BufferedGoroDelegate { public abstract void bind()public abstract void bind(); public abstract void bind()public abstract void unbind(); private BoundGoro.BoundGoroImpl goro; private BoundGoro.OnUnexpectedDisconnection disconnection; } class BoundGoroTest extends BufferedGoroDelegate { ...
goro = (BoundGoro.BoundGoroImpl) spy(Goro.bindAndAutoReconnectWith(context)); goro.bind(); assertBinding(); reset(goro); goro.onServiceDisconnected(new ComponentName("test", "test")); assertBinding(); } }
36370530_3
class DefaultPropertyFilter implements EncryptablePropertyFilter { @Override public boolean shouldInclude(PropertySource<?> source, String name) { if (isIncludeAll()) { return true; } if (isMatch(source.getName(), excludeSourceNames) || isMatch(name, excludePropertyNames)) ...
DefaultPropertyFilter filter = new DefaultPropertyFilter(null, null, null, Collections.singletonList("some")); MapPropertySource source = new MapPropertySource("applicationConfig", Collections.emptyMap()); assertTrue(filter.shouldInclude(source, "some.property")); } }
36371585_4
class FacebookAuthProvider extends AuthProvider { Collection<String> getPermissions() { return permissions; } public FacebookAuthProvider(String connectionName, AuthenticationAPIClient auth0); FacebookAuthProvider(String connectionName, AuthenticationAPIClient auth0, FacebookApi facebook); ...
assertThat(provider.getPermissions(), is(hasSize(1))); assertThat(provider.getPermissions(), hasItem("public_profile")); } }
36378766_2
class GoogleAuthProvider extends AuthProvider { String getConnection() { return connectionName; } public GoogleAuthProvider(@NonNull String serverClientId, @NonNull AuthenticationAPIClient client); public GoogleAuthProvider(@NonNull String connectionName, @NonNull String serverClientId, @Non...
MatcherAssert.assertThat(provider.getConnection(), is(notNullValue())); } }
36404681_0
class Neo4jFactoryImpl implements Neo4jFactory { protected GraphDatabaseFactory createGraphDatabaseFactory(Map<String, String> config) { if (config != null && config.containsKey("ha.server_id")) return new HighlyAvailableGraphDatabaseFactory(); return new GraphDatabaseFactory(); } @Overrid...
GraphDatabaseFactory factory = new Neo4jFactoryImpl().createGraphDatabaseFactory(Collections.singletonMap("ha.server_id", "1")); assertEquals(true, factory instanceof HighlyAvailableGraphDatabaseFactory); } }
36419249_0
class AsyncContext { @SuppressWarnings("unchecked") protected void releaseData(final D data) { if (async instanceof Releaser) { ((Releaser<D>) async).release(data); } } public AsyncContext(final Context context, final Async<D> async); } class AsyncContextTest { @Test public void releaseS...
class TestAsync implements Async<String>, Releaser<String> { @Override public void subscribe(AsyncObserver<String> observer) { } @Override public void cancel() { } @Override public Async<String> replicate() { return this; } @Override public void rele...
36429443_19
class AccessTokenUtils { public static Optional<String> getAccessTokenFromSecurityContext() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); if (authentication instanceof OAuth2Authentication) { ...
final Authentication userAuthentication = mock(Authentication.class); when(userAuthentication.getDetails()).thenReturn(singletonMap(ACCESS_TOKEN, "1234567890")); SecurityContextHolder.getContext().setAuthentication(new OAuth2Authentication(mock(OAuth2Request.class), userAuthenti...