id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
153061118_9
class RocketMQUtil { @Deprecated public static org.apache.rocketmq.common.message.Message convertToRocketMessage( ObjectMapper objectMapper, String charset, String destination, org.springframework.messaging.Message message) { Object payloadObj = message.getPayload(); byte[] payl...
Message msgWithStringPayload = MessageBuilder.withPayload("test body") .setHeader("test", 1) .setHeader(RocketMQHeaders.TAGS, "tags") .setHeader(RocketMQHeaders.KEYS, "my_keys") .build(); org.apache.rocketmq.common.message.Message rocketMsg = RocketMQUtil....
153085231_2
class AccountManager { void registerAccount(String dlt, Account account) throws IllegalKeyException, EmptyAccountException { if (null == dlt) { throw new IllegalKeyException(); } else if (null == account) { throw new EmptyAccountException(); } if (null == thi...
Assertions .assertThatThrownBy(() -> this.accountManager.registerAccount(null, null)) .isInstanceOf(IllegalKeyException.class) .hasMessage("DLT type is not found"); } }
153088484_15
class AccountCmd extends BaseCmd { @CmdAnnotation(cmd = "ac_updatePassword", version = 1.0, description = "根据原密码修改账户密码/Modify the account password by the original password") @Parameters(value = { @Parameter(parameterName = "chainId", requestType = @TypeDescriptor(value = int.class), parameterDes = ...
try { //创建未加密账户 create unencrypted account List<String> accountList = CommonRpcOperation.createAccount(chainId, 1, password); String address = accountList.get(0); //为未设置密码的账户修改密码 change password for account Map<String, Object> params = new HashMap<>()...
153224042_12
class FileUtils { @Nullable static String calculateMd5(@NonNull InputStream inputStream) { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { VLog.w(e, "Exception while getting digest"); retur...
Assert.assertEquals("2a66a876a40630539e220890dc897550", FileUtils.calculateMd5(getInputStream("com.wlqq.phantom.plugin.sample1_1.0.0.apk"))); } }
153274035_4
class HeaderUtils { public static Long valueAsLong(Headers headers, String key) { return asLong(value(headers, key)); } private HeaderUtils(); public static Long asLong(byte[] value); public static String asString(byte[] value); public static String valueAsString(Headers headers, Str...
assertThat(valueAsLong(new RecordHeaders(), "some-invalid-key")).isNull(); } }
153278268_6
class PokerHelper { public static PokerSell checkPokerType(List<Poker> pokers) { if(pokers != null && ! pokers.isEmpty()) { sortPoker(pokers); int[] levelTable = new int[20]; for(Poker poker: pokers) { levelTable[poker.getLevel().getLevel()] ++; } int startIndex = -1; int endIndex = -1; ...
pokers.clear(); Assert.assertNull(PokerHelper.checkPokerType(pokers).getSellPokers()); Assert.assertEquals(-1,PokerHelper.checkPokerType(pokers).getScore()); Assert.assertEquals(SellType.ILLEGAL,PokerHelper.checkPokerType(pokers).getSellType()); pokers.add(new Poker(PokerLevel.L...
153280357_3
class MongoTokenStore implements TokenStore { @Override public void initializeSegment(TrackingToken token, String processorName, int segment) throws UnableToInitializeTokenException { try { AbstractTokenEntry<?> tokenEntry ...
GlobalSequenceTrackingToken testToken = new GlobalSequenceTrackingToken(100); tokenStore.initializeSegment(testToken, testProcessorName, testSegment); // Initializes the given token twice, causing the exception assertThrows( UnableToInitializeTokenException.class, ...
153314760_9
class SpringHttpCommandBusConnector implements CommandBusConnector { @Override public <C> void send(Member destination, CommandMessage<? extends C> commandMessage) { shutdownLatch.ifShuttingDown("JGroupsConnector is shutting down, no new commands will be sent."); if (destination.local()) { ...
testSubject.send(DESTINATION, COMMAND_MESSAGE); verify(executor).execute(any()); verify(serializer).serialize(COMMAND_MESSAGE.getMetaData(), byte[].class); verify(serializer).serialize(COMMAND_MESSAGE.getPayload(), byte[].class); HttpEntity<SpringHttpDispatchMessage<String>> ex...
153620926_0
class DemoService { @DbLog(resource = "demoResource", action = "demoAction") public void sayHello() { System.out.println("hello foo.\n"); } @Autowired private DemoService demoService; @Autowired @Qualifier("dbLogJdbcTemplate") private JdbcTemplate jdbcTemplate; } class DemoSe...
// 清空数据 jdbcTemplate.update("delete from `log`"); demoService.sayHello(); // 检查 sayHello 是否在数据库里插入了正确的数据 Map<String, Object> result = jdbcTemplate.queryForMap("select * from `log`"); // 校验数据是否和预期的一致 Assert.assertEquals("demoResource", result.get("resource")); /...
153720290_4
class RequestServiceImpl implements JdbcRequestService { @Override public ApiResponse apply(JdbcExecutor sender, String user, String password) { return apply(sender, JdbcJsonBuilder.buildAuthJson(user, password, "")); } @Override @SuppressWarnings("unchecked") public ApiResponse apply(JdbcExec...
String jsonString = "{\"database\":cube,\"requestType\":\"SQL\",\"auth\":\"authCode\",\"requestId\":\"93eceaf1-4e47-40a1-84e9-814404eb7ad5\",\"sql\":\"select * from tableA\"}"; JdbcExecutor mockJdbcExecutor = PowerMock.createMock(JdbcExecutor.class); ApiResponse mockApiResponse = PowerMock.creat...
153720329_77
class BaseByteArrayReader implements ByteArrayReader { @Override public void release() { IoUtil.release(dataReader, lenReader, posReader); } public BaseByteArrayReader(ByteReader dataReader, LongReader posReader, IntReader lenReader); @Override public boolean isReadable(); @Override ...
mockStatic(IoUtil.class); new BaseByteArrayReader(dataReader, posReader, lenReader).release(); verifyStatic(IoUtil.class); IoUtil.release(dataReader, lenReader, posReader); } }
154016270_39
class PmdSensor implements Sensor { @Override public boolean shouldExecuteOnProject(Project project) { return (hasFilesToCheck(Type.MAIN, PmdConstants.REPOSITORY_KEY)) || (hasFilesToCheck(Type.TEST, PmdConstants.TEST_REPOSITORY_KEY)) || (hasFilesToCheck(Type.MAIN, PmdConstants.XML_REPOSITORY_KEY)); } pu...
addOneJavaFile(Type.MAIN); addOneXmlFile(Type.MAIN); boolean shouldExecute = pmdSensor.shouldExecuteOnProject(project); assertThat(shouldExecute).isTrue(); } }
154099498_57
class ChannelServiceHttpClient { @WorkerThread @NonNull public <T> LineApiResponse<T> postWithJson( @NonNull Uri uri, @NonNull Map<String, String> requestHeaders, @NonNull String postData, @NonNull ResponseDataParser<T> responseDataParser) { return se...
Map<String, String> requestHeaders = new HashMap(); requestHeaders.put("headerKey1", "headerValue1"); requestHeaders.put("headerKey2", "headerValue2"); String postData = "{\"text\": \"hello\"}"; setResponseData("test".getBytes(CHARSET)); LineApiResponse<String> responseD...
154137427_0
class DateUtils { public static boolean dateIsBefore(String standDate, String desDate) { try { return YYYYMMDD_FORMAT.parse(desDate).before(YYYYMMDD_FORMAT.parse(standDate)); } catch (ParseException var3) { var3.printStackTrace(); return false; } } ...
assertEquals(DateUtils.dateIsBefore("2017-12-26","2017-12-25"),true); } }
154246246_56
class WalletManager { public static Wallet importWalletFromMnemonic(Metadata metadata, @Nullable String accountName, String mnemonic, String path, @Nullable List<EOSKeystore.PermissionObject> permissions, String password, boolean overwrite) { if (metadata.getSource() == null) metadata.setSource(Metadata.F...
String m; m = "attack curtain frog balcony trash base twenty history cradle cruel illness attitude"; Wallet wallet = WalletManager.importWalletFromMnemonic( new Metadata(ChainType.BITCOIN, Network.TESTNET, "name", "passwordHint"), m, BIP44Util.BITCOIN_TESTNET_PATH, SampleKey.PASSWORD, true);...
154382730_14
class StatisticServiceImpl implements StatisticService { @Override public Mono<Long> eventsCount(EventType type) { return repository.findByEventType(type) .map(r -> 1) .reduce(0L, Long::sum); } @Autowired public StatisticServiceImpl(StatisticRepository repository, ...
StatisticDocument statisticDocument1 = new StatisticDocument(); statisticDocument1.setId("Stat1"); statisticDocument1.setEventType(EventType.SHORTENER_VIEWED); StatisticDocument statisticDocument2 = new StatisticDocument(); statisticDocument2.setId("Stat2"); statisticDocument2.setEventType(Even...
154510460_4
class Calculator { public double subtraction(double firstOperand, double secondOperand) { return firstOperand - secondOperand; } public double addition(double firstOperand, double secondOperand); public double division(double firstOperand, double secondOperand); public double multiplicatio...
double resultSub = mCalculator.subtraction(2d, 10d); assertThat(resultSub, is(equalTo(-8d))); } }
154647700_15
class VaadinConnectController { @PostMapping(path = "/{service}/{method}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<String> serveVaadinService( @PathVariable("service") String serviceName, @PathVariable("method") String methodName, @RequestBody(required = false) Obj...
int inputValue = 222; String expectedMessage = "OOPS"; class MyCustomException extends VaadinConnectException { public MyCustomException() { super(expectedMessage); } } Method serviceMethodMock = createServiceMethodMockThatThrows(inputValue, new InvocationTargetExceptio...
154974836_3
class FunctionalClass { public <F> @NonNull FunctionalProperty<T, F> field(final @NonNull String name) { final PropertyDescriptor descriptor = this.getPropertyDescriptor(name); return new FunctionalProperty<>(descriptor); } public Supplier<T> getConstructor(); private PropertyDescripto...
assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> of(Person.class).field("i")) .withCauseInstanceOf(IntrospectionException.class) .withMessageContaining("Unknown property: i") .satisfies( exception ...
155078306_3
class DataProxy { protected static String map1stMatchingTagNames(SpanPack pack, String tagNames) { if (StringUtil.isEmpty(tagNames)) { return null; } return Arrays.stream(tagNames.split(",")) .map(tag -> pack.tags.getText(tag)) .filter(StringUtil:...
assertThat(DataProxy.map1stMatchingTagNames(pack, "tag1"), is(pack.tags.getText("tag1"))); assertThat(DataProxy.map1stMatchingTagNames(pack, "tag2"), is(pack.tags.getText("tag2"))); assertThat(DataProxy.map1stMatchingTagNames(pack, "tag1,tag2"), is(pack.tags.getText("tag1"))); assertThat...
155195958_0
class ID3 { public boolean setTag(SongItem songItem) throws IOException, NotSupportedException { ID3v23Tag tag = new ID3v23Tag(); tag.setTitle(songItem.name); tag.setArtist(songItem.artist); tag.setAlbumArtist(songItem.artist); tag.setAlbum(songItem.album); mp3File.s...
for (File testFile: testFileList) { ID3 id3 = new ID3(testFile); SongItem songItem = new SongItem(); songItem.name = testName; songItem.artist = testArtist; boolean result = id3.setTag(songItem); Assert.assertEquals(result, true); }...
155383451_87
class AbstractApiDocService { protected void preparePath(N path, ApiDocPath<N> apiDocPath, ApiDocInfo apiDocInfo, String basePath, String originalEndpoint, String serviceId) { log.trace("Swagger Service Id: " + serviceId); log.trace("Original Endpoint: " + originalEndpoint); log.trace("Base...
List<Server> servers = new ArrayList<>(); servers.add(0, new Server().url("/apicatalog")); ApiDocPath<PathItem> apiDocPath = new ApiDocPath<>(); OpenAPI openAPI = getDummyOpenApiObject(servers); String apiDocContent = convertOpenApiToJson(openAPI); RoutedService routedSe...
155449545_1
class AccountNumber implements Serializable, Formattable, Comparable<AccountNumber> { @Override public void formatTo(Formatter formatter, int flags, int width, int precision) { formatter.format("%s-%s", value / 1000, value % 1000); } private AccountNumber(int value); public static Accoun...
assertEquals("123-123", String.format("%s", AccountNumber.of(123123))); assertEquals("1234-321", String.format("%s", AccountNumber.of(1234321))); } }
155476310_2
class SignatureUtils { public static String awsV4BuildCanonicalRequestString( HttpUriRequest httpMethod, String requestPayloadHexSha256Hash) { URI uri = httpMethod.getURI(); String httpRequestMethod = httpMethod.getMethod(); Map<String, String> headersMap = new HashMap<String, ...
final URI uri = new URI("" + "https://test-eu-central-1-mountainduck.s3-eu-central-1.amazonaws.com:443/?max-keys=1000&prefix=a%2F&delimiter=%2F"); final String method = "GET"; final Map<String, String> headers = new HashMap<String, String>(); headers.put("date", "Mon, 18 ...
155618699_62
class OutputFormatsHandler implements CliOptionHandler { @Override public void handle(String optionValue, Options options) { Set<OutputFormat> formats = ImmutableSet.of(OutputFormat.STDOUT); if (!StringUtils.isBlank(optionValue)) { try { String[] formatStrings = opt...
// given Options options = new Options(); // when underTest.handle("something", options); // then assertThat(options.getOutputFormats()).isEqualTo(of(OutputFormat.STDOUT)); } }
155886348_74
class RouteUtils { public boolean isArrivalEvent(@NonNull RouteProgress routeProgress, @NonNull Milestone milestone) { if (!(milestone instanceof BannerInstructionMilestone)) { return false; } boolean isValidArrivalManeuverType = upcomingStepIsArrivalManeuverType(routeProgress) || currentStep...
DirectionsRoute route = buildTestDirectionsRoute(); int first = 0; int lastInstruction = 1; RouteLeg routeLeg = route.legs().get(first); List<LegStep> routeSteps = routeLeg.steps(); int currentStepIndex = routeSteps.size() - 2; int upcomingStepIndex = routeSteps.size() - 1; LegStep curre...
155931552_1
class UtilFunctions { @CustomFunctionResolver("DensityCustomFunctionResolver0") public static Double Density(List<Tuple> things) { if(things == null || things.size() == 0) return null; double sumDensity = 0.0; int numValidThings = 0; Double density = null; ...
List<Tuple> t = new ArrayList<Tuple>(); assertNull(UtilFunctions.Density(t)); } }
155961075_0
class DefaultGraphQLInvocation implements GraphQLInvocation { @Override public Mono<ExecutionResult> invoke(GraphQLInvocationData invocationData, ServerWebExchange serverWebExchange) { ExecutionInput.Builder executionInputBuilder = ExecutionInput.newExecutionInput() .query(invocationDat...
String query = "query myQuery {foo}"; String operationName = "myQuery"; Map<String, Object> variables = new LinkedHashMap<>(); DefaultGraphQLInvocation defaultGraphQLInvocation = new DefaultGraphQLInvocation(); ExecutionInputCustomizer executionInputCustomizer = mock(ExecutionI...
156101856_17
class PlantUMLClassDiagramGenerator { public String generateDiagramText() throws ClassNotFoundException, IOException { resolvedClasses.clear(); // read all classes from directories or jars resolvedClasses.addAll(getAllDiagramClasses()); // sort all classes for a reliable sorted result Collections.sort(resol...
String filename = "0018_blacklist_fields.txt"; URL testResourceURL = this.getClass().getClassLoader().getResource(filename); String testResourceURLString = testResourceURL.toString(); String testClassPath = testResourceURLString.substring(0, testResourceURLString.length() - filename.length()) + "../../src/t...
156298013_124
class Convert { public static BigDecimal toSha(String number, Unit unit) { return toSha(new BigDecimal(number), unit); } private Convert(); public static BigDecimal fromSha(String number, Unit unit); public static BigDecimal fromSha(BigDecimal number, Unit unit); public static BigDec...
assertThat(Convert.toSha("21", Convert.Unit.SHA), is(new BigDecimal("21"))); assertThat(Convert.toSha("21", Convert.Unit.KSHA), is(new BigDecimal("21000"))); assertThat(Convert.toSha("21", Convert.Unit.MSHA), is(new BigDecimal("21000000"))); assertThat(Convert.toSha("21", Convert.Unit.GS...
156317154_6
class WildcardUtils { @Nullable public static LinearRange rangeOfMatch(String pattern, String str) { List<LinearRange> literalRanges = getLiteralRanges(pattern); int first = -1; int pos = 0; for (LinearRange literalRange: literalRanges) { String literal = pattern.substring(literalRange.getFrom(), l...
assertEquals("1-3", rangeOfMatch("el", "hello").toString()); assertEquals(null, rangeOfMatch("tu", "hello")); assertEquals("3-8", rangeOfMatch("lo*wo", "hello world").toString()); assertEquals("3-9", rangeOfMatch("lo*w?r", "hello world").toString()); assertEquals("12-37", rangeOfMatch("this*my*program", "hell...
156459372_14
class Exercise4 { static <A> List<A> reverse(final List<A> list) { return Lists.foldLeft(list, Collections.emptyList(), (reversedList, item) -> Lists.prepend(item, reversedList) ); } static Integer maximum(final List<Integer> list); static Integer minimum(final List<Int...
// given: final List<Integer> list = asList(1, 2, 3, 4); final List<Integer> expected = asList(4, 3, 2, 1); // when: final List<Integer> actual = Exercise4.reverse(list); // then: assertThat(actual, is(expected)); } }
156601203_7
class ThriftLogContext { public static void setRequestHeader(RequestHeader header) { threadLocal.get().setHeader(header); } private ThriftLogContext(); public static void newExecution(); public static long getTraceId(); public static void setTraceId(long traceId); public static l...
RequestHeader requestHeader = new RequestHeader(); requestHeader.setTraceId(0xDEAD); requestHeader.setSpanId(0xDEAF); requestHeader.setSampled(true); ThriftLogContext.setRequestHeader(requestHeader); assertEquals(MDC.get(ThriftLogContext.TRACE_ID), "dead"); asse...
156606443_2
class Sort { public static void sortUnsigned(long[] data) { sortUnsigned(data, 0, data.length); } public static void sortUnsigned(long[] data, int offset, int len); } class SortTest { @Test public void sortUnsignedShifted() {
Random r = new Random(1); for (int test = 0; test < 1000; test++) { int len = r.nextBoolean() ? r.nextInt(10) : r.nextInt(1000); int rotate = r.nextInt(60); long[] data = new long[len]; long xor = 0; for (int i = 0; i < len; i++) { ...
156613410_3
class Util { public static String addForInterface(String interfaceType) { if (interfaceType.contains("<")) { return null; } return shortName(interfaceType); } static boolean isVoid(String type); static boolean notVoid(String type); static String classOfMethod(String method); static Strin...
assertNull(Util.addForInterface("java.util.List<Some>")); assertEquals("Bar", Util.addForInterface("com.foo.Bar")); } }
156655880_128
class StringUtils { @SuppressWarnings("StringEquality") public static boolean isEqual(String s1, String s2) { if (s1 == null || s2 == null) { return s1 == s2; } return s1.equals(s2); } } class StringUtilsTest { @Test public void isEqual() throws Exception {
assertThat(StringUtils.isEqual(null, "a")).isFalse(); assertThat(StringUtils.isEqual("a", null)).isFalse(); assertThat(StringUtils.isEqual("a", "b")).isFalse(); assertThat(StringUtils.isEqual("a", "A")).isFalse(); assertThat(StringUtils.isEqual("a", "a")).isTrue(); assert...
156706507_0
class MarkdownReplayer implements InteractionMonitor { public void setPlaybackConversation(String conversation) { this.filename = "no filename set"; int charPosn = -1; int ctr = 0; boolean again = true; while (again) { charPosn = conversation.indexOf(SERVIRTIUM_I...
MarkdownReplayer m = new MarkdownReplayer(); try { m.setPlaybackConversation("oh noes"); fail("should have barfed"); } catch (UnsupportedOperationException e) { assertEquals("No '## Interaction' found in conversation 'oh noes'. Wrong/empty script file?", e.get...
156776643_78
class Events { public <T> void subscribe(Object token, Consumer<T> consumer) { Set<Consumer<?>> set = subscriptions.get(token); if (set == null) { set = new LinkedHashSet<>(); subscriptions.put(token, set); } set.add(consumer); } public void unsubscribe(Object topic); public void unsubscribe(Object ...
Consumer<String> consumer = stringConsumerMock(); events.subscribe(TOKEN, consumer); events.publish(TOKEN, "hello"); events.tick(); Mockito.verify(consumer) .accept("hello"); } }
156879211_11
class CorePeripheral implements Peripheral { @Override public Single<Integer> readRssi() { SingleSubject<Integer> scopedSubject = SingleSubject.create(); return scopedSubject .doOnSubscribe(disposable -> processReadRssi(scopedSubject)) .doFinally(() -> clearReadRssiSubject(scopedSubject));...
readRssiTestObserver = corePeripheral.readRssi().test(); readRssiTestObserver.assertError( throwable -> { PeripheralError error = (PeripheralError) throwable; return error != null && error.getCode() == DISCONNECTED; }); } }
157118635_2
class HelloWorldMapper extends AbstractOIDCProtocolMapper implements OIDCAccessTokenMapper, OIDCIDTokenMapper, UserInfoTokenMapper { @Override public String getHelpText() { return "Adds a hello world text to the claim"; } @Override public String getDisplayCategory(); @Override public Strin...
assertThat(new HelloWorldMapper().getHelpText()).isNotBlank(); } }
157370190_20
class Payslip { public double getNet() { final double ltbg = Math.max(Math.min(sal, 20000.0) - 5000, 0.0); final double mtbg = Math.max(Math.min(sal, 40000) - 20000, 0.0); final double utbg = Math.max(sal - 40000, 0.0); return sal - (ltbg * 0.1 + mtbg * 0.2 + utbg * 0.4); } ...
final Payslip payslip = new Payslip(50000); assertEquals(40500, payslip.getNet(), 1e-6); final Payslip payslip2 = new Payslip(60000); assertEquals(46500, payslip2.getNet(), 1e-6); } }
157413720_40
class ExtendsDirectiveProcessor extends DirectiveProcessor<DiffableScope> { @Override @SuppressWarnings("unchecked") public void process(DiffableScope scope, DirectiveNode node) { validateArguments(node, 1, 1); validateOptionArguments(node, "exclude", 0, 1); validateOptionArguments(...
scope.put("f", ImmutableList.of(1L, 2L, 3L)); processor.process(scope, parse("@extends: { f: [ 4, 5 ] } -merge true")); assertThat(scope.get("f")).isEqualTo(ImmutableList.of(1L, 2L, 3L, 4L, 5L)); } }
157564875_4
class DirectoryStructureReader { public DirectoryStructure readDirectoryStructure( String rootDirectory, String include, String exclude ) throws IOException { FileFilter filter = FileFilter.of(rootDirectory, include, exclude); List<FileEntry> allFilesEntries = directoryLister.listFiles(rootDirectory, filter); ...
createDirsAndFiles(); DirectoryStructure structure = reader.readDirectoryStructure(root.getName(), null, null); assertStructure(structure) .hasDirectories("dir1", "dir2", "dir3", "dir3/dir3X", "dir3/dir3Y") .hasFiles("fileA", "fileB", "dir1/file1A", "dir1/file1B", "dir2/file2A", "dir3/dir3X/file3XA"); } }
157572651_4
class ReactiveResilience4JCircuitBreaker implements ReactiveCircuitBreaker { @Override public <T> Mono<T> run(Mono<T> toRun, Function<Throwable, Mono<T>> fallback) { io.github.resilience4j.circuitbreaker.CircuitBreaker defaultCircuitBreaker = registry.circuitBreaker(id, config.getCircuitBreakerConfig()); cir...
ReactiveCircuitBreaker cb = new ReactiveResilience4JCircuitBreakerFactory().create("foo"); assertThat(Mono.just("foobar").transform(it -> cb.run(it)).block()).isEqualTo("foobar"); } }
157765359_1
class EiDASCertificate { public String addPsdAttibutes( String certificate, String privatekey, String passphrase, String organizationIdentifier, String ncaname, String ncaid, List<String> roles ) { String pemCertificate = certificate.replaceAll("\\\\n", "\n"); EiDASCertificate eidascert...
String orgId = null; String ncaName = "Auth"; String ncaId = "Germany"; List<String> roles = new ArrayList<String>(Arrays.asList( "PSP_AS", "PSP_PI", "PSP_AI", "PSP_IC" )); EiDASCertificate eidascert = new EiDASCertificate(); String certpem = eidascert.addPsdAttibutes( c, k, p, or...
157848372_23
class OngoingMissionRun { public ReturnHelper<Result> returnResult() { return new ReturnHelper<Result>(new ReturnResult()); } public OngoingMissionRun(Mole mole, Mono<MissionHandle> handle); public OngoingMissionRun and(); public void forget(); protected Mole mole(); public Mono<...
OngoingMissionRun.ReturnHelper<Result> resultReturnHelper = run.returnResult(); assertNotNull(resultReturnHelper.whenFinished()); assertThat(resultReturnHelper.whenFinished(), instanceOf(Result.class)); assertEquals(Result.SUCCESS, resultReturnHelper.whenFinished()); assertNotN...
157902250_1306
class HttpClient { public String post(Map<String, String> parameters) { OutputStreamWriter wr = null; BufferedReader rd = null; String response = ""; StringBuilder data = new StringBuilder(); try { // Construct data for (Map.Entry<String, String> entry : parameters.entrySet()) { // skip ov...
Map<String, String> parameters = new TreeMap<>(); parameters.put("one", "one"); parameters.put("two", "two"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); when(connection.getOutputStream()).thenReturn(stream); when(connection.getInputStream()).thenReturn(new ByteArrayInputStream("response"...
157945047_38
class SmcpDiscoveryQuery extends DiscoveryQuery { @Override public Set<Thing> get() throws InterruptedException, TechnologyException { if (!mTimeout.isCancelled()) { try { mTimeout.get(mTimeoutInMs, TimeUnit.MILLISECONDS); } catch (CancellationException | Timeou...
try { SmcpTechnology techHosting = new SmcpTechnology(mContextA); SmcpTechnology techBacking = new SmcpTechnology(mContextA); MyLightBulb localFe = new MyLightBulb(); techHosting .getServer() .addLocalEndpoint( ...
158186574_12
class JSONDecoder extends AbstractJSONDecoder { @Override public TEvent decode(String source) throws DecodeException { JSONObject object = parse(source); TEvent event = new TEvent(); decodeToEvent(event, object); return event; } public void init(); @Override public ...
TEvent event = new TEvent(); JSONDecoder decoder = new JSONDecoder(); decoder.decode(simpleSource1, event, "tgt"); JSONObject o = (JSONObject)event.get("tgt"); Assert.assertEquals("name1", o.getString("name")); Assert.assertEquals("type1", o.getString("type")); } }
158213242_39
class DefaultFormEntityProvider implements FormEntityProvider { @Override public Form getForm(ContainerRequestContext context) throws IOException { final InputStream is = context.getEntityStream(); // Ensure stream can be restored for next interceptor InputStream bufferedStream; ...
EasyMock.expect(context.getEntityStream()).andReturn(new ByteArrayInputStream("foo=bar".getBytes())); EasyMock.expect(context.getMediaType()).andReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE); context.setEntityStream(EasyMock.anyObject(InputStream.class)); EasyMock.replay(context); ...
158267213_31
class AuthorityService implements IAuthorityService { @Override public List<IAuthorityEntry> findByUri(IUser user, String uri) { List<IAuthorityEntry> results = entryRepository.findByUsernameAndUriOrderByName(user.getUsername(), uri); if (uri.endsWith("/")) { uri = uri.substring(0, ...
String username = "user"; IUser user = new User(); user.setUsername(username); String uri = "http://test.uri/"; String uriNoSlash = "http://test.uri"; IAuthorityEntry entry = new AuthorityEntry(); entry.setUri(uri); List<IAuthorityEntry> entries = new Ar...
158331158_16
class ParameterValidator { public static ParameterValidatorResult getSingleValue(Enumeration<String> input) { return getSingleValue(input, null); } public static ParameterValidatorResult getSingleValue(Enumeration<String> input, String defaultValue); public static ParameterValidatorResult getSingleValue(S...
String[] value = new String[0]; ParameterValidatorResult result = ParameterValidator.getSingleValue(value); assertEquals(ParameterValidatorResult.RESULT.NONE, result.getResult()); } }
158452696_4
class AkkaStreamsDemo implements ReactiveStreamsDemo { public static List<Integer> doParallelSquares() { final ActorSystem system = ActorSystem.create("parallel-squares"); // 1 final Materializer mat = ActorMaterializer.create(system); // 2 List<Integer> squares = new ArrayList<>(); ...
List result = demo.doParallelSquares() .stream().sorted().collect(Collectors.toList()); assertArrayEquals(squares.toArray(), result.toArray()); } }
158543059_1442
class LogTailScanner { public LogTailInformation getTailInformation() throws UnderlyingStorageException { if ( logTailInformation == null ) { try { logTailInformation = findLogTail(); } catch ( IOException e ) { ...
// given long txId = 11; setupLogFiles( logFile( checkPoint(), checkPoint(), start(), commit( txId ) ) ); // when LogTailInformation logTailInformation = tailScanner.getTailInformation(); // then assertLatestCheckPoint( true, true, txId, endLogVersion, logTailIn...
158546420_11
class AutoColumn extends GenericColumn { public GenericColumn getInternalColumn() { return internalColumn; } public AutoColumn(String name); private Consumer<String[]> createPostBuildListener(); @Override public Consumer<String[]> getPostBuildListener(); @Override public List<Transfo...
final String intAttr = "IntAttr"; AnchorTabular tabular = new AnchorTabularBuilderByName() .addColumn(new AutoColumn(intAttr)) .build(getTestCSV()); assertEquals(1, tabular.getTabularInstances()[0].getTransformedValue(intAttr)); assertEquals(2, tabular.ge...
158547266_14
class EnvvarSource extends PropertiesFormat implements ConfijSource { public static EnvvarSource withPrefix(String prefix) { return new EnvvarSource(prefix); } protected EnvvarSource(String prefix); @Override public void override(ConfijNode rootNode); } class EnvvarSourceTest implements ConfijSource { @Te...
String value1 = UUID.randomUUID() + ""; String value2 = UUID.randomUUID() + ""; SystemLambda.withEnvironmentVariable("A_PREFIX_xy", value1) .and("A_PREFIX_others_fuu.", value2) .and("A_PREFIXORNORATALL_xy", "fuuuuu") .execute(() -> { Config config = ConfijBuilder.of(Config.class) .loadFrom...
158618423_2
class SimpleStoreImpl implements SimpleStore { @Override public ListenableFuture<Void> clear() { requireOpen(); return Futures.submitAsync( () -> { Exception isDead = isDead(); if (isDead != null) { return Futures.immediateFailedFuture(isDead); } ...
try (SimpleStore store = SimpleStoreFactory.create(directoryProvider, SAMPLE_SCOPE)) { store.put(TEST_KEY, new byte[1]).get(); store.clear().get(); ListenableFuture<byte[]> empty = store.get(TEST_KEY); assertThat(empty.get()).isEmpty(); } } }
158704131_0
class JsonFormatter implements Formatter { @Override public String format(Object object) { try { return objectMapper.writeValueAsString(object); } catch (JsonProcessingException e) { // 解析失败返回非法参数异常 throw new IllegalArgumentException(e); } } ...
JsonFormatter formatter = new JsonFormatter(); Assert.assertEquals("{\"id\":1,\"name\":\"小马哥\"}", formatter.format(new User())); } }
158831879_0
class KnowNERLanguageConfigurator { public List<String> run() throws KnowNERLanguageConfiguratorException { List<String> errorMessages = new ArrayList<>(); for (KnowNERResourceChecker checker : checkerList) { logger.info("Creating '" + language + "' KnowNER resources for " + checker.getClass().getSimpl...
KnowNERResourceChecker mockedChecker = mock(KnowNERResourceChecker.class); when(mockedChecker.check()).thenReturn(new KnowNERResourceResult()); KnowNERLanguageConfigurator configurator = new KnowNERLanguageConfiguratorBuilder() .setLanguage("de") .setMainDir("") .addResourceChecker(mockedChecker) ...
158992067_14
class KeyMatcher implements Matcher { public String match(Set<String> sources, String target ) { return sources.contains(target) || sources.isEmpty() ? target : matchMissingKey(sources,target); } private String[] getSegments(String s); private boolean isBoundedT...
String nonExistentTarget = "A.X"; final String match = keyMatcher.match(listeners, nonExistentTarget); assertEquals("A.*", match); } }
159189646_3
class SwaggerBasePathRewritingFilter extends SendResponseFilter { @Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); context.getResponse().setCharacterEncoding("UTF-8"); String rewrittenResponse = rewriteBasePath(context); if (context....
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL); RequestContext context = RequestContext.getCurrentContext(); context.setRequest(request); MockHttpServletResponse response = new MockHttpServletResponse(); context.setResponseGZipped(f...
159208572_0
class CustomerSync { public boolean syncWithDataLayer(ExternalCustomer externalCustomer) { CustomerMatches customerMatches; if (externalCustomer.isCompany()) { customerMatches = loadCompany(externalCustomer); } else { customerMatches = loadPerson(externalCustomer); ...
String externalId = "12345"; ExternalCustomer externalCustomer = createExternalCompany(); externalCustomer.setExternalId(externalId); Customer customer = createCustomerWithSameCompanyAs(externalCustomer); customer.setExternalId(externalId); CustomerDataLayer db = mock(...
159473524_4
class RecipientServiceImpl implements RecipientService { @Override @CatAnnotation public Recipient save(String accountName, Recipient recipient) { recipient.setAccountName(accountName); recipient.getScheduledNotifications().values() .forEach(settings -> { if (settings.getLastNotified() == null) { ...
NotificationSettings remind = new NotificationSettings(); remind.setActive(true); remind.setFrequency(Frequency.WEEKLY); remind.setLastNotified(null); NotificationSettings backup = new NotificationSettings(); backup.setActive(false); backup.setFrequency(Frequency.MONTHLY); backup.setLastNotified(new D...
159519764_0
class AdvertisementService { @PreAuthorize("hasPermission(#id, 'com.sap.cp.appsec.domain.Advertisement', 'read')") public Advertisement findById(Long id) throws NotFoundException { Optional<Advertisement> advertisement = repository.findById(id); if (!advertisement.isPresent()) { Not...
Advertisement adsRead = service.findById(advertisementId); assertThat(adsRead, is(notNullValue())); } }
159537834_32
class GraphQLConverter { <K extends Entity.Key<S>, S extends Specification> Mutation<?, ?, ?> convert(Event<K, S> event) { var converter = (Converter<?, ?, ?, ?, K, S>) converters.get(event.getKey().getClass()); if (converter == null) { throw new IllegalArgumentException("Unknown key class " + event.g...
var mutation = underTest.convert(Event.status(producerKey, statusEntry)); assertThat(mutation, is(instanceOf(ProducerStatusMutation.class))); } }
159544942_2
class NativeSoftBodyUtil { public static FloatBuffer mapVertexData(IntBuffer indexMap, FloatBuffer inputBuffer, int numFloatsPerVertex) { Validate.nonNull(indexMap, "index map"); Validate.positive(numFloatsPerVertex, "number of floats per vertex"); int numFloats = inputBuffer.li...
/* * Exemple : * mesh : P1\P3----P4 * ¦¯\_ ¦ * ¦ ¯\_¦ * P2----P6\P5 * * with P1==P3 and P6==P5 * Buffers indexes : | 0| 1| 2| 3| 4| 5| * >- JME PositionBuffer : [P1,P2,P3,P4,P5,P6] ...
159894918_4
class Game2048BoardManager implements Serializable { void action(Game2048Layout.Action action) { saveStates(activityContext); game2048ScoreManager.saveScore(getGame2048ScoreManager().calculateScore()); for (int i = 0; i < complexity; i++) { List<Game2048Item> rowList = new Array...
initializeBoard(); initializeListener(); testBoardManagerInit(); fillBoardWithZero(); Game2048Layout.Action leftAction = Game2048Layout.Action.LEFT; Game2048Layout.Action rightAction = Game2048Layout.Action.RIGHT; Game2048Layout.Action upAction = Game2048Layout.Ac...
160156999_13
class HelloWorldService extends MutinyGreeterGrpc.GreeterImplBase { @Override public Uni<HelloReply> sayHello(HelloRequest request) { int count = counter.incrementAndGet(); String name = request.getName(); return Uni.createFrom().item("Hello " + name) .map(res -> HelloRe...
GreeterGrpc.GreeterBlockingStub client = GreeterGrpc.newBlockingStub(channel); HelloReply reply = client .sayHello(HelloRequest.newBuilder().setName("neo-blocking").build()); assertThat(reply.getMessage()).isEqualTo("Hello neo-blocking"); } }
160219599_13
class Range implements Iterable<E> { public void merge(Range<E> range) { first = min(first, range.getFirst()); last = max(last, range.getLast()); } public Range(E element); public Range(E first, E last); public Range(E first, E last, IEnumerator<E> enumerator); public Range...
Range<Integer> range; (range = range(-10, 10)).merge(range(-20, -11)); assertEquals(range(-20, 10), range); (range = range(-10, 10)).merge(range(-20, -10)); assertEquals(range(-20, 10), range); (range = range(-10, 10)).merge(range(-10, 10)); assertEquals(range(...
160260778_2
class Creator { public Class createModel(CreatorConfig config) throws Exception { this.config = config; buildGraph(); generateAndCompileEvents(); generateAndCompileNodes(); return generateAndCompileSepConfig(); } private void buildGraph(); private void generateA...
ConfigParser parser = new ConfigParser(); String outPkg = GenerationContext.SINGLETON.getPackageName(); String configDoc = "" + "outputPackage: " + outPkg + "\n" + "outputSepConfigClass: " + outPkg + ".MySepCfg\n" + "processorId: processor1\n" ...
160304314_0
class GithubCommentManager { public int deleteComment(Predicate<Comment> commentPredicate) throws IOException { List<Comment> comments = issueService.getComments(repoId, issueNumber); int delCount = 0; for (Comment c : comments) { if (logger.isDebugEnabled()) { logger.debug("pre filtered comment {} : {}...
when(mockIssue.getComments(repositoryId, prNum)) .thenReturn(Collections.singletonList(new Comment().setId(1).setBody("test") .setUser(new User().setId(1)))); doNothing().when(mockIssue) .deleteComment(repositoryId, 1); GithubCommentManager manager = new GithubCommentManager(mockIssue, repositoryId...
160760515_102
class FavoriteService { public void deleteFavorite(long favoriteId) { Favorite favorite = favoriteRepository.findById(favoriteId).orElse(null); checkUserOperatePermission(favorite); favoriteRepository.delete(favorite); } public Favorite addFavorite(Favorite favorite); public List<Favorite> searc...
long legalFavoriteId = 21L; favoriteService.deleteFavorite(legalFavoriteId); Assert.assertNull(favoriteRepository.findById(legalFavoriteId).orElse(null)); } }
160777074_17
class PullMessageFilterChain { boolean needKeep(final PullRequest request, final Buffer message) { for (PullMessageFilter filter : filters) { if (filter.isActive(request, message) && !filter.match(request, message)) { return false; } } return true; } PullMessageFilterChain(final DynamicConfig con...
Whitebox.setInternalState(pullMessageFilterChain, "filters", Lists.newArrayList(activeAndMatchFilter, activeAndMatchFilter)); PullRequest request = TestToolBox.createDefaultPullRequest(); Buffer buffer = TestToolBox.createDefaultBuffer(); boolean needKeep = pullMessageFilterChain.needKeep(request, buffer); ...
160877396_0
class BorgInstallation { File download(RunningMode.OSType osType) { String[] binary = getBinary(osType); if (binary == null) { log.info("Can't download binary (no binary found for OS '" + osType + "'."); return null; } return download(binary); } priv...
String version = new BorgVersion().getBinariesDownloadVersion(); checkDownload(RunningMode.OSType.LINUX, "borg-linux64-" + version); checkDownload(RunningMode.OSType.MAC_OS, "borg-macosx64-" + version); checkDownload(RunningMode.OSType.FREEBSD, "borg-freebsd64-" + version); asser...
160931942_7
class ExchangeRateUtil { public JSONObject parseBlockchainInfoResponse(JSONObject response) { JSONObject formattedRates = new JSONObject(); // loop through all returned currencies Iterator<String> iter = response.keys(); while (iter.hasNext()) { String fiatCode = iter.n...
JSONObject in = new JSONObject(readStringFromFile("exchange_rate_blockchain_info_response.json")); JSONObject out = ExchangeRateUtil.getInstance().parseBlockchainInfoResponse(in); assertEquals(2, out.length()); assertEquals(1E-8, out.getJSONObject("USD").getDouble("rate")); } }
161138654_31
class HttpClientTransport implements RestTransport { @Segment(name = "transport", category = "network", library = "kamon") @Override public SagaResponse with(String address, String path, String method, Map<String, Map<String, String>> params) { URIBuilder builder = new URIBuilder().setScheme("http").setHost(...
try { transport.with("http://somewhere:9090", faultyResource, "DELETE", emptyMap()); expectFailing(TransportFailedException.class); } catch (TransportFailedException e) { assertThat(e.getMessage(), is("Network Error")); } } }
161169958_4
class RepositoryDataPollingService implements Runnable { @Override public void run() { final PollingTimeslice pollingTimeslice = lastPolledService.getPollingTimeslice(); LOGGER.info("Start polling repository data: {}", pollingTimeslice); pollProcessDefinitions(pollingTimeslice); ...
// define polling cycle when(lastPolledService.getPollingTimeslice()) .thenReturn(new PollingTimeslice(CUTOFF_TIME.date, START_TIME.date, END_TIME.date)); ...
161246688_26
class CreditCardGenerator { public CreditCardGenerator(){ this.type = null; } public CreditCardGenerator(); public CreditCardGenerator(String type); public String generate(); private int generateCheckDigit(String number); public String getType(); public void setType(String t...
for (int i=0;i<100;i++) { CreditCardGenerator creditCardGenerator = new CreditCardGenerator(); String value = creditCardGenerator.generate(); switch (creditCardGenerator.getType()){ case "AMEX": Assert.assertEquals(value.charAt(0),'3'); ...
161378406_0
class RestliServerComponent extends BaseRestliServerComponent<RestRequest> implements RestliServerApi { @Override public void handleRequest(final Http.Request request, final RestliTransportCallback callback) throws Exception { RestRequest restRequest = createRestRequest(request); if (restRequest == null) {...
Capture<RequestContext> captureContext = newCapture(); _httpDispatcher.handleRequest(EasyMock.<RestRequest>anyObject(), capture(captureContext), anyObject()); expectLastCall(); replay(_httpDispatcher); Http.Request request = createDefaultRequestBuilder().remoteAddress(remoteAddress).bodyRaw(new byt...
161444854_18
class AsyncSnapshotPersistence { public void delete(final String transactionId) { synchronized (COMMITTED_TRANSACTION_ID_BUFFER) { COMMITTED_TRANSACTION_ID_BUFFER.get(0).add(transactionId); } } public AsyncSnapshotPersistence(final DataSource dataSource); private void del...
AsyncSnapshotPersistence asyncSnapshotPersistence = new AsyncSnapshotPersistence(dataSource); asyncSnapshotPersistence.delete("1"); Thread.sleep(1000); verify(statement).executeBatch(); verify(connection).commit(); } }
161474325_0
class DestinationDetailsController { @Timed @RequestMapping(value = "/travel/destination-details/{city}", produces = MediaType.APPLICATION_JSON) String getInfoAboutDestination(@PathVariable final String city) throws Exception { return loader.get(city); } @Autowired public DestinationDetailsController(T...
//given travelDestinationDetailsMock.addInfo("SUPER_CITY", "Beautiful Town"); //when String res = destinationDetailsController.getInfoAboutDestination("SUPER_CITY"); //then assertThat(res).isEqualTo("Beautiful Town"); } }
161493518_8
class RawConfigParser implements ConfigParser<RawConfig, Config> { @Override public @NonNull Config parse(final @Nullable RawConfig config) { Objects.requireNonNull(config); final ProducerConfig producerConfig = producerConfigParser.parse(config.producer, RawProducerConfig::new); final Records...
// given final RawConfig config = new RawConfig(); final ProducerConfig producerConfig = producerConfigParser.parse(new RawProducerConfig()); final RecordsConfig recordsConfig = recordsConfigParser.parse(new RawRecordsConfig()); config.maxInFlightRecords = 2; config.inFlightRecordCheckIntervalMs...
161649007_59
class ScoreUtils { public static double chiSquared(final double[] parentClassCounts, final double[][] childrenClassCounts) { checkGainInputs(parentClassCounts, childrenClassCounts); final double[] parentDistribution = ArrayUtilities.normalise(copy(parentClassCounts), true); double sum = 0; ...
double v = ScoreUtils.chiSquared(new int[] {8, 4}, new int[][] { {4, 2}, {4, 2}, }); Assert.assertEquals(0, v, 0.0); } }
161651256_6
class CustomSeekProvider extends PlaybackSeekDataProvider { @Override public long[] getSeekPositions() { if (!videoPlayerAdapter.canSeek()) return new long[0]; return splitIntoThirtySecondsParts(videoPlayerAdapter.getDuration()); } CustomSeekProvider(VideoPlayerAdapter videoPlayerAda...
VideoPlayerAdapter videoPlayerAdapter = mock(VideoPlayerAdapter.class); when(videoPlayerAdapter.canSeek()).thenReturn(true); when(videoPlayerAdapter.getDuration()).thenReturn(130_000L); CustomSeekProvider customSeekProvider = new CustomSeekProvider(videoPlayerAdapter); long[] e...
161654269_3
class TextSelection extends Selection { public void applyStyle(OdfStyleBase style) throws InvalidNavigationException { // append the specified style to the selection if (validate() == false) { throw new InvalidNavigationException("No matched string at this position"); } OdfElement parentElement...
search = null; search = new TextNavigation("delete", doc); OdfOfficeAutomaticStyles autoStyles = null; try { autoStyles = doc.getContentDom().getAutomaticStyles(); } catch (Exception e1) { Assert.fail("Failed with " + e1.getClass().getName() + ": '" + e1.getMessage() + "'"); } //...
161757837_7
class FileUtil extends cn.hutool.core.io.FileUtil { public static String getFileNameNoEx(String filename) { if ((filename != null) && (filename.length() > 0)) { int dot = filename.lastIndexOf('.'); if ((dot > -1) && (dot < (filename.length()))) { return filename.subs...
assertEquals("foo", getFileNameNoEx("foo")); assertEquals("bar", getFileNameNoEx("bar.txt")); } }
161790867_0
class SelectionManager { public SelectionManager( ApplicationMaster am, Configuration conf, StatusManager statusManager, RequestManager requestManager) { this.am = am; this.conf = conf.getLauncherConfig(); this.statusManager = statusManager; this.requestManager = requestManager; } pu...
Node node1 = new Node("node1", null, ResourceDescriptor.newInstance(200, 200, 2, 3L), ResourceDescriptor.newInstance(0, 0, 0, 0L)); Node node2 = new Node("node2", null, ResourceDescriptor.newInstance(200, 200, 4, 0xFL), ResourceDescriptor.newInstance(0, 0, 0, 0L)); Node node3 = new Node("node3", null, Resou...
161804680_8
class OwnerNameService { public boolean shouldContainOwnerName(IbanAccountReference ibanAccountReference, SpiAccountAccess accountAccess) { SpiAdditionalInformationAccess spiAdditionalInformationAccess = accountAccess.getSpiAdditionalInformationAccess(); if (spiAdditionalInformationAccess != null &...
IbanAccountReference accountReference = new IbanAccountReference(IBAN_FIRST_ACCOUNT, CURRENCY_EUR); SpiAccountAccess accountAccessAvailableAccounts = jsonReader.getObjectFromFile("json/account/additional-account-information/spi-account-access-available-accounts.json", SpiAccountAccess.class); b...
161828855_11
class PuppetTask implements Task { @Override public void execute(Context ctx) throws Exception { PuppetResult result; try { result = getResult(ctx); } catch (Exception ex) { // Determine if task should fail gracefully if (ignoreErrors != null && ign...
MockContext ctx = new MockContext(buildDbQueryConfig()); // Set ignoreErrors = true UtilsTest.injectVariable(task, "action", "bad_action"); UtilsTest.injectVariable(task, "ignoreErrors", true); // Normally, this should throw an exception task.execute(ctx); // M...
162030403_1
class UUIDValidator implements ConstraintValidator<ValidUUID, String> { @Override public boolean isValid(String uuid, ConstraintValidatorContext context) { return pattern.matcher(uuid).matches(); } @Override public void initialize(ValidUUID constraint); private static final UUIDValidator ...
Assertions.assertThat(validator.isValid("3a1757d0", null)).isFalse(); } }
162051749_345
class InfoboxTypeMapper { private InfoboxTypeMapper() { // no instance } private InfoboxTypeMapper(); private static final Map<String, String> loadMapping(final int colIdx); public static LocationType getLocationType(String infoboxName); public static String getConLLType(String infob...
assertNull(getConLLType("doesNotExist")); assertNull(getLocationType("doesNotExist")); assertEquals("LOC", getConLLType("country")); assertEquals(COUNTRY, getLocationType("country")); } }
162158820_2
class SUtil { public static URI toURI(URL url) { if(url==null) return null; URI ret = null; try { ret = url.toURI(); } catch(Exception e) { throw new RuntimeException(e); } return ret; } public static final SecureRandom getSecureRandom(); public static String[] getStringArray(String...
URI uri = SUtil.toURI("tcp-mtp://fe80:0:0:0:8cf:5aff:feeb:f199%eth0:42716"); Assert.assertEquals("tcp-mtp", uri.getScheme()); Assert.assertEquals("[fe80:0:0:0:8cf:5aff:feeb:f199%eth0]", uri.getHost()); Assert.assertEquals(42716, uri.getPort()); } }
162236965_22
class GridBase implements Grid, EventTarget { @Override public void spanRow(int count, int rowIndex, int colIndex) { if (count <= 0 || count > getRowCount() || rowIndex >= getRowCount() || colIndex >= columnCount) { return; } final SpreadsheetCell cell = rows.get(rowIndex).g...
grid.spanRow(0, 0, 0); assertEquals(1, grid.getRows().get(0).get(0).getRowSpan()); grid.spanRow(-1, -1, -1); grid.spanRow(0, -1, 0); grid.spanRow(0, 0, -1); grid.spanRow(-1, 0, 0); grid.spanRow(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); gri...
162272754_69
class RegisterRenterController { @PostMapping(value = ENDPOINT) public ResponseEntity registerRenter(@RequestBody Renter renter) { ResponseEntity responseEntity; final HttpResponse httpResponse = adapter.registerRenter(renter); switch (httpResponse.getStatus()) { case CREATE...
final RegisterRenterController controller = new RegisterRenterController( new MockRegisterRenterInputPort()); Renter renter = new Renter(); renter.setFirstName("John"); renter.setLastName("Doe"); renter.setEmail("john.doe@email.com"); final ResponseEntity<?> r...
162297452_5
class SimpleCassandraVersion implements Comparable<SimpleCassandraVersion> { public static SimpleCassandraVersion create(String version) { String stripped = SNAPSHOT.matcher(version).replaceFirst(""); Matcher matcher = pattern.matcher(stripped); if (!matcher.matches()) throw...
SimpleCassandraVersion alpha = SimpleCassandraVersion.create("4.0-alpha5-SNAPSHOT"); assertThat(alpha.major).isEqualTo(4); assertThat(alpha.minor).isEqualTo(0); assertThat(alpha.patch).isEqualTo(0); } }
162325477_17
class StaticHexRegexDataHandler extends HexRegexDataHandler { @Override public Optional<byte[]> handle(final byte[] data) { final String encoded = BaseEncoding.base16().encode(data); final boolean matches = hexRegex.matcher(encoded).matches(); if (matches) { return Optional...
final Optional<byte[]> handleResult = dataHandler.handle(DEFAULT_TEST_DATA); assertThat(handleResult, is(optionalWithValue(equalTo(base16().decode(RESPONSE_DATA))))); } }
162388276_15
class GenericUtils { public static <T> Class<T> ancestorGenericClass(Class<T> clazz) { ParameterizedType genericSuperclass = firstParameterizedType(clazz); Class<T> genericClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0]; return genericClass; } public static Class<T...
Assertions.assertThrows(RuntimeException.class, () -> GenericUtils.ancestorGenericClass(AAA.class)); Assertions.assertSame(LinkedList.class, GenericUtils.ancestorGenericClass(BBB.class)); Assertions.assertSame(LinkedList.class, GenericUtils.ancestorGenericClass(CCC.class)); Assertions.as...
162389327_6
class FootballPlayerFacadeREST extends AbstractFacade<FootballPlayer> { @PUT @Path("{id}") @Consumes({MediaType.APPLICATION_JSON}) @Transactional(Transactional.TxType.REQUIRES_NEW) public void edit( @PathParam("id") Integer id, FootballPlayer entity) { super.edit(entity); } ...
System.out.println("edit"); FootballPlayer player = target.path("24").request().get( new GenericTypeFootballPlayerImpl()); player.setPrice(new BigInteger("150")); Response response = target.path("24").request().put(Entity. entity(player, ...
162538669_4
class MetaUtil { public static DefaultRequest convertOldProtocolHeaderToRequest(RequestHeader header, DefaultRequest request) { request.setRemoteAppkey(header.getClientAppkey()); request.setClientIp(header.getClientIp()); TransportTraceInfo transportTraceInfo = new TransportTraceInfo(header...
DefaultRequest request = new DefaultRequest(); request.setServiceInterface(Echo.Iface.class); MetaUtil.convertOldProtocolHeaderToRequest(requestHeader, request); Assert.assertEquals(request.getRemoteAppkey(), "com.sankuai.mock2"); Assert.assertEquals(request.getClientIp(), "127.0...
162657716_191
class JsonRpc2_0Rx { public Observable<PlatonBlock> replayBlocksObservable( DefaultBlockParameter startBlock, DefaultBlockParameter endBlock, boolean fullTransactionObjects) { return replayBlocksObservable(startBlock, endBlock, fullTransactionObjects, true); } public JsonR...
List<PlatonBlock> ethBlocks = Arrays.asList(createBlock(0), createBlock(1), createBlock(2)); OngoingStubbing<PlatonBlock> stubbing = when(web3jService.send(any(Request.class), eq(PlatonBlock.class))); for (PlatonBlock ethBlock : ethBlocks) { stubbing = stubbing.then...