id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
184650438_19
class SearchDataSourceServlet extends SlingSafeMethodsServlet { protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { final String PARAMETER_OFFSET = "_commerce_offset"; final String PARAMETER_LIMIT = "_commerce_limit"; final String PA...
dataSourceProperties.put("path", TEST_PATH); dataSourceProperties.put("path", TEST_PATH); results.add(mock(Resource.class)); when(request.getParameter("root")).thenReturn("rootPath"); rootResourceProperties.put(CommerceConstants.PN_COMMERCE_TYPE, Constants.CATEGORY); root...
185218009_0
class AdditionalBuildCommands { public static AdditionalBuildCommands load(Path file) throws IOException { logger.entering(file); AdditionalBuildCommands result = new AdditionalBuildCommands(); result.contents = new HashMap<>(); try (BufferedReader reader = Files.newBufferedReader(...
String filename = "bad-section.txt"; assertThrows(IllegalArgumentException.class, () -> { AdditionalBuildCommands.load(getPath(filename)); }); } }
185263418_0
class Federation { @NotNull public static SchemaTransformer transform(final GraphQLSchema schema) { return new SchemaTransformer(schema); } private Federation(); public static SchemaTransformer transform(final TypeDefinitionRegistry typeRegistry, final RuntimeWiring runtimeWiring); p...
final GraphQLSchema federated = Federation.transform(emptySDL) .build(); Assertions.assertEquals("directive @extends on OBJECT | INTERFACE\n" + "\n" + "directive @external on FIELD_DEFINITION\n" + "\n" + "directive @key(fiel...
185394887_8
class MultiArray { public static <O> MultiArray<O> wrap(final O elements, final int[] dimensions) { return wrap(elements, 0, dimensions); } protected MultiArray(final T elements, final int[] dimensions, final int offset); @SuppressWarnings("unchecked") public static MultiArray<O> wrap(final ...
assertThrows(IllegalArgumentException.class, () -> MultiArray.wrap("Foo", 0, new int[] { 1, 2, 3 })); // elements no array assertThrows(IllegalArgumentException.class, () -> MultiArray.wrap("Foo", 0)); // elements no array assertThrows(IllegalArgumentException.class, () -> MultiArray.wrap(new St...
185565206_0
class ConfigHelper { public static String findConnectorLibPath(String dbType) { DbType type = DbType.valueOf(dbType); URL resource = Thread.currentThread().getContextClassLoader().getResource("logback.xml"); _LOG.info("jar resource: {}", resource); if (resource != null) { try { File file = new File(res...
String path = ConfigHelper.findConnectorLibPath("Oracle"); Assert.assertTrue(path.contains("ojdbc")); } }
185576294_6
class SynchronizedMarkHolder extends MarkHolder { @Override public synchronized void event( long gen, String eventName, String tagName, long tagId, long nanoTime) { writeNnss(gen + EVENT_N2S2_OP, nanoTime, tagId, eventName, tagName); } SynchronizedMarkHolder(); SynchronizedMarkHolder(int maxEv...
mh.event(gen, "task1", 8); mh.event(gen, "task2", 5); List<Mark> marks = mh.read(false); assertEquals(2, marks.size()); List<Mark> expected = Arrays.asList(Mark.event(gen, 8, "task1"), Mark.event(gen, 5, "task2")); assertEquals(expected, marks); } }
185739179_51
class PmdSensor implements Sensor { @Override public void execute(SensorContext context) { if (shouldExecuteOnProject()) { for (RuleViolation violation : executor.execute()) { pmdViolationRecorder.saveViolation(violation, context); } } } public ...
// given addOneJavaFile(Type.MAIN); final RuleViolation pmdViolation = violation(); final Report report = report(pmdViolation); when(executor.execute()).thenReturn(report); // when pmdSensor.execute(sensorContext); // then verify(pmdViolationRec...
185821779_6
class OAuthUserProvider extends AbstractProvider<OAuthUser> { @Override public OAuthUser take() { var user = userSessionRepository.take().getUser(); if (user instanceof OAuthUser) { return (OAuthUser) user; } throw new NoUserFoundException("No OAuth users found in the repository."); } ...
var oAuthUser1 = new OAuthUserImpl(null, TEST_USER_1, TEST_PW, ACCESS_TOKEN, REFRESH_TOKEN, SCOPE, CLIENT_ID, USER_ID, US_REGION ); var userSession = new UserSessionImpl(oAuthUser1); when(repo.take()).thenReturn(userSession, userSession, u...
185828241_1
class EmployeeRepository { public boolean exists(long id) { String sqlQuery = "select count(*) from employees where id = ?"; //noinspection ConstantConditions: return value is always an int, so NPE is impossible here int result = jdbcTemplate.queryForObject(sqlQuery, Integer.class, id); return resu...
boolean exists = employeeRepository.exists(-1); assertThat(exists).isFalse(); } }
185871137_25
class AbstractResponseDecoder implements ResponseDecoder { @SuppressWarnings("unchecked") @Override public <T> T decode(Response response, Class<T> type) { try { if (byte[].class.equals(type)) { return (T) response.toByteArray(); } else if (InputStream.class.isAssignableFrom(type)) { ...
this.decoder.decode(this.response, FileInputStream.class); verify(response, times(1)).body(); } }
186282860_2
class ml2en { public String convert(String input, boolean capitalize) { return transliterate(input, capitalize); } public ml2en(); public void initVars(); String transliterate(String input, boolean capitalize); String _replaceModifiedGlyphs(Map glyphs, String input); String jo...
ml2en m = new ml2en(); assertEquals("Oru phranchu ganithashaasthrajnjanum bhauthikashaasthrajnjanum raashtreeyakkaaranumaayirunnu lasaare kaarnottu.", m.convert("ഒരു ഫ്രഞ്ച് ഗണിതശാസ്ത്രജ്ഞനും ഭൗതികശാസ്ത്രജ്ഞനും രാഷ്ട്രീയക്കാരനുമായിരുന്നു ലസാരെ കാർനോട്ട്.")); assertEquals("2019 e...
186347363_1
class RevokeTokenService { public void revokeToken(TokenTypeHint tokenTypeHint, String token, String clientId) { if (TokenTypeHint.refresh_token.equals(tokenTypeHint)) { revokeRefreshToken(token, clientId); } else { revokeAccessToken(token, clientId); } } pr...
// given String token = "accessToken"; doReturn(this.authentication).when(tokenStore).readAuthentication(token); // when revokeTokenService.revokeToken(TokenTypeHint.access_token, token, clientId); // then verify(tokenStore).readAuthentication(token); v...
186361323_1
class StrKit { public static String firstCharToUpperCase(String str) { char firstChar = str.charAt(0); if (firstChar >= 'a' && firstChar <= 'z') { char[] arr = str.toCharArray(); arr[0] -= ('a' - 'A'); return new String(arr); } return str; } ...
Assert.assertEquals("BAZ", StrKit.firstCharToUpperCase("BAZ")); Assert.assertEquals("Foo", StrKit.firstCharToUpperCase("foo")); } }
186387230_2
class CertificationImporter { abstract Certification load()abstract Certification load(); abstract Certification load()public CertificationImporter(); abstract Certification load()abstract String getName(); } class CertificationImporterTest { @Test void testImporters() {
var service = this.engine.getService(CertificationService.class); service.loadImporters(); for (var certificationId : service.getImporters().keySet()) { var certification = service.load(certificationId); assertNotNull(certification); assertFalse(certification.getControls().isEmpty()); ...
186525996_1
class Friend { public Friend() { } public Friend(); public Friend(Long userId1, Long userId2, Integer status); public Friend(Long userId1, Long userId2); public Friend(Long id, Long userId1, Long userId2); public Long getUserId1(); public void setStatus(Integer status); public...
Friend friend = new Friend(1L, 1L, 1L); Assert.assertEquals((Long)1L, friend.getId()); Friend friend2 = new Friend(1L, 1L, 1); Assert.assertEquals((Integer)1, friend2.getStatus()); } }
186556620_53
class WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profile...
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); webConfigurer.onStartup(servletContext); verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class)); } }
186642789_1
class CompanyFixed { public EmployeeFixed findEmployeeById(String id) { return this.employees.stream() .filter(e -> e.getId().equals(id)) .findFirst() .orElse(null); } public CompanyFixed(String newName); public String getName(); public...
/* * TEST SMELL: No assertions */ this.company.addEmployee(new EmployeeFixed("123", "Dave", 100_000.00)); this.company.addEmployee(new EmployeeFixed("456", "Alice", 100_000.00)); this.company.addEmployee(new EmployeeFixed("789", "Bob", 100_000.00)); Employee...
186955716_0
class ReservationClient { public Flux<Reservation> getAllReservations() { return this.client.get() .uri("http://localhost:8080/reservations") .retrieve() .bodyToFlux(Reservation.class); } @Autowired private ReservationClient client; @Autowired private ObjectMapper objectMapper; } class ReservationC...
/* List<Reservation> reservations = Arrays.asList(new Reservation("1", "Jane"), new Reservation("2", "John")); List<String> validNames = reservations.stream().map(r -> r.getReservationName()).collect(Collectors.toList()); String json = this.jsonFrom(reservations); WireMock.stubFor(WireMock.get(WireMock.urlEq...
186978836_31
class GroupKey { public static String getKeyTenant(String dataId, String group, String tenant) { return doGetKey(dataId, group, tenant); } public static String getKey(String dataId, String group); public static String getKey(String dataId, String group, String datumStr); private static Str...
// Act final String actual = GroupKey.getKeyTenant("\u0000\u0000", "%+", null); // Assert result Assert.assertEquals("\u0000\u0000+%25%2B", actual); } }
187556247_613
class Spoon extends ApplicationWindow implements AddUndoPositionInterface, TabListener, SpoonInterface, OverwritePrompter, PDIObserver, LifeEventHandler, XulEventSource, XulEventHandler, PartitionSchemasProvider { public void openFile() { openFile( false ); } private Spoon(); private Spoon( Repository...
String repositoryName = null; String fileName = "fileName"; setLoadLastUsedJobLocalWithRepository( false, repositoryName, null, fileName, false ); verify( spoon ).openFile( fileName, false ); } }
187590023_3
class PersonServiceImpl implements PersonService { @CacheEvict(value = "people", key = "#id") @Override public void remove(Long id) { log.info("删除了id、key为" + id + "的数据缓存"); } @Cacheable(value = "people" , key = "#person.id") @Override public Person save(Person person); @CacheEvict(valu...
Person p = new Person(5, "name1", 12, "address1"); personService.save(p); log.info("缓存中一个缓存 id = 5 的 Person 对象"); personService.remove(5L); log.info("删除一个缓存 id = 5 的 Person 对象"); Person person = personService.findOne(p); log.info("从数据库中抓取一个 id = 2 的对象,并存入缓存"); ...
187595602_12
class WindowsProxyUtils { static ProxyProvider createInternalProxy(final DeploymentConfiguration config, final RegistryQueryResult queryResult) throws IOException { final String autoConfigUrl = queryResult.getValue(AUTO_CONFIG_URL_VAL); if (autoConfigUrl != null) { LOG.debug("Registry v...
//given final DeploymentConfiguration config = new DeploymentConfiguration(); final Map<String, RegistryValue> proxyRegistryEntries = new HashMap<>(); proxyRegistryEntries.put(PROXY_ENABLED_VAL, new RegistryValue(PROXY_ENABLED_VAL, REG_DWORD, "0x0")); final RegistryQueryResult qu...
187648701_0
class PlaceOpObjectHelper { protected static void generateDiff(OpObject editObject, String field, Map<String, Object> change, Map<String, Object> current, Map<String, Object> oldM, Map<String, Object> newM) { TreeSet<String> removedTags = new TreeSet<>(oldM.keySet()); removedTags.removeAll(newM.keySet()); fo...
OpObject opObject = null; String field = F_TAGS + "."; Map<String, Object> change = new TreeMap<>(); Map<String, Object> current = new TreeMap<>(); Map<String, Object> oldM = new TreeMap<>(); oldM.put("addr:city", "台北市"); oldM.put("amenity", "cafe"); oldM.put("http://touat.com.tw", "running"); Map<Str...
187765477_5
class HttpSource extends AbstractSource<HttpResourceId> implements NonListenableSource<HttpResourceId> { @Override public LoadedResource loadIfModified(HttpResourceId resourceId, SourceVersion version) { var cacheControl = resourceId.getCacheControl(); if (version == SourceVersion.EMPTY || cach...
var response = aResponse().withStatus(200).withHeader("ETag", "1ab"); stubFor(headPath().willReturn(response)); stubFor(getPath().willReturn(response.withBody("init"))); var source = Http.builder().receiveBufferSize(5).build(); var id = Http.url(defaultURL(), ETAG_HEAD); ...
187767967_2
class JavaTypeInspector implements ITypeInspector { @Override public boolean isCollection(Type type) { if (type instanceof Class) { var clazz = (Class)type; if (clazz.isArray()) { return true; } if (Collection.class.isAssignableFr...
var type = TestJavaTypeInspector.class.getMethod("test1").getGenericReturnType(); assertTrue(_typeInspector.isCollection(type)); } }
187873041_1
class DefaultDatabasePermissionManagement extends ClusterSynchronizedPermissionManagement implements DefaultSynchronizedPermissionManagement, DefaultPermissionManagement { @Override public Collection<IPermissionGroup> getGroups() { for (IPermissionGroup permissionGroup : this.permissionGroupsMap.values...
String groupName = "Test", userName = "Tester", permission = "test.permission", groupPermission = "role.permission"; new File("build/h2database.mv.db").delete(); new File("build/group_permissions.json").delete(); AbstractDatabaseProvider databaseProvider = new H2DatabaseProvider("build...
187946264_2
class RouterFunctions { public static <T extends ServerResponse> RouterFunction<T> route( RequestPredicate predicate, HandlerFunction<T> handlerFunction) { return new DefaultRouterFunction<>(predicate, handlerFunction); } public static RouterFunction<T> nest( RequestPredicate predicate, RouterFunction<T> ...
RouterFunction<ServerResponse> routerFunction1 = request -> Mono.empty(); RequestPredicate requestPredicate = request -> true; RouterFunction<ServerResponse> result = routerFunction1.andRoute(requestPredicate, this::handlerMethod); assertNotNull(result); MockServerRequest request = MockServerRequest.builder...
187972412_38
class MessageServiceImpl implements MessageService { @Override public List<MessageView> queryMessageByTopic(String topic, final long begin, final long end) { DefaultMQPullConsumer consumer = new DefaultMQPullConsumer(MixAll.TOOLS_CONSUMER_GROUP, null); List<MessageView> messageViewList = Lists....
final String messageId = msgId; List<MessageView> messageViewList = null; for (int i = 0; i < 10; i++) { messageViewList = messageService.queryMessageByTopic(TEST_CONSOLE_TOPIC, System.currentTimeMillis() - 100000, System.currentTimeMillis()); if (CollectionUtils.isEmpty(...
188058370_0
class StringUtil { public static boolean isNullOrEmpty(String str) { return str == null || str.isEmpty(); } } class StringUtilTest { @Test public void testIsNullOrEmpty() {
boolean isEmpty = StringUtil.isNullOrEmpty("aaa"); Assert.assertFalse(isEmpty); } }
188081982_21
class HandResolver { public Hand hand(CardSet cardSet) { List<Card> handCards = cardSet.getSortedCards(); // Figure our high card by same color SUIT colorCandidate = handCards.get(0).getSuit(); boolean allSameColor = handCards.stream() .allMatch(card -> card.getSuit...
CardSet cardSet = new CardSet( aCard(HEART, EIGHT), aCard(DIAMOND, EIGHT), aCard(CLUB, NINE), aCard(SPADE, TEN), aCard(HEART, JACK)); Hand hand = handResolver.hand(cardSet); assertThat(hand) .hasRan...
188223092_16
class ModelRepository { public void addModel(final String modeluri, final EObject model) throws IOException { final Resource resource = resourceSet.createResource(createURI(modeluri)); resourceSet.getResources().add(resource); resource.getContents().add(model); resource.save(null); } ...
repository.addModel("SuperBrewer3000.json", CoffeeFactory.eINSTANCE.createBrewingUnit()); assertTrue(repository.hasModel("SuperBrewer3000.json")); } }
188229074_0
class UcManageKeyListImpl extends AbstractKeyListUc implements UcManageKeyList { @Override @RolesAllowed(ApplicationAccessControlConfig.PERMISSION_SAVE_KEY_LIST) public KeyListEto saveKeyList(KeyListEto keyList) { Objects.requireNonNull(keyList, "keyList"); KeyListEntity keyListEntity = getBeanMapper()...
TestUtil.login("admin", ApplicationAccessControlConfig.PERMISSION_FIND_KEY_LIST, ApplicationAccessControlConfig.PERMISSION_SAVE_KEY_LIST); KeyListEto keyList = this.keymanagement.findKeyListByKey(KeyListCountryTestAspect.KEY_COUNTRY); KeyListCountryTestAspect.verifyCountry(keyList); keyList.set...
188279001_0
class PokemonToPokemonResponseAssembler { public PokemonResponse assemble(Pokemon data) { return PokemonResponse.builder() .name(data.getName()) .abilities(data.getAbilities()) .baseExperience(data.getBaseExperience()) .weight(data.getWeight()) .height(data.getHeight()) ...
Pokemon pokemon = from("a valid pokemon", Pokemon.class); PokemonResponse pokemonResponse = pokemonToPokemonResponseAssembler.assemble(pokemon); assertThat(pokemonResponse, notNullValue()); assertThat( pokemonResponse.getAbilities(), equalTo(Arrays.asList(Ability.LIMBER, Ability.OVERGROW))); ...
188292946_0
class ServiceLoaderProvider { public static <T> T get(Class<T> supplier) { return getSupplier(requireNonNull(supplier, "supplier is required")); } private ServiceLoaderProvider(); private static T getSupplier(Class<T> supplier); public static T getUnique(Class<T> supplier); public st...
assertThrows(ProviderNotFoundException.class, () -> ServiceLoaderProvider.get(Unicorn.class)); } }
188402392_0
class StandardOPCUAService extends AbstractControllerService implements OPCUAService { @Override public byte[] getValue(List<String> tagNames, String returnTimestamp, boolean excludeNullValue, String nullValueString) throws ProcessException { try { if (opcClient =...
runner.setProperty(service, StandardOPCUAService.ENDPOINT, endpoint); runner.setProperty(service, StandardOPCUAService.SECURITY_POLICY, "Basic256Sha256"); runner.setProperty(service, StandardOPCUAService.SECURITY_MODE, "SignAndEncrypt"); runner.setProperty(service, StandardOPCUAService.A...
188429680_19
class Example implements Serializable { public boolean isMultiSentenceInstruction() { int fromIndex = 0; int dotInd; while ((dotInd = instructionUtterance.indexOf(".", fromIndex)) >= 0){ if (!instructionUtterance.substring(dotInd + 1).trim().isEmpty() && // The dot isn't the end of the utterance. Strin...
List<String> multiSentenceInstructions = Arrays.asList( "a. a", "aaa. bbb.", "aaa. bbb. " ); List<String> nonMultiSentenceInstructions = Arrays.asList( "", "a.", "a. ", "a b. ", ...
188534881_1
class ServerSelector { Optional<String> select(String version) { if (version.isEmpty()) { // of nullable since map could be empty return Optional.ofNullable(m.lastEntry().getValue()); } // strip "v" at head of string version = version.substring(1); int separatorIndex = version.indexOf("."); if (sepa...
ServerSelector ssArt = new ServerSelector(() -> new AdaptiveRadixTree<>(APIVersionBinaryComparable.INSTANCE)); ServerSelector ssRbt = new ServerSelector(() -> new TreeMap<>(APIVersionComparator.INSTANCE)); // add API versions ssArt.addServer(new APIVersion(1, 1), "hosta:port"); ssArt.addServer(new APIVersion...
188592933_0
class GenericRetryExecution implements RetryExecution { public Optional<Long> nextDelay() { if (lastAttemptIndex == 0) { lastAttemptIndex++; return Optional.of(0L); } if (genericRetry.getMaxAttempts() > -1 && lastAttemptIndex >= genericRetry.getMaxAttempts()) { ...
assertThat(getDefaultRetryExecution().nextDelay().get()).isEqualTo(0); } }
188643956_0
class Inventory extends BaseAggregate { public static Inventory create(String productId, String productName) { return Inventory.builder() .id(newUuid()) .productId(productId) .productName(productName) .remains(0) .createdAt(Ins...
assertNotNull(Inventory.create("12345", "name")); } }
188644064_0
class Product extends BaseAggregate { public static Product create(String name, String description, BigDecimal price, String categoryId) { Product product = Product.builder() .id(newUuid()) .name(name) .description(description) .price(price) ...
Product product = Product.create("name", "desc", BigDecimal.valueOf(12.0), "123456"); assertNotNull(product); } }
189012247_10
class KafkaMessageHandlerRegistry implements IKafkaMessageHandlerRegistry<T> { @Override public List<IKafkaMessageHandler<T>> getForTopicOrFail(String topic) { List<IKafkaMessageHandler<T>> topicKafkaMessageHandlers = getForTopic(topic); if (topicKafkaMessageHandlers.isEmpty()) { throw new IllegalSta...
assertThrows(IllegalStateException.class, () -> kafkaMessageHandlerRegistry.getForTopicOrFail("UNKNOWN")); } }
189027594_176
class WxMpCardServiceImpl implements WxMpCardService { @Override public String decryptCardCode(String encryptCode) throws WxErrorException { JsonObject param = new JsonObject(); param.addProperty("encrypt_code", encryptCode); String responseContent = this.wxMpService.post(CARD_CODE_DECRYPT, param.toStr...
String encryptCode = "pd0vTUHSHc9tMUCL2gXABcUmINm6yxqJh0y9Phsy63E="; String cardCode = this.wxService.getCardService().decryptCardCode(encryptCode); assertNotNull(cardCode); System.out.println(cardCode); } }
189191730_26
class ArchiveIdentifierPattern extends ArchiveIdentifier { @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Objects.hash(pattern.pattern(), patternType); return result; } public ArchiveIdentifierPattern(fi...
final ArchiveIdentifierPattern ai1 = new ArchiveIdentifierPattern(ArchiveType.JAVA, PatternType.PATTERN_ON_FILENAME, "abc"); final ArchiveIdentifierPattern ai2 = new ArchiveIdentifierPattern(ArchiveType.JAVA, PatternType.PATTERN_ON_FILENAME, "def"); Assert.assertN...
189204070_1
class RoomServiceImpl implements RoomService { @Override public List<Room> findRoomsByType(String type) { if (roomTypes.contains(type)) { return roomRepo.findRoomsByRoomType(type); } else { throw new RoomServiceException("Room type: " + type + " not found!"); } } public RoomServiceImpl(RoomRepo room...
RoomRepo repo = mock(RoomRepo.class); RoomServiceImpl service = new RoomServiceImpl(repo, roomTypes); verify(repo, times(0)).findRoomsByRoomType(any()); expectedException.expect(RoomServiceException.class); expectedException.expectMessage("Room type: NOT FOUND not found!"); service.findRoomsByType("NOT FOUN...
189356507_1
class LogProducerProvider extends AbstractClientProvider<LogProducer> { @Override protected void closeClient() { if (client != null) { // close the producer. while (true) { try { client.close(); break; } catch (InterruptedException e) { // ignore interrupt signal to avoid io thread lea...
LogProducerProvider producerProvider = new LogProducerProvider( "test-project", "test-endpoint", "test-ak", "test-secret", 1, 100); LogProducer producer = Mockito.mock(LogProducer.class); Whitebox.setInternalState(producerProvider, "client", producer); Mockito.doThrow(new InterruptedException()).doNothing...
189556566_0
class StringUtil { public static String getSizeString(long size){ if(size < 1024){ return String.format(Locale.getDefault(), "%d B", size); }else if(size < 1024 * 1024){ float sizeK = size / 1024f; return String.format(Locale.getDefault(), "%.2f KB", sizeK); ...
String msg = StringUtil.getSizeString(102400); assertEquals("100.00 KB", msg); } }
189605649_51
class NativeRequest extends AdRequest<NativeRequest, UnifiedNativeAdRequestParams> { @SuppressWarnings("WeakerAccess") public boolean containsAssetType(MediaAssetType assetType) { return mediaAssetTypes.isEmpty() || mediaAssetTypes.contains(assetType) || mediaAssetTypes....
NativeRequest nativeRequest = new NativeRequest.Builder() .setMediaAssetTypes(MediaAssetType.Icon, MediaAssetType.Image) .build(); assertTrue(nativeRequest.containsAssetType(MediaAssetType.Icon)); assertTrue(nativeRequest.containsAssetType(MediaAssetType.Image)); ...
189841989_2
class Combinator { public static <T> Stream<List<Optional<T>>> combinations(List<T> list) { long n = (long) Math.pow(2, list.size()); return StreamSupport.stream(new Spliterators.AbstractSpliterator<>(n, Spliterator.SIZED) { long i = 0; @Override public boolean...
List<List<Optional<String>>> combinations = Combinator .combinations(List.of("a", "b", "c")) .collect(Collectors.toList()); assertEquals(8, combinations.size()); assertSameSize(3, combinations); assertContains(List.of(Optional.empty(), Optional.empty(), ...
189845277_4
class RouterFunctions { public static Builder route() { return new RouterFunctionBuilder(); } public static RouterFunction<T> route( RequestPredicate predicate, HandlerFunction<T> handlerFunction); public static RouterFunction<T> nest( RequestPredicate predicate, RouterFunction<T> routerFunction); public...
HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().build(); RouterFunction<ServerResponse> routerFunction1 = request -> Optional.empty(); RouterFunction<ServerResponse> routerFunction2 = request -> Optional.of(handlerFunction); RouterFunction<ServerResponse> result = routerFunctio...
190100311_0
class AccountCreateImpl implements AccountCreate { @Nonnull @Override public String create() throws IdentityException { Validate.notNull(account.getUsername(), "username must be set"); Validate.notNull(account.getFirstName(), "first name must be set"); Validate.notNull(account.getLa...
new Expectations() {{ systemService.currentTimeMillis(); result = 1563200810123L; times = 1; passwordService.createPasswordHash("test_pwd"); result = "test_pwd_hash"; times = 1; }}; String result = accountCreate ...
190168097_216
class AwsRDSInstanceContainer extends AwsContainer { @ChaosExperiment(experimentType = ExperimentType.STATE) public void restartInstance (Experiment experiment) { experiment.setCheckContainerHealth(() -> awsRDSPlatform.getInstanceStatus(dbInstanceIdentifier)); awsRDSPlatform.restartInstance(dbI...
awsRDSInstanceContainer.restartInstance(experiment); verify(experiment, times(1)).setCheckContainerHealth(any()); verify(awsRDSPlatform, times(1)).restartInstance(dbInstanceIdentifier); } }
190197552_1
class Neo4jDriverProperties { public URI getUri() { return this.uri; } public void setUri(URI uri); public Authentication getAuthentication(); public void setAuthentication( Authentication authentication); public PoolSettings getPool(); public void setPool(PoolSettings pool); public DriverSettings getConf...
Neo4jDriverProperties driverProperties = new Neo4jDriverProperties(); assertThat(driverProperties.getUri()).isNull(); } }
190209753_0
class HllUtil { public static double pow2(int p) { if (p < 0) { return 1.0 / (1L << -p); } if (p > 0) { return 1L << p; } return 1.0; } public static long murmurHash64A(byte[] data, int seed); } class HllUtilTest { @Test public vo...
assertThat(HllUtil.pow2(0)).isEqualTo(1.0); assertThat(HllUtil.pow2(8)).isEqualTo(256.0); assertThat(HllUtil.pow2(-8)).isEqualTo(0.00390625); } }
190267909_31
class LocalityAwareRandomPartitioner extends LocalityAwarePartitioner { @Override public int partition(Object messageKey, List<PartitionInfo> partitions) { if (localPartitions == null || isTimeToRefresh()) { checkAndAssignLocalPartitions(partitions); // set next refresh time updateNextRefresh...
List<PartitionInfo> partitions = Arrays.asList( new PartitionInfo("topix", 0, new Node(0, "0", 9092, "us-east-1a"), null, null), new PartitionInfo("topix", 1, new Node(1, "0", 9092, "us-east-1e"), null, null), new PartitionInfo("topix", 3, new Node(2, "0", 9092, "us-east-1d"), null, null), ...
190303335_18
class S3FileSystem extends FileSystem implements Comparable<S3FileSystem> { public String getKey() { return key; } public S3FileSystem(S3FileSystemProvider provider, String key, AmazonS3 client, String endpoint); @Override public S3FileSystemProvider provider(); @Override public void clo...
String fileName = "βeta.png"; String expected = "https://bucket.s3.eu-west-1.amazonaws.com/%CE%B2eta.png"; AmazonS3 amazonS3Client = AmazonS3ClientBuilder.standard() .withRegion(Regions.EU_WEST_1) .build(); S3FileSystem s3FileSystem = new S3FileSystem(nul...
190335075_411
class InsnList { public AbstractInsnNode[] toArray() { int currentInsnIndex = 0; AbstractInsnNode currentInsn = firstInsn; AbstractInsnNode[] insnNodeArray = new AbstractInsnNode[size]; while (currentInsn != null) { insnNodeArray[currentInsnIndex] = currentInsn; currentInsn.index = curren...
InsnList insnList = newInsnList(insn1, insn2); AbstractInsnNode[] insnArray = insnList.toArray(); assertArrayEquals(new AbstractInsnNode[] {insn1, insn2}, insnArray); } }
190419065_18
class PluginManagerUtils { public static String appendPathOntoUrl(Object urlString, Object... pathSection) { String[] args = new String[pathSection.length]; for (int i = 0; i < pathSection.length; ++i) { requireNonNull(pathSection[i]); args[i] = pathSection[i].toString(); ...
String result = PluginManagerUtils.appendPathOntoUrl("http://bob.com:8080/", "path/to/", "file.json"); assertThat(result).isEqualTo("http://bob.com:8080/path/to/file.json"); } }
190664284_131
class WorkerRegistryV2 implements WorkerRegistry, WorkerEventSubscriber { @Override public int getNumRunningWorkers() { if(logger.isDebugEnabled()) { logger.debug("In getNumRunningWorkers"); } int cnt = jobToWorkerInfoMap.values().stream() .map(workerList -> workerList.strea...
WorkerRegistryV2 workerRegistryV2 = new WorkerRegistryV2(); LifecycleEventPublisher eventPublisher = new LifecycleEventPublisherImpl(new AuditEventSubscriberLoggingImpl(), new StatusEventSubscriberLoggingImpl(), new DummyWorkerEventSubscriberImpl(workerRegistryV2)); Map<StageScalingPolicy.Scali...
190686426_1
class Calculator { public int add(int n1,int n2) { return n1+n2; } Calculator calculator; } class CalculatorTest { Calculator calculator; @Test public void add2() {
int actual = calculator.add(12, 12); int expected = 25; assertNotEquals(expected, actual); } }
190690143_17
class JsCacheBuilder { public JsApiCache buildFrom(Map<String, Object> registeredApis) { JsApiCache.Builder builder = new JsApiCache.Builder(); for(String apiBaseName : registeredApis.keySet()) { appendObject(builder, apiBaseName, registeredApis.get(apiBaseName)); } return builder.build(); } private v...
JsCacheBuilder cacheBuilder = new JsCacheBuilder(); Map<String, Object> apis = new HashMap<>(); apis.put("api1", new ObjectWithFunctionReturningArray()); JsApiCache cache = cacheBuilder.buildFrom(apis); ApiEntry classEntry = cache.get("--classes").get(Foo.class.getName()); assertThat(classEntry).isInstanc...
190718318_3
class Warehouse { public void addProduct(String name, int price) throws WarehouseException { if (price < 0) { throw new IllegalArgumentException("The product's price cannot be negative."); } Product product = new Product(name, price); productDao.addProduct(product); ...
// given String name = "test"; int price = -123; // when/then assertThrows(IllegalArgumentException.class, () -> warehouse.addProduct(name, price)); } }
190783541_11
class BackupUploadService implements IBackupUploadService { @Override public void startUploading(IDicomWebClient webClient, BackupState backupState) throws IBackupUploader.BackupException { scheduleUploadWithDelay(webClient, backupState); } public BackupUploadService(IBackupUploader backupUploader, Backu...
doThrow(new DicomWebException("Reason", HttpStatus.INTERNAL_SERVER_ERROR_500, Status.ProcessingFailure)) .doNothing().when(webClientMock).stowRs(any(InputStream.class)); when(backupUploaderMock.doReadBackup(eq(UNIQUE_FILE_NAME))).thenReturn(backupInputStream); backupUploadService.startUploading(web...
191232069_5
class MaxHeapAllocationPerfVerifier implements VerifiablePerformanceIssue<ExpectMaxHeapAllocation, Allocation> { @Override public PerfIssue verifyPerfIssue(ExpectMaxHeapAllocation annotation, Allocation measuredAllocation) { Allocation maxExpectedAllocation = new Allocation(annotation.value(), annotat...
// GIVEN ExpectMaxHeapAllocation annotation = JvmAnnotationBuilder.expectMaxHeapAllocation(3.75 * 1024 , AllocationUnit.MEGA_BYTE); // 3.75 giga bytes Allocation measuredAllocation = Allocation.ofBy...
191553604_1044
class Dispatcher extends FencedRpcEndpoint<DispatcherId> implements DispatcherGateway, LeaderContender, SubmittedJobGraphStore.SubmittedJobGraphListener { @Override public void onAddedJobGraph(final JobID jobId) { runAsync( () -> { if (!jobManagerRunnerFutures.containsKey(jobId)) { // IMPORTANT: onAdd...
dispatcher = createAndStartDispatcher(heartbeatServices, haServices, new ExpectedJobIdJobManagerRunnerFactory(TEST_JOB_ID, createdJobManagerRunnerLatch)); final FlinkException expectedFailure = new FlinkException("Expected failure"); submittedJobGraphStore.setRecoveryFailure(expectedFailure); dispatcherLeader...
191586445_1
class WebSocketEndpoint { @OnClose public void onClose(Session session, @PathParam("username") String username) { sessions.remove(username); broadcaster.removeSession(session); broadcaster.broadcast("#User: " + username + " left"); LOGGER.info(username + " is offline!"); } ...
webSocketEndpoint.onClose(session, "user2"); Mockito.verify(broadcaster).removeSession(session); Mockito.verify(broadcaster).broadcast("#User: user2 left"); } }
192009782_4
class PopTokenBuilderUtils { public static RSAPrivateKey encryptedKeyPemStringToRsaPrivateKey(String encryptedPrivateKeyPemString, String privateKeyPassword) throws PopPrivateKeyParseException { if (StringUtils.isBlank(encryptedPrivateKeyPemString)) { throw new IllegalArgumentExcep...
// perform an action RSAPrivateKey rsaPrivateKey = PopTokenBuilderUtils.encryptedKeyPemStringToRsaPrivateKey(aes256EncryptedPrivateKeyPemString, privateKeyPassword); // validate the results assertNotNull("The rsaPrivateKey should not be null", rsaPrivateKey); } }
192381473_43
class RequestIdentifier { public static boolean isIndexRequest(@NonNull Request esRequest) { // the path should contain /index/type/ or /index/type/id // type shouldn't be _search String[] pathFields = esRequest.getEndpoint().substring(1).split("/"); return (pathFields.length == Co...
esRequest = new Request(TestConstants.PUT_METHOD, TestConstants.WRONG_INDEX_PATTERN); boolean result = RequestIdentifier.isIndexRequest(esRequest); assertFalse(result); } }
192457111_9
class HCatClient { public abstract String getMessageBusTopicName(String dbName, String tableName) throws HCatExceptionpublic abstract String getMessageBusTopicName(String dbName, String tableName) throws HCatException; public abstract String getMessageBusTopicName(String dbName, String tableName) throws HCatException...
try { HCatClient client = HCatClient.create(new Configuration(hcatConf)); String dbName = "testGetMessageBusTopicName_DBName"; String tableName = "testGetMessageBusTopicName_TableName"; client.dropDatabase(dbName, true, HCatClient.DropDBMode.CASCADE); client.createDatabase(HCatCreateDB...
192508383_59
class PmdSensor implements Sensor { @Override public void execute(SensorContext context) { if (shouldExecuteOnProject()) { for (RuleViolation violation : executor.execute()) { pmdViolationRecorder.saveViolation(violation, context); } } } public ...
// given final RuleViolation pmdViolation = violation(); final Report report = report(pmdViolation); when(executor.execute()).thenReturn(report); when(report.iterator()).thenReturn(Iterators.forArray(pmdViolation)); // when pmdSensor.execute(sensorContext); ...
192942452_46
class ApplicationLifecycleManager { public void ensureStopped() throws InterruptedException { for (int i = 0; i < 30; i++) { ApplicationStatus currentStatus = detailSupplier.get().applicationStatus(); switch (currentStatus) { case RUNNING: stop();...
Mockito.when(client.describeApplication(describeApplicationRequest)) .thenReturn(withStatus(ApplicationStatus.STOPPING)); try { manager.ensureStopped(); Assert.fail("expected timeout waiting for application to finish starting"); } catch (IllegalStateException ...
193047220_40
class DefaultComponentsValidatorFactory implements ComponentsValidatorFactory { @Override public List<ComponentsValidator> create(FactoryOptions options) { List<ComponentsValidator> validators = new ArrayList<>(); // skeletons validators.add(new ComponentsHeadersValuesValidator(headerValidatorFactory....
FactoryOptions options = new FactoryOptions(emptyMap()); List<ComponentsValidator> validators = validatorFactory.create(options); assertThat(validators).hasSize(6); assertThat(validators).hasOnlyElementsOfTypes( ComponentsHeadersValuesValidator.class, ComponentsParametersValuesValidator....
193065376_4
class DeepCopySubstitution { @Substitute public static Object simpleDeepCopy(Object toCopy) { return JsonUtils.cloneJson(toCopy); } } class DeepCopySubstitutionTest { @SuppressWarnings("unchecked") @Test void nominalSchemaDeepCopyShouldSucceed() {
LinkedHashMap<String, Object> originalLinkedHashMap = new LinkedHashMap<>(); ArrayList<Integer> originalArrayList = new ArrayList<>(Arrays.asList(new Integer(10))); originalLinkedHashMap.put("boolean", new Boolean(true)); originalLinkedHashMap.put("string", "original"); original...
193085253_6
class LeaveRequestService { public Optional<LeaveRequest> approve(UUID id) { Optional<LeaveRequest> found = repo.findById(id); found.ifPresent(lr -> lr.setStatus(Status.APPROVED)); return found; } public LeaveRequest request(String employee, LocalDate from, LocalDate to); public Optional<LeaveRequest> deny(...
LeaveRequest saved = repository.save(new LeaveRequest("Alice", of(2019, 11, 30), of(2019, 12, 03), PENDING)); Optional<LeaveRequest> approved = service.approve(saved.getId()); verify(repository).findById(saved.getId()); assertThat(approved).isPresent(); assertThat(approved).get().isSameAs(saved); assertThat...
193109862_14
class DENOPTIMEdge implements Serializable { public boolean sameAs(DENOPTIMEdge other, StringBuilder reason) { if (this.getSourceDAP() != other.getSourceDAP()) { reason.append("Different source atom ("+this.getSourceDAP()+":" +other.getSourceDAP()+"); "); return false; } ...
DENOPTIMEdge eA = new DENOPTIMEdge(0, 1, 0, 0, 1); DENOPTIMEdge eB = new DENOPTIMEdge(0, 1, 0, 0, 2); assertFalse(eA.sameAs(eB, reason)); } }
193272759_264
class TrainingSetManager { public synchronized void addTrainingSet(TrainingSet trainingSet) { trainingSet.setTrainingSetID(trainingSetIDCounter++); trainingSets.add(trainingSet); } TrainingSetManager(); public void addTrainingSets(Collection<TrainingSet> trainingSets); public synchronized TrainingSet acq...
TrainingSetManager manager = new TrainingSetManager(); manager.reset(); TrainingSet trainingSet = manager.acquireTrainingSet(0); assertThat(trainingSet).isNull(); fillTrainingSetManager(manager, 10); trainingSet = manager.acquireTrainingSet(0); assertThat(trainingSet).isNotNull(); TrainingSet t...
193500053_6
class GitMlRules { static Map<String, List<String>> stripDuplicatePrefixes(Map<String, List<String>> fullList) { // Create a prefix tree var trie = mapToTrie(fullList); // Prune it var pruned = pruneEntry(trie); // Restore the map from the tree return trieToMap(pru...
assertEquals(Map.of("k/1", List.of("v1"), "k/2a", List.of("v2")), GitMlRules.stripDuplicatePrefixes(Map.of("k/1/aa", List.of("v1"), "k/1/bb", List.of("v1"), ...
193582925_57
class StorageCli extends SubcommandCli { public static void testMain(String[] args) { new StorageCli(args, true).processCmd(); } private StorageCli(String[] args, boolean useByTest); private static StorageClient openStorageClient(String host, int port, SslContext sslContext, ZooKeeperClient...
int numPartitions = 1; IntegrationTestHelper helper = getIntegrationTestHelper(numPartitions); Properties cfgProperties = createProperties(helper.getZkConnectString(), helper.getZnodePath(), helper.getSslSetup()); String cliConfigPath = IntegrationTestHelper.createYamlConfigFile(DIR_NAM...
193657959_5
class JWTFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String ...
MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/api/test"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); jwtFilter.doFilter(request, response, filterChain); as...
193945625_21
class ReadHandler extends BaseHandlerStd { protected ProgressEvent<ResourceModel, CallbackContext> handleRequest( final AmazonWebServicesClientProxy proxy, final ResourceHandlerRequest<ResourceModel> request, final CallbackContext callbackContext, final ProxyClient<CloudFormationCli...
final CloudFormationClient client = getServiceClient(); final DescribeTypeResponse describeTypeResponse = DescribeTypeResponse.builder() .arn("arn:aws:cloudformation:us-west-2:123456789012:type/resource/AWS-Demo-Resource/00000001") .defaultVersionId("00000001") .depr...
194059614_0
class OAuthConsumerAppToExternal implements Function<OAuthConsumerAppDTO, AuthorizedAppDTO> { @Override public AuthorizedAppDTO apply(OAuthConsumerAppDTO oAuthConsumerAppDTO) { AuthorizedAppDTO authorizedAppDTO = new AuthorizedAppDTO(); authorizedAppDTO.setAppId(oAuthConsumerAppDTO.getApplica...
OAuthConsumerAppDTO oAuthConsumerAppDTO = new OAuthConsumerAppDTO(); oAuthConsumerAppDTO.setApplicationName("TestApp"); oAuthConsumerAppDTO.setOauthConsumerKey("TestConsumerKey"); AuthorizedAppDTO authorizedAppDTO = new OAuthConsumerAppToExternal().apply(oAuthConsumerAppDTO); A...
194304228_11
class StringValidateEncodeUtils { public static String unicodeCodePoint2PercentHexString(int codePoint, String charsetName) { if (!Character.isDefined(codePoint)) throw new IllegalArgumentException( String.format("Given code point [U+%1$04X - %1$d] not assigned to an abstract character.", codePoi...
// From "Invalid code points" section of the UTF-8 Wikipedia article // (http://en.wikipedia.org/wiki/UTF-8#Invalid_code_points): // According to the UTF-8 definition (RFC 3629) the high and low // surrogate halves used by UTF-16 (U+D800 through U+DFFF) are not // legal Unicode values, and their UT...
194333585_127
class IndexScrutinyTableOutput { static String constructMetadataParamQuery(List<String> metadataSelectCols) { String pkColsCsv = getPksCsv(); String query = QueryUtil.constructSelectStatement(OUTPUT_METADATA_TABLE_NAME, metadataSelectCols, pkColsCsv, null, true);...
String metadataParamQuery = IndexScrutinyTableOutput .constructMetadataParamQuery(Arrays.asList("INVALID_ROWS_QUERY_ALL")); assertEquals( "SELECT \"INVALID_ROWS_QUERY_ALL\" FROM PHOENIX_INDEX_SCRUTINY_METADATA WHERE (\"SOURCE_TABLE\",\"TARGET_TABLE\",\...
194654807_4
class InstallManager { public Path install(BuildahConfiguration buildahConfiguration) throws IOException { final LocationResolver locationResolver = this.locationResolverChain.getLocationResolver(buildahConfiguration); return install(locationResolver.getBuildahName(), locationResolver.loadBuildahRe...
// Given when(locationResolverChain.getLocationResolver(any(BuildahConfiguration.class))).thenReturn(locationResolver); when(locationResolver.getBuildahName()).thenReturn("hellobuildah.txt"); when(locationResolver.loadBuildahResource()).thenReturn(new ByteArrayInputStream("binaries/hel...
194726816_0
class MultiSignaturePublicKey implements ByteSequence { public static MultiSignaturePublicKey create(List<PublicKey> publicKeys, int threshold) { byte[] multiSigPublicKeyBytes = new byte[publicKeys.size() * PUBLIC_KEY_LENGTH + 1]; int counter = 0; for (PublicKey pk : publicKeys) { ...
MultiSignaturePublicKey multisigPubKey = MultiSignaturePublicKey.create(asList(PublicKey.fromHexString(PUBKEY1), PublicKey.fromHexString(PUBKEY2), PublicKey.fromHexString(PUBKEY3)), 2); assertThat(multisigPubKey.toString(), is( "df2226d8633a4f392cca1c5d198ae10e99e1192b51...
194776722_7
class Line { public boolean isVertical() { return this.isVerticalLine; } public Line(Point p1, Point p2); public Line(Point point, double slope); public Line(double slope, double yIntercept); public double perpendicularSlope(); public double evaluate(double x); public Point...
// We correctly assign slope and intercept Line base = new Line(-1, 2); assertEquals(base.slope, -1); assertEquals(base.intercept, 2); assertFalse(base.isVertical()); // We convert from point slope to slope intercept properly Point p1 = new Point(-1000, 1002); ...
194907949_1
class OreSettingsYamlImpl implements ConfigurationSerializable, OreSettings { @NotNull @Override public Ore getOre() { return this.ore; } public OreSettingsYamlImpl(@NotNull final Ore ore); public OreSettingsYamlImpl(@NotNull final Ore ore, @NotNull final Map<Setting, Double> setting...
for (Ore ore : Ore.values()) assertSame(ore, new OreSettingsYamlImpl(ore).getOre()); for (Ore ore : Ore.values()) assertSame(ore, new OreSettingsYamlImpl(ore, new HashMap<>()).getOre()); } }
195077933_15
class AccountController { @GetMapping(path = "/list") @Authorize(value = { AuthConstant.AUTHORIZATION_SUPPORT_USER }) public ListAccountResponse listAccounts(@RequestParam int offset, @RequestParam @Min(0) int limit) { AccountList accountList = accountService.list(offset, limit); ...
// arrange mock when(mailClient.send(any(EmailRequest.class))).thenReturn(BaseResponse.builder().message("email sent").build()); // first account String name = "testAccount001"; String email = "test001@staffjoy.xyz"; String phoneNumber = "18001801236"; String sub...
195297601_0
class CurrencyConverter { public BigDecimal convert(BigDecimal amount, String currencyFrom, String currencyTo) { BigDecimal exchangeRate = currencyDto.getExchangeRate(currencyFrom, currencyTo); return amount.multiply(exchangeRate); } public CurrencyConverter(CurrencyDto currencyDto); public static Cur...
Assertions.assertEquals(converter.convert(BigDecimal.TEN, "EUR", "USD"), new BigDecimal("100")); Assertions.assertTrue(currencyDto.isMethodCalled()); } }
195330123_50
class HBaseClient10 extends com.yahoo.ycsb.DB { @Override public Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { // if this is a "new" table, init HTable object. Else, use existing one if (!tableName.equals(table)) { ...
// Fill with data final String colStr = "row_number"; final byte[] col = Bytes.toBytes(colStr); final int n = 10; final List<Put> puts = new ArrayList<Put>(n); for(int i = 0; i < n; i++) { final byte[] key = Bytes.toBytes(String.format("%05d", i)); final byte[] value = java.nio.ByteB...
195429957_0
class OpenTracingUtil { public static Span getSpan() { Context c = Vertx.currentContext(); return c == null ? null : c.getLocal(ACTIVE_SPAN); } public static void setSpan(Span span); public static void clearContext(); private Vertx vertx; private MockTracer tracer; } class OpenTracingUtilTest {...
Span span = tracer.buildSpan("test").start(); vertx.runOnContext(ignored -> { assertNull(OpenTracingUtil.getSpan()); Context context = Vertx.currentContext(); context.putLocal(ACTIVE_SPAN, span); assertSame(span, OpenTracingUtil.getSpan()); }); } }
195650526_707
class SignatureAlgorithmConverter { static String toJavaName(String opensslName) { if (opensslName == null) { return null; } Matcher matcher = PATTERN.matcher(opensslName); if (matcher.matches()) { String group2 = matcher.group(2); if (group2 != n...
assertEquals("SHA512withRSA", SignatureAlgorithmConverter.toJavaName("sha512WithRSAEncryption")); } }
195708935_5
class Parser { public ParsedOutput parse(List<String> args) { final Command commandName = this.findCommand(args); fillShortAndLongOptions(commandName); final Map<CommandFlag, Object> options = this.findOptions(args); return new ParsedOutput(commandName, args, options); } public Parser(final ...
assertThrows( NoCommandNameFound.class, () -> { ParsedOutput output = testParser.parse(new ArrayList<>(List.of("--update"))); }); } }
196110471_5
class Handy { public static StringBuilder appendByteArrayAsHex(StringBuilder sb, byte[] ab, int of, int cb) { sb.ensureCapacity(sb.length() + cb * 2); while (--cb >= 0) { int n = ab[of++]; sb.append(nibbleToChar(n >> 4)) .append(nibbleTo...
StringBuilder sb = new StringBuilder(); Assert.assertEquals(sb, appendByteArrayAsHex(sb, new byte[] {0x01, (byte) 0xFF, 0x78, 0x5A}, 1, 2)); Assert.assertEquals(sb.toString(), "FF78"); } }
197006279_77
class SphU { public static Entry entry(String name) throws BlockException { return Env.sph.entry(name, EntryType.OUT, 1, OBJECTS0); } public static Entry entry(Method method); public static Entry entry(Method method, int count); public static Entry entry(String name, int count); public...
Method method = SphUTest.class.getMethod("testMethodEntryNormal"); Entry e = SphU.entry(method, 2); assertNotNull(e); assertTrue(StringUtil .equalsIgnoreCase(e.resourceWrapper.getName(), "com.alibaba.csp.sentinel.SphUTest:testMethodEntryNormal()")); a...
197192301_6
class ArtifactTypeUtil { public static ArtifactType discoverType(ContentHandle content, String contentType) throws InvalidArtifactTypeException { boolean triedProto = false; // If the content-type suggests it's protobuf, try that first. if (contentType == null || contentType.toLowerCase()....
Assertions.assertThrows(InvalidArtifactTypeException.class, () -> { ContentHandle content = resourceToContentHandle("example.txt"); ArtifactTypeUtil.discoverType(content, null); }); } }
197277844_0
class OAuthBearerTokenImpl implements OAuthBearerToken { static String getPayload(String token) { int first = token.indexOf('.'); int last = token.lastIndexOf('.'); return token.substring(first+1, last); } public OAuthBearerTokenImpl(String token); private static String pars...
String payload = "eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJteXByb2plY3QiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiZGVmYXVsdC10b2tlbi1ydHE2ayIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJkZWZhdWx0Iiwia3ViZX...
197729287_0
class Movie extends BaseObservable implements Serializable { @Bindable public String getTitle() { return title; } @Ignore public Movie(); public Movie(String posterPath, boolean adult, String overview, String releaseDate, int id, String originalTitle, String originalLanguage, String titl...
final String mTitle = "Alita: Battle Angel"; Movie newMovie = new Movie(); newMovie.setTitle(mTitle); assertEquals(newMovie.getTitle(), mTitle); } }
197782274_0
class Contact implements Comparable<Contact> { @Override public int compareTo(Contact contact) { String givenName1 = this.givenName == null ? "" : this.givenName.toLowerCase(); String givenName2 = contact == null ? "" : (contact.givenName == null ? "" : contact.givenName.toLowerCase...
Contact contact1 = new Contact("id"); contact1.givenName = "givenName"; Contact contact2 = new Contact("id2"); assertThat(contact1.compareTo(contact2)) .isGreaterThan(0); } }
198181246_11
class ServiceCombClient { public List<ServiceInstance> getInstances(Microservice microservice, String revision) { List<ServiceInstance> instanceList = new ArrayList<>(); Response response = null; try { Map<String, String> heades = Maps.newHashMap(); String CONSUMER_HEADER = "X-ConsumerId"; ...
final int expectedCode = 200; Response response = new Response(); response.setStatusCode(expectedCode); String responseString = "{\n" + " \"instances\": [\n" + " {\n" + " \"instanceId\": \"1\",\n" + " \"serviceId\": \"2\",\n" + " \"version\": \"...
198220069_27
class FilterMessageSupport { public List<ByteBuffer> filter(Consumer consumer, List<ByteBuffer> byteBuffers, FilterCallback filterCallback) throws JoyQueueException { FilterPipeline<MessageFilter> filterPipeline = filterRuleCache.get(consumer.getId()); if (filterPipeline == null) { filt...
// Consumer consumer, List<ByteBuffer> byteBuffers, FilterCallback filterCallback List<ByteBuffer> byteBufferList = new LinkedList<>(); for (int i = 0; i < 10; i++) { ByteBuffer allocate = ByteBuffer.allocate(100); allocate.position(59); allocate.putShort((sho...