id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
55726733_21
class GradleTooling { public static ProjectInfo loadProjectInfo(Path projectPath) throws Exception { ProjectInfo projectInfo = null; GradleConnector connector = GradleConnector.newConnector(); connector.forProjectDirectory(projectPath.toFile()); ProjectConnection connection = null; try { connection =...
ProjectInfo projectInfo = GradleTooling.loadProjectInfo(_wsPath); Assert.assertNotNull("liferay/portal:7.2.0-ga1", projectInfo.getDockerImageLiferay()); } }
55814679_1
class SomeClient implements Client { @Override public String getValueFromTheInternet(String id){ return "42"; } @Override public String putValueToTheInternet(String id, String value); Client cut; } class SomeClientTest { Client cut; @Test public void shouldReturn42() throws Exception {
assertThat(cut.getValueFromTheInternet("yo")).isEqualTo("42"); } }
55834606_13
class InterversionConverter { public <T> T convertToLowerVersion(String targetVersion, Object source) { Class<?> sourceType = source.getClass(); SupportedVersion supportedVersion = sourceType.getAnnotation(SupportedVersion.class); if (supportedVersion == null) { throw new IllegalVersionException(ta...
AddressV1 address = converter.convertToLowerVersion("v1", new AddressV2("Samplestreet 1", " ", new CityV2("12345", "Samplecity"))); assertThat(address.getAddressLine1(), is("Samplestreet 1")); assertThat(address.getAddressLine2(), is(" ")); assertThat(address.getZipCode(), is("12345")); assertThat(a...
55874962_1
class MainActivityPresenter extends BasePresenter { @Override public void onUpdateComplete(RequestResult requestResult, ViewModel.QueryEnum query) { if (query instanceof MainActivityViewModel.QueryEnumMainActivity) { if (requestResult == null) { return; } ...
when(mWeatherRequestResult.getRequestStatus()).thenReturn(RequestStatus.FAILED); when(mWeatherRequestResult.getThrowable()).thenReturn(new Exception("This is a mocked exception!")); mPresenter.onUpdateComplete(mWeatherRequestResult, MainActivityViewModel.QueryEnumMainActivity.UPDATE_WEATHER); ...
55884057_2
class SwipeLayout extends FrameLayout { public void startWith(int position) { makeSureOrientationStrategy(); orientationStrategy.startWith(position); } public SwipeLayout(Context context); public SwipeLayout(Context context, AttributeSet attrs); public SwipeLayout(Context contex...
swipeLayout.startWith(0); verify(orientationStrategy).startWith(0); verifyNoMoreInteractions(orientationStrategy); } }
55912872_9
class CollectionUtils { public static boolean containsUserEstimate(final Collection<Estimate> estimates, final String userName) { return estimates.stream().anyMatch(input -> input.getUserName().equalsIgnoreCase(userName)); } private CollectionUtils(); public static boolean containsIgnoreCase...
final Estimate estimate = new Estimate("Rich A", "5"); final Collection<Estimate> estimates = Sets.newHashSet(estimate); assertFalse(CollectionUtils.containsUserEstimate(estimates, "Jimmy Page")); } }
55965971_1
class RegularExpressionMatching { public boolean isMatch(String s, String p) { return false; } private RegularExpressionMatching testObject; private String[][] sp; private boolean[] results; } class RegularExpressionMatchingTest { private RegularExpressionMatching testObject; pr...
for (int i = 0; i < sp.length; i++) { Assert.assertEquals(results[i], testObject.isMatch(sp[i][0], sp[i][1])); } } }
56003224_5
class AclServiceOFFlowBuilder { public static Map<String,List<MatchInfoBase>> programUdpFlow(AceIp acl) { Map<String,List<MatchInfoBase>> flowMatchesMap = new HashMap<>(); SourcePortRange sourcePortRange = acl.getSourcePortRange(); DestinationPortRange destinationPortRange = acl.getDestinat...
AceIpBuilder builder = new AceIpBuilder(); AceIpv4Builder v4builder = new AceIpv4Builder(); v4builder.setSourceIpv4Network(new Ipv4Prefix("10.1.1.1/24")); v4builder.setDestinationIpv4Network(new Ipv4Prefix("20.1.1.1/24")); builder.setAceIpVersion(v4builder.build()); build...
56003499_35
class TepCommandHelper { public boolean isInCache(Uint64 dpnId, String ipAddress, String transportZone) throws TepException { boolean exists = false; final VtepsKey vtepkey = new VtepsKey(dpnId); IpAddress ipAddressObj = IpAddressBuilder.getDefaultInstance(ipAdd...
try { tepCommandHelper.createLocalCache(dpId1, tepIp1, transportZone1); tepCommandHelper.isInCache(dpId1, tepIp1 ,transportZone1); } catch (TepException e) { LOG.error(e.getMessage()); } verify(mockReadTx).read(LogicalDatastoreType.CONFIGURATION,trans...
56008391_27
class EntanglingClass { @VisibleForTesting MethodSpec createEntangleMethod() { MethodSpec.Builder result = MethodSpec.methodBuilder("entangle") .addModifiers(PUBLIC) .addParameter(TypeVariableName.get("T"), "target", FINAL); result.addStatement("this.target = ta...
MethodSpec entangle = entanglingClass.createEntangleMethod(); assertThat(entangle.parameters, hasSize(1)); } }
56037404_0
class MainPresenter implements IMainPresenter { @Override public void loadSpinnerData() { mSpinnerData = mMainModel.loadSpinnerData(); if (mSpinnerData == null || mSpinnerData.size() == 0){ mMainView.showErrorMsg(); return; } mMainView.updateSpinnerData(m...
mMainPresenter.loadSpinnerData(); Mockito.verify(mMainModel).loadSpinnerData(); List<String> data = new ArrayList<>(); Mockito.when(mMainModel.loadSpinnerData()).thenReturn(data); Mockito.verify(mMainView).showErrorMsg(); } }
56039864_3
class NetworkingModule extends ReactContextBaseJavaModule { @ReactMethod /** * @param timeout value of 0 results in no timeout */ public void sendRequest( final ExecutorToken executorToken, String method, String url, final int requestId, ReadableArray headers, ReadableMa...
RCTDeviceEventEmitter emitter = mock(RCTDeviceEventEmitter.class); ReactApplicationContext context = mock(ReactApplicationContext.class); when(context.getJSModule(any(ExecutorToken.class), any(Class.class))).thenReturn(emitter); OkHttpClient httpClient = mock(OkHttpClient.class); NetworkingModule n...
56074333_2
class GetReceivedCards { public void get(Callback callback) { List<Card> receivedCards = database.getReceivedCards(); callback.onGetReceivedCards(receivedCards); } @Inject public GetReceivedCards(Database database); private GetReceivedCards getReceivedCards; @Mock private Database database; @Moc...
List<Card> cards = Arrays.asList(new Card(), new Card()); when(database.getReceivedCards()).thenReturn(cards); getReceivedCards.get(callback); verify(callback).onGetReceivedCards(eq(cards)); } }
56108213_42
class Feed implements Hydratable { public boolean hasMangaLibraryEntries() { return mMangaLibraryEntries != null && !mMangaLibraryEntries.isEmpty(); } public void addAnime(@Nullable final ArrayList<Anime> anime); @Nullable public ArrayList<Anime> getAnime(); @Nullable public ArrayList<Stri...
assertFalse(mFeed.hasMangaLibraryEntries()); } }
56132696_0
class URLValidator extends FieldValidatorSupport { public void validate(Object object) throws ValidationException { String fieldName = getFieldName(); // if there is no value - don't do comparison // if a value is required, a required validator should be added to the field if (obje...
HashMap<String, Object> map = new HashMap<String, Object>(); map.put("url", "http://aaa.bb.com"); try { this.validate(map); } catch (ValidationException e) { Assert.fail(e.getMessage()); } } }
56136555_20
class ClusterDiskSpaceChecker implements DiskSpaceChecker { @Override public boolean isSpaceAvailable() throws DiskSpaceCheckerException { Map<String, DiskSpace> clusterSpace = clusterManager.getDiskSpace(); boolean withinThreshold = true; for (String server : clusterManager.getServers()) { DiskSpace ds = ...
final DiskSpace server0Space = new DiskSpace(128L, 1024L); spaceMap.put(servers[0], server0Space); final DiskSpace server1Space = new DiskSpace(128L, 512L); spaceMap.put(servers[1], server1Space); when(threshold.withinThreshold(server0Space)).thenReturn(true); when(threshold.withinThreshold(server1Space))....
56214716_11
class HBaseTimestampStorage implements TimestampStorage { @Inject public HBaseTimestampStorage(Configuration hbaseConfig, HBaseTimestampStorageConfig config) throws IOException { connection = ConnectionFactory.createConnection(hbaseConfig); this.table = connection.getTable(TableName.valueOf(con...
final long INITIAL_TS_VALUE = 0; HBaseTimestampStorageConfig config = new HBaseTimestampStorageConfig(); HBaseTimestampStorage tsStorage = new HBaseTimestampStorage(hbaseConf, config); // Test that the first time we get the timestamp is the initial value assertEquals(tsStorage....
56219850_29
class ObjectUtil { public static boolean same(Object obj1, Object obj2) { return obj1 == obj2; } public static boolean isNull(Object obj); public static boolean isNotNull(Object obj); public static boolean andIsNull(Object... objects); public static boolean orIsNull(Object... objects); public static boolean ...
String o1 = new String("1"); String o2 = new String("1"); assertTrue(ObjectUtil.same(o1, o1)); assertFalse(ObjectUtil.same(o1, o2)); } }
56249750_0
class ProdutoDAO { public BigDecimal somaPrecosPorTipo(TipoPreco tipoPreco) { TypedQuery<BigDecimal> query = manager .createQuery("select sum(preco.valor) from Produto p " + " join p.precos preco where preco.tipo = :tipoPreco", BigDecimal.class); query.setParameter("tipoPreco", tipoPreco); return quer...
List<Produto> livrosImpressos = ProdutoBuilder .newProduto(TipoPreco.IMPRESSO, BigDecimal.TEN) .mais(3).buildAll(); List<Produto> livrosEbook = ProdutoBuilder .newProduto(TipoPreco.EBOOK, BigDecimal.TEN) .mais(3).buildAll(); livrosImpressos.stream().forEach(produtoDao::gravar); livrosEboo...
56258294_3
class ConsulRateLimiter extends AbstractRateLimiter { @Override protected void saveRate(Rate rate) { String value = ""; try { value = this.objectMapper.writeValueAsString(rate); } catch (JsonProcessingException e) { log.error("Failed to serialize Rate", e); ...
JsonProcessingException jsonProcessingException = Mockito.mock(JsonProcessingException.class); when(objectMapper.writeValueAsString(any())).thenThrow(jsonProcessingException); ConsulRateLimiter consulRateLimiter = new ConsulRateLimiter(rateLimiterErrorHandler, consulClient, objectMapper); ...
56258575_13
class HttpHandler extends NanoHTTPD { @Override public Response serve(IHTTPSession session) { if (!apiAuthEnabled || hasValidCredentials(session)) { return respond(session); } return newFixedLengthResponse(Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, "Invalid API key\r\n"); ...
Configuration config = Configuration.getDefaultConfiguration(); config.global.httpApiAuthEnabled = true; DiagnosticsApi mxBean = mock(DiagnosticsApi.class); HttpHandler httpApi = new HttpHandler(config, mxBean); IHTTPSession session = mock(IHTTPSession.class); when(sessi...
56278667_91
class SearchHostProvider { public String getSearchHost() { String scheme = isToolboxEnableHttpScheme ? "http" : aptoideWebServicesScheme; return "http".equals(scheme) ? scheme + "://" + aptoideWebServicesSearchHost + "/v1/" : scheme + "://" + aptoideWebServicesSearchSslHost + "/v1/"; } public S...
SearchHostProvider searchHostProvider = new SearchHostProvider(false, "https", "buzz.aptoide.com:10001", "buzz.aptoide.com:10002"); String searchHost = searchHostProvider.getSearchHost(); assertEquals(searchHost, "https://buzz.aptoide.com:10002/v1/"); } }
56323969_241
class WorldpayOrderModificationListener extends AbstractEventListener<OrderModificationEvent> { @Override protected void onEvent(final OrderModificationEvent orderModificationEvent) { final OrderNotificationMessage orderNotificationMessage = orderModificationEvent.getOrderNotificationMessage(); ...
when(journalReplyMock.getJournalType()).thenReturn(CANCELLED); testObj.onEvent(orderModificationEventMock); verify(worldpayCartServiceMock, never()).setWorldpayDeclineCodeOnCart(anyString(), anyString()); verify(modelServiceMock).save(worldpayOrderModificationModelMock); verify...
56365609_5
class TopicMatcher { public static boolean match(String topicFilter, String topicName) { if (!TopicMatcher.isValid(topicFilter, true) || !TopicMatcher.isValid(topicName, false)) { return false; } if ((topicFilter.startsWith(MULTI_LEVEL_WILDCARD) || topicFilter.startsWith(SINGLE_LEVEL_WILDCARD)) && topicName....
Assert.assertThat(TopicMatcher.match("test/1/2", "test/1/2"), IsEqual.equalTo(true)); Assert.assertThat(TopicMatcher.match("test+", "test_1"), IsEqual.equalTo(false)); Assert.assertThat(TopicMatcher.match("test#", "test_1"), IsEqual.equalTo(false)); Assert.assertThat(TopicMatcher.match("+test+", "1_test"), Is...
56423934_0
class JavaIndexArtifact extends IndexArtifact { @Override protected Map<String, Boolean> getFileTypes() { return fileTypes; } public JavaIndexArtifact(String location); public String getSnapshotVersion(); public void setSnapshotVersion(String snapshotVersion); @Override publi...
JavaIndexArtifact jia = new JavaIndexArtifact(""); Map<String, Boolean> types = jia.getFileTypes(); assertFalse(types.get("jar")); assertFalse(types.get("jar.sha1")); assertFalse(types.get("jar.md5")); assertFalse(types.get("pom")); assertFalse(types.get("pom.sha1")); assertFalse(types.get("pom.md5")...
56433446_0
class PathStore { public String[] getPaths() { Set<Node> endPoints = mRoot.getEndPoints(); String[] result = new String[endPoints.size()]; int index = 0; for (Node node : endPoints) { result[index] = node.getPath(); index++; } re...
PathStore store = new PathStore(); assertEquals("Expected one element length if nothing added", 1, store.getPaths().length); assertEquals("Expected empty", true, store.isEmpty()); store.add("1"); assertEquals(1, store.getPaths().length); assertEquals("Expected not empty"...
56442452_47
class MigraMongo { public MigraMongoStatus status(String fromVersion) { final Iterable<MigrationEntry> migrations = migrationHistoryService.findMigrations(fromVersion); for (MigrationRun migEntry : migrations) { if (migEntry.getStatus() == MigrationStatus.ERROR) { return...
// given when(migEntryService.findMigrations("1")) .thenReturn(Arrays.asList(createMigrationEntry("1", "2", MigrationStatus.OK))); // when final MigraMongoStatus status = migraMongo.status("1"); // then assertThat(status.status, is(MigrationStatus.OK)); ...
56527099_10
class HttpsConfiguration { public static Builder builder() { return new Builder(); } private HttpsConfiguration(); public HttpsConfiguration(String serverKeystorePath, String serverKeystorePassword, String clientKeystorePath, String clientKeystorePassword, String truststorePath, ...
public void testNoTrustPass() throws Exception { try { HttpsConfiguration.builder() .serverKeystorePath("sPath") .serverKeystorePassword("sPass") .truststorePath("tPath") .verifyPeerCert("False") .build()...
56551000_92
class TraceContextCodec implements Codec<TextMap> { @Override public void inject(JaegerSpanContext spanContext, TextMap carrier) { char[] chars = new char[TRACEPARENT_HEADER_SIZE]; chars[0] = VERSION.charAt(0); chars[1] = VERSION.charAt(1); chars[2] = TRACEPARENT_DELIMITER; HexCodec.writeHexLon...
Map<String, String> carrier = new HashMap<>(); TextMapAdapter textMap = new TextMapAdapter(carrier); long traceIdLow = 1; long spanId = 2; long parentId = 3; long traceIdHigh = HexCodec.hexToUnsignedLong("c281c27976c85681", 0, 16); JaegerSpanContext spanContext = new JaegerSpanContext(traceI...
56572755_0
class JpaProcessor implements BootPlugin { public void process(Writer writer, List<Class<?>> annotatedList) throws Exception { Set<String> puNames = new HashSet<String>(); XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLStreamWriter w = new IndentingXMLStreamWriter(xof.createXMLSt...
JpaProcessor processor = new JpaProcessor(); Map<PersistentUnit, List<? extends AnnotationMirror>> units = new HashMap<>(); PersistentUnit pu = getTestPersitentUnit(); units.put(pu, Collections.emptyList()); URL url = this.getClass().getResource("/expected_persistence.xml"); ...
56590318_0
class ConfigurationTemplatesDao implements TemplatesDao, InitializingBean { protected TemplateDefinitionImpl loadTemplate(Path p) throws IOException { ObjectMapper mapper = new ObjectMapper(); TemplateDefinitionImpl t = mapper.readValue(p.toFile(), TemplateDefinitionImpl.class); return t; ...
ConfigurationTemplatesDao dao = new ConfigurationTemplatesDao(null); TemplateDefinitionImpl t = dao.loadTemplate(Paths.get(getClass().getResource("/templates-test/overshootUndershoot.json").toURI())); MatcherAssert.assertThat(t.getId(), CoreMatchers.is("overshootUndershoot")); MatcherA...
56611216_24
class OemBO { public List<OemData> getAllOem() { List<OemData> allOemData = new ArrayList<OemData>(); try { List<TblOem> allRecords = tblOemJpaController.findTblOemEntities(); for (TblOem tblOem : allRecords) { OemData oemData = new OemData(tblOem.getName(),...
System.out.println("getAllOem"); OemBO instance = new OemBO(); // int expResult = 1; List result = instance.getAllOem(); assertNotNull(result); // don't check for a specific record count because this can change during testing/development } }
56649404_7
class StatisticsPresenter implements StatisticsContract.Presenter { @Override public void start() { loadStatistics(); } public StatisticsPresenter(@NonNull TasksRepository tasksRepository, @NonNull StatisticsContract.View statisticsView); private void loadS...
// Given an initialized StatisticsPresenter with no tasks TASKS.clear(); // When loading of Tasks is requested mStatisticsPresenter.start(); //Then progress indicator is shown verify(mStatisticsView).setProgressIndicator(true); // Callback is captured and invok...
56670932_2
class PercentageOperator extends Operator<String> { @Override public Flag.FlagResultStatus appliesTo(@Nullable String value) throws NumberFormatException { if (StringUtils.isEmpty(value)) { return DISABLED; } final int val = Integer.parseInt(value); //If there is no...
PercentageOperator percentageOperator = new PercentageOperator("modulo", 10, 5); assertEquals(Flag.FlagResultStatus.DISABLED, percentageOperator.appliesTo("0")); } }
56679521_31
class ConfigurableWeightLoadBalance extends ActiveWeightLoadBalance<T> { @Override protected void doSelectToHolder(Request request, List<Referer<T>> refersHolder) { if (holder == emptyHolder) { return; } RefererListCacheHolder<T> h = this.holder; int i = 0, j = 0; ...
generate(3, new int[] {2, 3, 5}, new int[] {3, 4, 5}); List<Referer<IHello>> list = new ArrayList<Referer<IHello>>(); balance.doSelectToHolder(new DefaultRequest(), list); assertTrue(list.size() > 0 && list.size() <= ConfigurableWeightLoadBalance.MAX_REFERER_COUNT); } }
56690117_871
class DefaultChooser extends Chooser { @Override public BigInteger getDhServerPublicKey() { if (context.getServerDhPublicKey() != null) { return context.getServerDhPublicKey(); } else { return config.getDefaultServerDhPublicKey(); } } DefaultChooser(Tl...
context.setServerDhPublicKey(null); config.setDefaultServerDhPublicKey(BigInteger.ONE); assertEquals(BigInteger.ONE, config.getDefaultServerDhPublicKey()); assertEquals(BigInteger.ONE, chooser.getDhServerPublicKey()); context.setServerDhPublicKey(BigInteger.TEN); assertEq...
56703957_8
class RemoveOneTokenFromPhrase extends QueryRelaxerHeuristic { @Override public Set<RelaxerSuggestion> createSuggestions(SolrQueryRequest req) { List<String> tokens = new ArrayList<String>(); int countOfQuotes = 0; SolrParams params = req.getParams(); String userQuery = params.get(CommonParams...
Set<RelaxerSuggestion> sugs = heuristic.createSuggestions(req(CommonParams.Q, "\"some\" test \"")); verify(sugs, "test \"", "\"some\" \""); } }
56717384_36
class Container extends Box { public Dimension getUsedSpace() { Dimension maxBox = Dimension.EMPTY; for (Level level : levels) { maxBox = getUsedSpace(level, maxBox); } return maxBox; } public Container(Container container); public Container(Dimension dimension, int weight); public Container(int w,...
assertEquals(new Dimension(0, 0, 0), new Container(0, 0, 0, 0).getUsedSpace()); } }
56718024_27
class ProvisioningProfile implements Comparable<ProvisioningProfile> { public static ProvisioningProfile find(List<ProvisioningProfile> profiles, String search) { for (ProvisioningProfile p : profiles) { if (p.uuid.equals(search) || p.appIdPrefix.equals(search) || p.appIdName != null && p.appId...
ProvisioningProfile p1 = createProfile("Profile 1", "App 1", "DF6YH89WE3", "DF6YH89WE3.*", false, null, "0123456789"); ProvisioningProfile p2 = createProfile("Profile 2", "App 2", "HSKDO63H63", "HSKDO63H63.com.*", false, null, "2123456789"); ProvisioningProfile p3 = createProfile("Profile 3", "A...
56729247_1
class Instrumenter { public static final void instrument(String rtJar, String outJar) throws NoSuchAlgorithmException, IOException { Logger.getGlobal().log(Level.FINE, "Instrumenting " + rtJar + " into " + outJar); new Instrumenter().process(rtJar, outJar); } private Instrumen...
try { Instrumenter.instrument(Paths.get("resources", "doesnotexist.jar").toString(), Paths.get("resources", "doesnotexistOut.jar").toString()); fail("Expected an IOException to be thrown"); } catch (IOException exc) { assertThat(exc...
56730584_3
class MD5 { public static byte[] hash(byte[] source) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); return digest.digest(source); } catch (NoSuchAlgorithmException e) { logger.error("Failed to find MD5"); } return null; } ...
byte[] hash = MD5.hash(TestConstants.msg.getBytes()); Assert.assertEquals(TestConstants.md5HashedBase64Msg, Base64.encodeToString(hash)); } }
56735986_14
class TransactionContextExecutor extends Observable<T> { public TransactionContextExecutor<T> withSingleTransaction() { return new TransactionContextExecutor<>(SINGLE_TRANSACTION_TRANSACTION_CONTEXT, provider, connectionConsumer); } public TransactionContextExecutor( TransactionContext transactionConte...
Connection c = mock(Connection.class); ConnectionPool.of(c) .execute(connection -> just(null, null)) .withSingleTransaction() .toBlocking().subscribe(o -> {}, throwable -> {}); verify(c, times(1)).close(); } }
56748637_33
class QuestionWord implements IAnalyzer { public QuestionWord() { ArrayList<String> attributeValues = new ArrayList<String>(); attributeValues.add("Who"); attributeValues.add("What"); attributeValues.add("When"); attributeValues.add("Where"); attributeValues.add("Which"); attributeValues.add(Commands...
QuestionWord questionWord = new QuestionWord(); ArrayList<Attribute> fvWekaAttributes = new ArrayList<Attribute>(); fvWekaAttributes.add(questionWord.getAttribute()); new Instances("Test", fvWekaAttributes, 1 ); Instance test = new DenseInstance(fvWekaAttributes.size()); test.setValue(questionWord.getAttrib...
56765949_4
class MvpConductorLifecycleListener extends Controller.LifecycleListener { @Override public void preDestroyView(@NonNull Controller controller, @NonNull View view) { P presenter = getCallback().getPresenter(); if (presenter == null) { throw new NullPointerException( "Presenter returned from g...
MvpPresenter<MvpView> presenter = Mockito.mock(MvpPresenter.class); Controller controller = Mockito.mock(Controller.class); View view = Mockito.mock(View.class); MvpConductorDelegateCallback<MvpView, MvpPresenter<MvpView>> callback = Mockito.mock(MvpConductorDelegateCallback.class); MvpCon...
56791509_2
class RESTMockServer { public static MatchableCall whenPUT(Matcher<RecordedRequest> requestMatcher) { return RESTMockServer.whenRequested(allOf(isPUT(), requestMatcher)); } private RESTMockServer(); public static SSLSocketFactory getSSLSocketFactory(); public static X509TrustManager getT...
String path = "/sample"; String worksBody = "works"; MatchableCall matchableCall = RESTMockServer.whenPUT(pathEndsWith(path)); assertNotNull(matchableCall); assertEquals(0, matchableCall.getNumberOfAnswers()); verify(RESTMockServer.dispatcher, never()).addMatchableCall(ma...
56853150_7
class TPUAnalysis { public void run(String configPath, String outputPath, long timeMin, long timeMax, int limit)throws Exception { FlinkEnvManager fem = new FlinkEnvManager(configPath, "converterJob", TableIdentifier.RAW_TWITTER_DATA.get(),null); DataSet<Tuple2<Key,Value>> rawTwit...
tmpSettingsDir.create(); File settings = tmpSettingsDir.newFile("settings"); File output = tmpSettingsDir.newFile("outputcsv"); output.delete(); Connector conn = amc.getConnector(); System.out.println("I am connected as: " + conn.whoami()); conn.tableOperations(...
56855940_6
class MainActivityPresenter implements DialogInterface.OnClickListener { public void onTimingClick(String timing) { sharedPreferences.edit().putBoolean(Constants.APP_LOCK_ACTIVATED, false).apply(); storeTiming(timing); mainActivityView.showToast(Constants.OVERLAY_DEACTIVATED_MESSAGE); restoreToDefaul...
mainActivityPresenter.onTimingClick("3 min"); verify(mainActivityView).showToast(Constants.OVERLAY_DEACTIVATED_MESSAGE); verify(mainActivityView).launchActivity(Utils.getHomeScreenIntent()); verify(mainActivityView).hideTimingGrid(); verify(mainActivityView).showActivateButton(); verify(mainActi...
56890246_2
class TracerParameters { @SuppressWarnings({"unchecked", "rawtypes"}) public static Map<String, String> getParameters() { Properties props = Configuration.loadConfigurationFile(); loadSystemProperties(props); for (String propName : props.stringPropertyNames()) { String valu...
Properties props = new Properties(); props.setProperty(TracerParameters.ACCESS_TOKEN, ACCESS_TOKEN); props.setProperty(TracerParameters.COMPONENT_NAME, COMPONENT_NAME); props.setProperty(TracerParameters.COLLECTOR_CLIENT, COLLECTOR_CLIENT); props.setProperty(TracerParameters.COLL...
57079254_7
class StatisticsPresenter implements StatisticsContract.Presenter { @Override public void start() { loadStatistics(); } public StatisticsPresenter( @NonNull UseCaseHandler useCaseHandler, @NonNull StatisticsContract.View statisticsView, @NonNull GetTasks ge...
// Given an initialized StatisticsPresenter with no tasks TASKS.clear(); // When loading of Tasks is requested mStatisticsPresenter.start(); //Then progress indicator is shown verify(mStatisticsView).setProgressIndicator(true); // Callback is captured and invok...
57081740_1
class BotsHttpClient extends CloseableHttpClient { @Override public CloseableHttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException { HttpRequestWrapper wrap = HttpRequestWrapper.wrap(request); adviseRobotsTxt(wrap.getURI()); wrap.setURI(applyPHP(wrap.getURI())); r...
Bots bots = BotsUtils.readBots("http://localhost:5000/robots.txt"); BotsHttpClient client = new BotsHttpClient(bots); HttpGet request = new HttpGet("http://localhost:5000/data.txt"); HttpResponse response = client.execute(request); assertNotNull("No response", response); try (InputStre...
57096675_0
class Functional { public static <R> Future<List<R>> allOfFutures(List<Future<R>> futures) { return CompositeFutureImpl.all(futures.toArray(new Future[futures.size()])) .map(v -> futures.stream() .map(Future::result) .collect(Collectors.toList()) ); } private Functional(); } c...
List<Future<Integer>> list1 = Arrays.asList(Future.succeededFuture(2), Future.succeededFuture(9), Future.succeededFuture(17)); Future<List<Integer>> fs1 = Functional.allOfFutures(list1); List<Integer> cpList = Arrays.asList(2, 9, 17); assertEquals(fs1.succeeded(), true); assertEquals(fs1.resul...
57125528_11
class CSVMetadataLoader extends FileWithMetadataAction implements EOCAware { public String[] readMetadataFields(CSVReader reader) throws IOException { // read first line from the file, with metadata description String[] metadataFields = reader.readNext(); if(metadataFields==null) throw new RuntimeException...
setUp(); CSVReader reader = metadataLoader.createReader(); String[] metadataFields = metadataLoader.readMetadataFields(reader); assertEquals(4, metadataFields.length); assertEquals("path",metadataFields[0]); assertEquals("InputMetadata1",metadataFields[1]); assertEquals("InputMetadata2",metadataFields[2]...
57126883_2
class XicidailiProxyListPageParser implements ProxyListPageParser { @Override public List<Proxy> parse(String hmtl) { Document document = Jsoup.parse(hmtl); Elements elements = document.select("table[id=ip_list] tr[class]"); List<Proxy> proxyList = new ArrayList<>(elements.size()); ...
SimpleHttpClient simpleHttpClient = new SimpleHttpClient(null); String r = simpleHttpClient.get("http://www.xicidaili.com/wt/1.html"); XicidailiProxyListPageParser pageParser = new XicidailiProxyListPageParser(); List<Proxy> proxyList =pageParser.parse(r); Assert.assertTrue(proxy...
57191077_2
class HttpDaemon { public static void registerServlet(String urlPattern, HttpServlet servlet) { sServletMap.put(urlPattern, servlet); } public HttpDaemon(int port); public HttpDaemon(); public static int getPort(); public static HttpDaemon getSingleton(); public void start(); ...
HttpDaemon.registerServlet("/", new HttpServlet() { @Override public HttpResponse doGet(HttpRequest request) { return null; } @Override public HttpResponse doPost(HttpRequest request) { request.parseMultipartBody(repos...
57194230_3
class Container { public String createClasspath(String basedir, String aplVersion) { try { Stream<Path> paths = Files.walk(Paths.get(basedir)); String jarsPath = paths .filter(path -> path.toFile().isDirectory() && path.toFile().getName().contains(aplVersion)) ...
Container sut = new Container(1); String basePath = new File(ContainerTest.class.getClassLoader().getResource("containerTestResources").getPath()) .getAbsolutePath(); assertThat(sut.createClasspath(basePath, "0.2.0")).isEqualTo(basePath); } }
57202360_28
class DrawerPresenter extends BaseActivityPresenter<DrawerMvp.View> implements DrawerMvp.Presenter { @Override public void onNavigationItemSelected(@IdRes int itemId) { if (itemId != selectedItemId) { switch (itemId) { case R.id.drawer_nav_schedule: view....
// Given presenter.selectedItemId = 0; // When presenter.onNavigationItemSelected(R.id.drawer_nav_speakers); // Then verify(view).showFragment(any(SpeakersListFragment.class)); } }
57251243_437
class BiConsumerWithTracing implements BiConsumer<T, U> { public static <T, U> BiConsumerWithTracing<T, U> withTracing(BiConsumer<T, U> origBiConsumer) { return new BiConsumerWithTracing<>(origBiConsumer); } public BiConsumerWithTracing(BiConsumer<T, U> origBiConsumer); public BiConsumerWith...
"true", "false" }) @Test public void pair_constructor_sets_fields_as_expected_when_pair_is_null(boolean useStaticFactory) { // when BiConsumerWithTracing instance = (useStaticFactory) ? withTracing(biConsumerMock, (Pair)null) ...
57261362_3
class RSAUtils { public static byte[] encryptByPublicKey(byte[] data, RSAPublicKey publicKey) { try { Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_PADDING); cipher.init(Cipher.ENCRYPT_MODE, publicKey); // 模长 int key_len = publicKey.getModulus().bitLength(...
} public static Pair<RSAPublicKey, RSAPrivateKey> genKeyPair(int rsaKeySize); public static String encodeBase64(Key key); public static PrivateKey decodePrivateKey(String key); public static PublicKey decodePublicKey(String publicKey); public static String sign(byte[] data, String privateKey);...
57263576_18
class WXText extends WXComponent { @Override public WXTextView getView() { return (WXTextView) super.getView(); } public WXText(WXSDKInstance instance, WXDomObject node, WXVContainer parent, boolean lazy); @Override protected void initView(); @Override public void updateExtra(Object ...
testBind(); Map<String, Object> prop = new HashMap<>(); prop.put(WXDomPropConstant.WX_ATTR_DISABLED, "false"); prop.put(WXDomPropConstant.WX_OPACITY, 0.8f); mWXText.updateProperties(prop); assertTrue(mWXText.getView().isEnabled()); assertTrue(mWXText.getView().get...
57338026_212
class AwsSecurityContextFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { requestContext.setSecurityContext(createSecurityContext()); } public AwsSecurityContextFilter(); public AwsSecurityContextFilter(Collection<String> allo...
GatewayRequest request = new GatewayRequestBuilder() .prepareCustomAuthorizerRequest(false) .build(); SecurityContext sc = filter(request); assertNull(sc.getUserPrincipal()); } }
57401572_44
class SpringBootAnnotationConfigProvider extends HttpConfigurationProvider { @Override @Nullable public Configuration getConfiguration(final ServletContext servletContext) { if (!this.properties.isEnabled()) { return null; } // Generate a list of all relevant annotations final Set<Class<? extends Annot...
this.webApplicationContextRunner .withPropertyValues("joinfaces.rewrite.annotation-config-provider.enabled=false") .run(context -> { SpringBootAnnotationConfigProvider annotationConfigProvider = context.getBean( SpringBootAnnotationConfigProvider.class); assertThat(annotationConfigProvider).isNotNu...
57461213_51
class ExaminePlugin extends Plugin { @VisibleForTesting void getItemPrice(int id, ItemComposition itemComposition, int quantity) { // quantity is at least 1 quantity = Math.max(1, quantity); final int gePrice = itemManager.getItemPrice(id); final int alchPrice = itemComposition.getHaPrice(); if (gePrice ...
ItemComposition itemComposition = mock(ItemComposition.class); when(itemComposition.getName()).thenReturn("Abyssal whip"); when(itemComposition.getHaPrice()).thenReturn(2); when(itemManager.getItemPrice(ItemID.ABYSSAL_WHIP)).thenReturn(3); examinePlugin.getItemPrice(ItemID.ABYSSAL_WHIP, itemComposition, 2_000...
57613683_0
class Jsouper { public <T> ElementAdapter<T> adapter(Type type) { return adapter(type, Util.NO_ANNOTATIONS); } public Jsouper(Builder builder); public ElementAdapter<T> adapter(Type type, Set<? extends Annotation> annotations); static final String MOVIE_HTML; final Document document; } class Jsou...
Jsouper jsouper = new Jsouper.Builder() .add(Movie.class, new MovieAdapter()) .build(); ElementAdapter<Movie> elementAdapter = jsouper.adapter(Movie.class); Movie movie = elementAdapter.fromElement(document); assertThat(movie).isEqualTo(new Movie("Deadpool", "Sample description", 4)); ...
57803948_11
class ReflectUtils { public static String createJson(Object obj) { final Map<String, ClassGetSetDTO> map = getFieldsTypeMap(obj.getClass()); String preKey = map.keySet().isEmpty() ? null : map.keySet().iterator().next(); if(map.size() == 1 && preKey != null && preKey.equals(StringConstants.EMPTY)){ ClassGetS...
Throwable exception = assertThrows(RoboReflectException.class, () -> { Map<String, PathAttributeDTO> map = new HashMap<>(); map.put("one", new PathAttributeDTO("one1", "1")); map.put("two", new PathAttributeDTO("two2", "2")); ReflectUtils.createJson(map); }); assertTrue(exception.getMessage().starts...
57921720_5
class SetVariablesConfirmation implements Confirmation { @Override public boolean validate() { return setVariableResult != null && setVariableResult.length > 0 && Arrays.stream(setVariableResult) .allMatch(setVariableResult -> setVariableResult.validate()); } public SetVariable...
boolean expected = false; SetVariablesConfirmation sut = new SetVariablesConfirmation(); boolean result = sut.validate(); Assert.assertEquals(expected, result); } }
57926203_280
class SfcIosXeUtils { static InstanceIdentifier<Local> createLocalSffIid() { return InstanceIdentifier.builder(Native.class) .child(ServiceChain.class) .child(org.opendaylight.yang.gen.v1.urn.ios.rev160308._native.service.chain.ServiceFunctionForwarder.class) ...
InstanceIdentifier<Local> result = SfcIosXeUtils.createLocalSffIid(); // Test IID InstanceIdentifier<Local> testIid = InstanceIdentifier.builder(Native.class).child(ServiceChain.class) .child(org.opendaylight.yang.gen.v1.urn.ios.rev160308._native.service.chain.ServiceFunctionForw...
57942251_1
class IonParser extends ParserMinimalBase { @Override public NumberType getNumberType() throws IOException { IonType type = _reader.getType(); if (type != null) { // Hmmh. Looks like Ion gives little bit looser definition here; // harder to pin down exact type. But l...
final ObjectReadContext ctxt = ObjectReadContext.empty(); final byte[] data = "{ score:0.291e0 }".getBytes(); IonSystem ion = IonSystemBuilder.standard().build(); final IonValue ionFloat = ion.newFloat(Float.MAX_VALUE); IonReader reader = ionFloat.getSystem().newReader(data, 0,...
57951012_835
class PdfVisibilityExpression extends PdfObjectWrapper<PdfArray> { public void addOperand(PdfLayer layer) { getPdfObject().add(layer.getPdfObject()); getPdfObject().setModified(); } public PdfVisibilityExpression(PdfArray visibilityExpressionArray); public PdfVisibilityExpression(Pdf...
PdfDocument tempDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); // create expression with the AND operator as the first parameter PdfVisibilityExpression expression = new PdfVisibilityExpression(PdfName.And); // add two empty dictionaries as the other parameters ...
57960070_2
class Evaluator { public EvalEntry eval(String stmt) throws Exception { try { return (EvalEntry) latteEngine.eval(stmt, latteEngine.getBindings(ScriptContext.ENGINE_SCOPE), new Config() .setScannerTy...
assertEquals(1, evaluator.eval("1").result); assertEquals(2, evaluator.eval("1+1").result); } }
57984189_4
class StacktraceHash implements IStacktraceHash { @Override public String hash(final IStacktrace st) throws StacktraceHashException { return hashString(st.getStacktraceText()); } public StacktraceHash(final String algorithm); public StacktraceHash(); public String getAlgorithm(); ...
StacktraceHash h = new StacktraceHash(); Throwable t1 = null; Throwable t2 = null; try { new TestClass().foo(1); } catch (RuntimeException e) { t1 = e; } try { new TestClass().foo(1); } catch (RuntimeException e) { ...
57997098_1
class ActivityDelegate extends AbstractDelegate<ICompositeActivity, ActivityPlugin> { public boolean onKeyDown(int keyCode, KeyEvent event) { if (mPlugins.isEmpty()) { return getOriginal().super_onKeyDown(keyCode, event); } final ListIterator<ActivityPlugin> iterator = mPlugins...
final ActivityPlugin a = spy(new ActivityPlugin()); final ActivityPlugin b = spy(new ActivityPlugin() { @Override public boolean onKeyDown(final int keyCode, final KeyEvent event) { return true; } }); final ActivityPlugin c = spy(new A...
58086354_147
class TransportSet implements WithLogId { final ClientTransport obtainActiveTransport() { ClientTransport savedTransport = activeTransport; if (savedTransport != null) { return savedTransport; } synchronized (lock) { // Check again, since it could have changed before acquiring the lock ...
SocketAddress addr1 = mock(SocketAddress.class); SocketAddress addr2 = mock(SocketAddress.class); createTransportSet(addr1, addr2); // Invocation counters int transportsAddr1 = 0; int transportsAddr2 = 0; int backoff1Consulted = 0; int backoff2Consulted = 0; int backoff3Consulted = ...
58089419_6
class AdsOptimizationImpl implements AdsOptimization { @Override public AdsOptimization selectTopK(int k) { if (k <= 0) { throw new IllegalArgumentException("The parameter should be a positive integer."); } if (_candidateAds.size() == 0) { return this; } ...
System.out.println("selectTopKShouldReturnAValidOutput"); // to do, for candidateAds size > k + 1 and <= k+1 assertEquals(expected, ads.selectTopK(k)); } }
58135054_0
class ScriptExecutionTask implements Runnable { public int getTaskId() { return taskId; } public ScriptExecutionTask(GameScriptingEngine gameScriptingEngine, ScriptExecutor<S> executor, int scriptId, GameScript<S> script, ScriptBindings scriptBindings, ScriptInvocationListener scriptInvocationListener); @O...
ScriptExecutionTask<DummyScript> task1 = new ScriptExecutionTask<DummyScript>(new DummyGameScriptingEngine(), new DummyScriptExecutor(null), 0, new GlobalGameScript<DummyScript>(new DummyScript("")), new ScriptBindings(), null); ScriptExecutionTask<DummyScript> task2 = new ScriptExecutionTask<DummyScript>(n...
58142278_0
class GRPCClient implements HLAPI { @Override public int getChainHeight() throws HLAPIException { BlockCount height = obs.getBlockCount(com.google.protobuf.Empty.getDefaultInstance()); return (int) height.getCount(); } public GRPCClient(String host, int port, int observerPort); p...
int height = client.getChainHeight(); log.debug("testGetBlockHeight height=" + height); assertTrue(height > 0); } }
58148640_17
class Journal { @SuppressLint("EmptyCatchBlock") /* package */ LinkedHashMap<String, Entry> retrieveEntriesFromJournal() { maybeSwitchToBackupJournalFile(mDirectory); File journalFile = new File(mDirectory, JOURNAL_FILE); if (journalFile.exists()) { LinkedHashMap<String, Entry> lruEntries = new L...
mJournalFile.delete(); FileWriter writer = new FileWriter(mJournalBkpFile); writer.write("DIRTY k1\nCLEAN k1 12\n"); writer.close(); LinkedHashMap<String, Entry> entries = mJournal.retrieveEntriesFromJournal(); assertThat(entries.size()).isEqualTo(1); assertThat(entries.get("k1")).isNotEqual...
58163050_0
class Calculator { public double add(double a, double b){ return a+b; } private Calculator calculator; private double result; } class CalculatorTest { private Calculator calculator; private double result; @Test public void testAdd() throws Throwable {
Assert.assertEquals(5.0,calculator.add(3.0, 2.0),0.01); } }
58194180_516
class SimpleAclRuleResource { public static SimpleAclRuleResource fromKafkaResourcePattern(ResourcePattern kafkaResourcePattern) { String resourceName; SimpleAclRuleResourceType resourceType; AclResourcePatternType resourcePattern = null; switch (kafkaResourcePattern.resourceType()...
// Regular group ResourcePattern kafkaGroupResourcePattern = new ResourcePattern(ResourceType.GROUP, "my-group", PatternType.LITERAL); SimpleAclRuleResource expectedGroupResourceRules = new SimpleAclRuleResource("my-group", SimpleAclRuleResourceType.GROUP, AclResourcePatternType.LITERAL); ...
58203049_62
class XMLStartElement { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("<" + getName() + ""); for (int i = 0; i < getNamespaceCount(); ++i) { sb.append(" xmlns"); String prefix = getNamespacePrefix(i); if (prefix != null && !prefix.isEmpty(...
XMLStartElement e = new XMLStartElement(null, "test", new String[] { "", "" }, new String[] { "key1", "key2" }, new String[] { "v1", "v2" }); assertEquals("<test key1=\"v1\" key2=\"v2\">", e.toString()); } }
58207096_1
class MarvelApi { public MarvelResult<SectionVO> listComics(long characterId, int offset) throws IOException, MarvelException { Response<SectionDataWrapper> response = mService.listComics(characterId, offset, MAX_FETCH_LIMIT).execute(); if (response.isSuccessful()) { return DataParser.p...
// Fetch the comic result and check for not null MarvelResult<SectionVO> result = mMarvelApi.listComics(CHARACTER_ID, OFFSET); assertNotNull(result); // Get the comic list and check for not null List<SectionVO> entries = result.getEntries(); assertNotNull(entries); ...
58208693_33
class ExpandedNodeId { public String toParseableString() { StringBuilder sb = new StringBuilder(); if (serverIndex.intValue() != 0) { sb.append("svr=").append(serverIndex).append(";"); } if (namespaceUri != null) { sb.append("nsu=").append(namespaceUri).app...
ExpandedNodeId xni = new ExpandedNodeId(ushort(0), null, "test"); assertEquals("ns=0;s=test", xni.toParseableString()); } }
58223375_0
class TrackLover { public synchronized void loveTrack(Track track) { if (scroballDB.isLoved(track)) { return; } LovedTracksEntry entry = scroballDB.writeLove(track, 0); pending.add(entry); lovePending(); eventBus.post(TrackLovedEvent.create()); } public TrackLover( LastfmCl...
when(scroballDB.isLoved(any())).thenReturn(true); trackLover.loveTrack(track1); verify(scroballDB, never()).writeLove(any(), anyInt()); verifyZeroInteractions(lastfmClient); } }
58224198_2
class RealPosClient implements PosClient { @Override public void launchPointOfSale() { List<ResolveInfo> activities = queryChargeActivities(); PackageInfo pointOfSalePackage = findPointOfSaleWithHighestVersion(activities); Intent pointOfSaleIntent = packageManager.getLaunchIntentForPackage(pointOfSalePac...
client.launchPointOfSale(); Intent expectedIntent = context.getPackageManager().getLaunchIntentForPackage("com.squareup"); verify(context).startActivity(expectedIntent); } }
58236838_0
class EddystoneURL extends EddystoneBase { public static String decode(byte[] data) { return null == data ? null : decode(data, 0, data.length); } public EddystoneURL(String url, byte[] lockKey, @Advertiser.Mode int mode, @Advertiser.Power int txPowerLevel, String name); ...
for (Map.Entry<String, byte[]> entry : valid.entrySet()) { assertEquals(entry.getKey(), EddystoneURL.decode(entry.getValue())); } for (Map.Entry<String, byte[]> entry : unexpanded.entrySet()) { assertEquals(entry.getKey(), EddystoneURL.decode(entry.getValue())); ...
58270602_3
class FinishedTorrentsDetector { public Collection<Torrent> filterFinishedTorrentsToNotify(Collection<Torrent> torrents, Server server) { long lastUpdateDate = server.getLastUpdateDate(); if (lastUpdateDate <= 0) return Collections.emptySet(); return filterFinishedAfterDate(torrents, lastU...
Server server = new Server("test", "localhost", 9091); server.setLastUpdateDate(100L); Collection<Torrent> torrents = ImmutableSet.of( new Torrent.Builder().doneDate(-1L).build(), new Torrent.Builder().doneDate(100L).build(), new Torrent.Builder()....
58279246_1
class EtcdFlagFieldUpdater { public void init() { init(Preconditions.checkNotNull(Strings.emptyToNull(directoryFlag.get()))); } public EtcdFlagFieldUpdater(FlagFieldRegistry registry); EtcdFlagFieldUpdater(FlagFieldRegistry registry, List<String> uris, RetryPolicy retryPolicy, Ex...
client.put(FLAGZ_PATH + "etcd_test_int", "101").send().get(); client.put(FLAGZ_PATH + "etcd_test_string", "etcdinit_overwritten").send().get(); etcdUpdater.init(); assertThat(flagInt.get(), is(101)); assertThat(flagString.get(), is("etcdinit_overwritten")); assertThat(flagMap.get(), is(flagMap.d...
58282625_3
class CommonsLang3RandomStringUtils { public static String random(final int count) { return random(count, false, false); } public CommonsLang3RandomStringUtils(); public static String randomAscii(final int count); public static String randomAlphabetic(final int count); public static ...
final long seed = System.currentTimeMillis(); assertEquals("aaa", CommonsLang3RandomStringUtils.random(3,0,0,false,false,new char[]{'a'},new Random(seed))); } }
58301263_6
class DateConverter { @SuppressWarnings("unused") public static Calendar convertModelToCalendar(Model tempModel) { return new GregorianCalendar(tempModel.getYear(), tempModel.getMonth(), tempModel.getDay(), 0, 0, 0); } public DateConverter(); private void initializeData(); private vo...
Model testModel = dc.getTodayNepaliDate(); Calendar testCalendar = dc.convertModelToCalendar(testModel); assertThat(testModel.getYear(), is(testCalendar.get(Calendar.YEAR))); assertThat(testModel.getMonth(), is(testCalendar.get(Calendar.MONTH))); assertThat(testModel.getDay(), ...
58311295_21
class MigrationRepository { public int getLatestVersion() { if (migrationScripts.isEmpty()) { return 0; } return migrationScripts.get(migrationScripts.size() - 1).getVersion(); } public MigrationRepository(); public MigrationRepository(String scriptPath); publ...
MigrationRepository repository = new MigrationRepository("cassandra/migrationtest/empty"); assertThat(repository.getLatestVersion(), is(equalTo(0))); } }
58317819_5
class Document implements Serializable { public <DATA extends ResourceIdentifier> ObjectDocument<DATA> asObjectDocument() { return asObjectDocument(0); } public Document(); public Document(Document document); @Deprecated public boolean include(Resource resource); @Deprecated public ...
Document document = getDocumentAdapter(Article.class) .fromJson(TestUtil.fromResource("/single_null.json")); assertNull(document.asObjectDocument().get()); } }
58336236_1
class SimpleHashLookup { public void reset() { nexts = new int[1024]; Arrays.fill(nexts, -1); hashes = new int[1024]; Arrays.fill(hashes, -1); heads = new int[1024]; Arrays.fill(heads, -1); load = (loadFactor * heads.length) >> 10; size = 0; } ...
HashStore store = new HashStore(); int[] vals = serie(2000, -1000, 3); store.add(vals); verify(store, vals); store.reset(); verify(store); store.add(vals); verify(store, vals); } }
58378593_2
class StringEscapeHelper { public String unescape(String str) { int slashIndex = str.indexOf('\\'); if (slashIndex > -1) { int offset = 0; StringBuilder unescaped = new StringBuilder(str.length() - 1); while (slashIndex > -1) { char c = str.charAt(slashIndex + 1); char r = (...
StringEscapeHelper escapeHelper = new StringEscapeHelper( 'n', '\n', 't', '\t', 'x', '!' ); String unescaped = escapeHelper.unescape("\\thello\\nworld\\x"); assertThat(unescaped, is("\thello\nworld!")); } }
58413602_0
class TechForumApiImpl implements TechForumApi { @NonNull @Override public List<Talk> retrieveAllTalks(boolean fromCache) throws IOException { final List<Talk> response = new ArrayList<>(); if (fromCache) { List<Talk> cachedResponses = localRepository.getTalkList(); ...
mockWebServer.enqueue(new MockResponse().setBody(SAMPLE_SERVER_DATA)); List<Talk> talks = techForumImpl.retrieveAllTalks(false); assertNotNull(talks); assertEquals(1, talks.size()); Talk talk = talks.get(0); assertEquals("123456", talk.getId()); assertEquals(...
58415158_3
class WFClient { public void deleteList(WFList toDelete) throws IOException { checkLoggedIn(); long time = getClientTimeInSeconds(); Long prevLm = toDelete.lm; PushPoll.Operation deleteOp; synchronized (this) { // set the proxy (and delete it from parent) ...
String rootName = "root_" + UUID.randomUUID().toString(); WFList root = client.createRootList(0, rootName, null); WFList child = client.createList(root, 0, "child_" + rootName, null); assertTrue(root.getChildren().contains(child)); client.deleteList(child); assertFalse(r...
58555246_58
class HAProxySubscriber extends DefaultSubscriber<HAProxyPublisher.HAProxyAction> implements Managed { @Override public void onNext(HAProxyPublisher.HAProxyAction action) { if (action.isRegistration()) { createNSQConsumer(action.getId()); } else { deleteNSQConsumer(actio...
// given @SuppressWarnings("unchecked") FlowableNSQConsumer<Integer> nsqConsumer1 = mock(FlowableNSQConsumer.class); when(nsqConsumer1.flowable()).thenReturn(Flowable.range(0, 10)); when(nsqConsumerBuilder.apply("haProxy1")).thenReturn(nsqConsumer1); @SuppressWarnings("un...
58644242_1
class Router { public void open(String url) { open(url, new Bundle()); } public Router(UrlMatcher urlMatcher, RouteCompiler routeCompiler, Context context); public Router(Context context); public Router setContext(Context context); public Context getContext(); public Router mism...
//verify(context); router.add(new Route("github.com/{vendor}", VendorActivity.class)); router.open("https://github.com/mr5"); } }
58712872_12
class NamedHealthCheck extends HealthCheck { @Override public Result execute() { try { Result result = check(); if (!result.isHealthy()) { logger.log(Level.WARNING, "HealthCheck '{0}' is unhealthy: {1}", new Object[]{getName(), result.getM...
result = HealthCheck.Result.unhealthy("ill"); assertThat(healthCheckException.execute().isHealthy(), is(false)); Mockito.verify(logger, Mockito.times(1)).log(eq(Level.WARNING), anyObject(), (Object[]) anyObject()); } }
58730569_11
class Auditor implements Serializable { ValueContainer inspectEntity(HasUuid entity) { DefaultValueContainer result = new DefaultValueContainer(); EntityInspector inspector = new EntityInspector(entity); for (Method currentAttribute : inspector.getAuditedAttributes()) { try { AuditedAttribute auditedAt...
Auditor auditor = new Auditor(); // uses a BooleanFormatter that generates 0 / 1 instead of false / true. SimpleBooleanFlagEntity entity = new SimpleBooleanFlagEntity("uuid-1", false); ValueContainer annotationChanges = auditor.inspectEntity(entity); String formatted = annotationChanges.getAttributes().get...
58760260_2
class User extends BaseEntity { public String getLastName() { return lastName; } protected User(); public User(String firstName, String lastName, String username, String password, String[] roles); public String getFirstName(); public void setFirstName(String firstName); public v...
assertEquals("galon", user.getLastName()); assertEquals("rabi", admin.getLastName()); } }
58766030_1
class LegacyConverters { public static LocalDateTime toLocalDateTime( Date date ) { Calendar c = Calendar.getInstance(); c.setTime( date ); int year = c.get( Calendar.YEAR ); int month = c.get( Calendar.MONTH ) + 1; // Calendar month starts at 0 int day = c.get( Calendar.DAY_OF_MONTH ); int hour = c.get(...
long epochMillis = 31415926535L; Date date = new Date( epochMillis ); Calendar c = Calendar.getInstance(); c.setTime( date ); int year = c.get( Calendar.YEAR ); int month = c.get( Calendar.MONTH ) + 1; int day = c.get( Calendar.DAY_OF_MONTH ); int hour = c.get( Calendar.HOUR_OF_DAY ); int minute = c.g...