src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
VehicleImpl extends AbstractVehicle { @Override public Location getStartLocation() { return startLocation; } private VehicleImpl(Builder builder); static Vehicle copyOf(Vehicle vehicle); static NoVehicle createNoVehicle(); @Override String toString(); @Override double getEarliestDeparture(); @Override double getLatest...
@Test public void whenVehicleIsBuiltWithCoord_itShouldHvTheCorrectCoord() { Vehicle v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(1, 2)).build(); assertEquals(1.0, v.getStartLocation().getCoordinate().getX(), 0.01); assertEquals(2.0, v.getStartLocation().getCoordinate().getY(), 0.01); }...
VehicleImpl extends AbstractVehicle { @Override public double getEarliestDeparture() { return earliestDeparture; } private VehicleImpl(Builder builder); static Vehicle copyOf(Vehicle vehicle); static NoVehicle createNoVehicle(); @Override String toString(); @Override double getEarliestDeparture(); @Override double get...
@Test public void whenVehicleIsBuiltAndEarliestStartIsNotSet_itShouldSetTheDefaultOfZero() { Vehicle v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(1, 2)).build(); assertEquals(0.0, v.getEarliestDeparture(), 0.01); } @Test public void whenVehicleIsBuiltAndEarliestStartSet_itShouldBeSetCo...
VehicleImpl extends AbstractVehicle { @Override public double getLatestArrival() { return latestArrival; } private VehicleImpl(Builder builder); static Vehicle copyOf(Vehicle vehicle); static NoVehicle createNoVehicle(); @Override String toString(); @Override double getEarliestDeparture(); @Override double getLatestAr...
@Test public void whenVehicleIsBuiltAndLatestArrivalIsNotSet_itShouldSetDefaultOfDoubleMaxValue() { Vehicle v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(1, 2)).build(); assertEquals(Double.MAX_VALUE, v.getLatestArrival(), 0.01); } @Test public void whenVehicleIsBuiltAndLatestArrivalIsS...
UserController { @RequestMapping(value = "/query/{key}", method = RequestMethod.GET) @PostAuthorize("hasRole('ADMIN') or (returnObject.username == principal.username)") @ApiOperation(value = "按某属性查询用户", notes = "属性可以是id或username或email或手机号", response = UserDO.class, authorizations = {@Authorization("登录权限")}) @ApiRespons...
@Test public void findByKey() throws Exception { UserDO user = userService.findById(1L); System.out.println(user); }
UserController { @ResponseStatus(HttpStatus.CREATED) @RequestMapping(method = RequestMethod.POST) @ApiOperation(value = "创建用户,为用户发送验证邮件,等待用户激活,若24小时内未激活需要重新注册", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 409, message = "用户名已存在"), @ApiResponse(code = 400, message = "用户属性校验失败") }) public void crea...
@Test public void createUser() throws Exception { BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String password = passwordEncoder.encode("user1"); System.out.println(password); }
UserController { @RequestMapping(value = "/{id}/avatar", method = RequestMethod.GET) @ApiOperation(value = "获取用户的头像图片", response = Byte.class) @ApiResponses(value = { @ApiResponse(code = 404, message = "文件不存在"), @ApiResponse(code = 400, message = "文件传输失败") }) public void getUserAvatar(@PathVariable("id") Long id, HttpS...
@Test public void getUserAvatar() throws Exception { System.out.println(UserMode.valueOf("USERNAME")); }
UserController { @RequestMapping(value = "/{id}/activation", method = RequestMethod.GET) @ApiOperation(value = "用户激活,前置条件是用户已注册且在24小时内", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 401, message = "未注册或超时或激活码错误") }) public void activate(@PathVariable("id") @ApiParam(value = "用户Id", required = true...
@Test public void activate() throws Exception { }
UserController { @RequestMapping(method = RequestMethod.PUT) @PreAuthorize("#user.username == principal.username or hasRole('ADMIN')") @ApiOperation(value = "更新用户信息", response = Void.class, authorizations = {@Authorization("登录权限")}) @ApiResponses(value = { @ApiResponse(code = 401, message = "未登录"), @ApiResponse(code = ...
@Test public void updateUser() throws Exception { }
UserController { @RequestMapping(value = "/{key}/password/reset_validation", method = RequestMethod.GET) @ApiOperation(value = "发送忘记密码的邮箱验证", notes = "属性可以是id,sername或email或手机号", response = UserDO.class) public void forgetPassword(@PathVariable("key") @ApiParam(value = "关键字", required = true) String key, @RequestParam(...
@Test public void forgetPassword() throws Exception { }
UserController { @RequestMapping(value = "/{id}/password", method = RequestMethod.PUT) @ApiOperation(value = "忘记密码后可以修改密码") public void resetPassword(@PathVariable("id") Long id, @RequestParam("forgetPasswordCode") @ApiParam(value = "验证码", required = true) String forgetPasswordCode, @RequestParam("password") @ApiParam(...
@Test public void resetPassword() throws Exception { }
UserController { @RequestMapping(value = "/{username}/duplication", method = RequestMethod.GET) @ApiOperation(value = "查询用户名是否重复", response = Boolean.class) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) public boolean isUsernameDuplicated(@PathVariable("username") String username) { if (service.fin...
@Test public void isUsernameDuplicated() throws Exception { }
UserController { @RequestMapping(method = RequestMethod.GET) @PreAuthorize("hasRole('ADMIN')") @ApiOperation(value = "分页查询用户信息", response = PageInfo.class, authorizations = {@Authorization("登录权限")}) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) public PageInfo<UserDO> findAllUsers(@RequestParam("pa...
@Test public void findAllUsers() throws Exception { }
LatexEscapeTool { public String escape(final String input) { if (input == null) { return null; } String output = input; output = output.replace("\\", "\\textbackslash "); output = output.replace("€", "\\euro "); output = output.replace("<", "\\textless "); output = output.replace(">", "\\textgreater "); output = output...
@Test public void testEscapingOfNull() { assertThat(tool.escape(null), is(nullValue())); } @Test public void testEscaping() { assertThat(tool.escape("\\"), is("\\textbackslash ")); assertThat(tool.escape("<"), is("\\textless ")); assertThat(tool.escape(">"), is("\\textgreater ")); assertThat(tool.escape("§"), is("\\S "...
LatexContext { public LatexContext add(final String key, final Object value) { requireNonNull(key, "key must not be null"); context.put(key, value); return this; } LatexContext add(final String key, final Object value); Set<String> keys(); Map<String, Object> asMap(); }
@Test(expected = NullPointerException.class) public void testNullKey() { new LatexContext().add(null, null); fail(); }
LatexTemplate { public final String populateFrom(final LatexContext context) { requireNonNull(context); final VelocityEngine velocityEngine = initializeEngine(); final VelocityContext velocityContext = prepareContext(context); return evaluateTemplate(velocityContext, velocityEngine); } LatexTemplate(final String templa...
@Test public void processTemplate() { LatexTemplate template = new LatexTemplate("${keyToReplace}"); LatexContext context = new LatexContext(); context.add("keyToReplace", "value"); String result = template.populateFrom(context); assertThat(result, is("value")); } @Test(expected = NullPointerException.class) public voi...
AggregationExample { public Iterator<DBObject> simpleAggregation() { BasicDBObjectBuilder builder = new BasicDBObjectBuilder(); builder.push("$group"); builder.add("_id", "$manufacturer"); builder.push("num_products"); builder.add("$sum", 1); builder.pop(); builder.pop(); return col.aggregate(builder.get()).results().i...
@Test public void simpleAggregation() throws UnknownHostException { List<String> vals = generateRandomAlphaNumericValues(); for (int i = 0; i < 100; i++) { if (i < 50) collection.insert(new BasicDBObject("manufacturer", vals.get(0))); else if(i < 75 ) collection.insert(new BasicDBObject("manufacturer", vals.get(1))); e...
AggregationExample { public Iterator<DBObject> sort() { BasicDBObjectBuilder match = buildMatchDBObject(); BasicDBObjectBuilder group = new BasicDBObjectBuilder(); group.push("$group"); group.add("_id", "$city"); group.push("population"); group.add("$sum", "$pop"); group.pop(); group.pop(); BasicDBObjectBuilder project...
@Test public void sortTest() { DBCollection zipsCollection = client.getDB("states").getCollection("zips"); agg.setCollection(zipsCollection); Iterator<DBObject> iter = agg.sort(); while(iter.hasNext()) { System.out.println(iter.next()); } }
AggregationExample { public Iterator<DBObject> limitAndSkip() { BasicDBObjectBuilder match = buildMatchDBObject(); BasicDBObjectBuilder group = new BasicDBObjectBuilder(); group.push("$group"); group.add("_id", "$city"); group.push("population"); group.add("$sum", "$pop"); group.pop(); group.pop(); BasicDBObjectBuilder...
@Test public void limitAndSkipTest() { DBCollection zipsCollection = client.getDB("states").getCollection("zips"); agg.setCollection(zipsCollection); Iterator<DBObject> iter = agg.limitAndSkip(); while(iter.hasNext()) { System.out.println(iter.next()); } }
AggregationExample { public Iterator<DBObject> unwind() { BasicDBObject unwind = new BasicDBObject("$unwind", "$tags"); BasicDBObjectBuilder group = new BasicDBObjectBuilder(); group.push("$group"); group.add("_id", "$tags"); group.push("count"); group.add("$sum", 1); group.pop(); group.pop(); BasicDBObjectBuilder sort...
@Test public void unwindTest() { DBCollection postsCollection = client.getDB("blog").getCollection("posts"); agg.setCollection(postsCollection); Iterator<DBObject> iter = agg.unwind(); while(iter.hasNext()) { System.out.println(iter.next()); } }
AggregationExample { public Iterator<DBObject> doubleUnwind() { BasicDBObject unwindSizes = new BasicDBObject("$unwind", "$sizes"); BasicDBObject unwindColors = new BasicDBObject("$unwind", "$colors"); BasicDBObjectBuilder group = new BasicDBObjectBuilder(); group.push("$group"); group.push("_id"); group.add("size", "$...
@Test public void doubleUnwindTest() { DBCollection inventoryCollection = db.getCollection("inventory"); agg.setCollection(inventoryCollection); inventoryCollection.insert(new BasicDBObject("name","Polo Shirt").append("sizes",new String[] {"Small", "Medium","Large"}).append("colors", new String[] {"navy","white","oragn...
AggregationExample { public Iterator<DBObject> compoundAggregation() { BasicDBObjectBuilder builder = new BasicDBObjectBuilder(); builder.push("$group"); builder.push("_id"); builder.add("manufacturer", "$manufacturer"); builder.add("category", "$category"); builder.pop(); builder.push("num_products"); builder.add("$su...
@Test public void compoundGrouping() { List<String> manufacturers = generateRandomAlphaNumericValues(); List<String> categories = generateRandomAlphaNumericValues(); for (int i = 0; i < 100; i++) { if (i < 50) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(0)).append("category", categories.get(Ra...
AggregationExample { public Iterator<DBObject> sumPrices() { BasicDBObjectBuilder builder = new BasicDBObjectBuilder(); builder.push("$group"); builder.add("_id", "$manufacturer"); builder.push("sum_prices"); builder.add("$sum", "$price"); builder.pop(); builder.pop(); return col.aggregate(builder.get()).results().iter...
@Test public void usingSumTest() { List<String> manufacturers = generateRandomAlphaNumericValues(); List<Double> prices = generateRandomDoubleValues(); for (int i = 0; i < 100; i++) { if (i < 50) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(0)).append("price", prices.get(RandomUtils.nextInt(pri...
AggregationExample { public Iterator<DBObject> averagePrices() { BasicDBObjectBuilder builder = new BasicDBObjectBuilder(); builder.push("$group"); builder.add("_id", "$category"); builder.push("sum_prices"); builder.add("$avg", "$price"); builder.pop(); builder.pop(); return col.aggregate(builder.get()).results().iter...
@Test public void usingAvgTest() { List<String> categories = generateRandomAlphaNumericValues(); List<Double> prices = generateRandomDoubleValues(); for (int i = 0; i < 100; i++) { if (i < 50) collection.insert(new BasicDBObject("category", categories.get(0)).append("price", prices.get(RandomUtils.nextInt(prices.size()...
AggregationExample { public Iterator<DBObject> addToSet() { BasicDBObjectBuilder builder = new BasicDBObjectBuilder(); builder.push("$group"); builder.push("_id"); builder.add("maker", "$manufacturer"); builder.pop(); builder.push("categories"); builder.add("$addToSet", "$category"); builder.pop(); builder.pop(); retur...
@Test public void addToSetTest() { List<String> manufacturers = generateRandomAlphaNumericValues(); List<String> categories = generateRandomAlphaNumericValues(); for (int i = 0; i < 100; i++) { if (i < 50) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(0)).append("category", categories.get(Random...
AggregationExample { public Iterator<DBObject> push() { BasicDBObjectBuilder builder = new BasicDBObjectBuilder(); builder.push("$group"); builder.push("_id"); builder.add("maker", "$manufacturer"); builder.pop(); builder.push("categories"); builder.add("$push", "$category"); builder.pop(); builder.pop(); return col.ag...
@Test public void pushTest() { List<String> manufacturers = generateRandomAlphaNumericValues(); List<String> categories = generateRandomAlphaNumericValues(); for (int i = 0; i < 100; i++) { if (i < 50) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(0)).append("category", categories.get(RandomUtil...
AggregationExample { public Iterator<DBObject> maxPrice() { BasicDBObjectBuilder builder = new BasicDBObjectBuilder(); builder.push("$group"); builder.push("_id"); builder.add("maker", "$manufacturer"); builder.pop(); builder.push("maxprice"); builder.add("$max", "$price"); builder.pop(); builder.pop(); return col.aggr...
@Test public void maxAndMinTest() { List<String> manufacturers = generateRandomAlphaNumericValues(); List<Double> prices = generateRandomDoubleValues(); for (int i = 0; i < 100; i++) { if (i < 50) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(0)).append("price", prices.get(RandomUtils.nextInt(pr...
AggregationExample { public Iterator<DBObject> doubleGroupStages() { BasicDBObjectBuilder group_1 = new BasicDBObjectBuilder(); group_1.push("$group"); group_1.push("_id"); group_1.add("class_id", "$class_id"); group_1.add("student_id", "$student_id"); group_1.pop(); group_1.push("average"); group_1.add("$avg", "$score...
@Test public void doubleGroupStages() { DBCollection grades = db.getCollection("grades"); agg.setCollection(grades); int[] class_id = {1,2,3,4,5}; int[] student_id = {100,101,102,103,104,105}; for(int cls = 0; cls < class_id.length; cls++) { for(int student = 0; student < student_id.length; student++) { grades.insert(n...
AggregationExample { public Iterator<DBObject> project() { BasicDBObjectBuilder builder = new BasicDBObjectBuilder(); builder.push("$project"); builder.add("_id", 0); builder.push("maker"); builder.add("$toLower", "$manufacturer"); builder.pop(); builder.push("details"); builder.add("category", "$category"); builder.pu...
@Test public void projectTest() { collection.insert(new BasicDBObject("manufacturer", "Apple").append("price", 2000.01).append("category", "Lap Top").append("name", "MacBookAir")); Iterator<DBObject> iter = agg.project(); while(iter.hasNext()) { System.out.println(iter.next()); } collection.drop(); }
AggregationExample { public Iterator<DBObject> match() { BasicDBObjectBuilder match = buildMatchDBObject(); BasicDBObjectBuilder group = new BasicDBObjectBuilder(); group.push("$group"); group.add("_id", "$city"); group.push("population"); group.add("$sum", "$pop"); group.pop(); group.push("zip_codes"); group.add("$add...
@Test public void matchTest() { DBCollection zipsCollection = client.getDB("states").getCollection("zips"); agg.setCollection(zipsCollection); Iterator<DBObject> iter = agg.match(); while(iter.hasNext()) { System.out.println(iter.next()); } }
Exec { static int parseExitCode(ApiClient client, InputStream inputStream) { try { Type returnType = new TypeToken<V1Status>() {}.getType(); String body; try (final Reader reader = new InputStreamReader(inputStream)) { body = CharStreams.toString(reader); } V1Status status = client.getJSON().deserialize(body, returnTyp...
@Test public void testExit0() { InputStream inputStream = new ByteArrayInputStream(OUTPUT_EXIT0.getBytes(StandardCharsets.UTF_8)); int exitCode = Exec.parseExitCode(client, inputStream); assertEquals(0, exitCode); } @Test public void testExit1() { InputStream inputStream = new ByteArrayInputStream(OUTPUT_EXIT1.getBytes...
DefaultDelayingQueue extends DefaultWorkQueue<T> implements DelayingQueue<T> { public void addAfter(T item, Duration duration) { if (super.isShuttingDown()) { return; } if (duration.isZero()) { super.add(item); return; } WaitForEntry<T> entry = new WaitForEntry<>(item, duration.addTo(Instant.now())); this.waitingForAdd...
@Test public void testCopyShifting() throws Exception { DefaultDelayingQueue<String> queue = new DefaultDelayingQueue<>(); final String first = "foo"; final String second = "bar"; final String third = "baz"; queue.addAfter(first, Duration.ofSeconds(1)); queue.addAfter(second, Duration.ofMillis(500)); queue.addAfter(thi...
MaxOfRateLimiter implements RateLimiter<T> { public MaxOfRateLimiter(List<RateLimiter<T>> rateLimiters) { this.rateLimiters = rateLimiters; } MaxOfRateLimiter(List<RateLimiter<T>> rateLimiters); @SafeVarargs @SuppressWarnings("varargs") MaxOfRateLimiter(RateLimiter<T>... rateLimiters); @Override Duration when(T item);...
@Test public void testMaxOfRateLimiter() { RateLimiter<String> rateLimiter = new MaxOfRateLimiter<>( new ItemFastSlowRateLimiter<>(Duration.ofMillis(5), Duration.ofSeconds(3), 3), new ItemExponentialFailureRateLimiter<>(Duration.ofMillis(1), Duration.ofSeconds(1))); assertEquals(Duration.ofMillis(5), rateLimiter.when("...
MaxOfRateLimiter implements RateLimiter<T> { @Override public Duration when(T item) { Duration max = Duration.ZERO; for (RateLimiter<T> r : rateLimiters) { Duration current = r.when(item); if (current.compareTo(max) > 0) { max = current; } } return max; } MaxOfRateLimiter(List<RateLimiter<T>> rateLimiters); @SafeVararg...
@Test public void testDefaultRateLimiter() { RateLimiter<String> rateLimiter = new DefaultControllerRateLimiter<>(); assertEquals(Duration.ofMillis(5), rateLimiter.when("one")); assertEquals(Duration.ofMillis(10), rateLimiter.when("one")); assertEquals(Duration.ofMillis(20), rateLimiter.when("one")); for (int i = 0; i ...
BucketRateLimiter implements RateLimiter<T> { @Override public Duration when(T item) { long overdraftNanos = bucket.consumeIgnoringRateLimits(1); return Duration.ofNanos(overdraftNanos); } BucketRateLimiter(long capacity, long tokensGeneratedInPeriod, Duration period); @Override Duration when(T item); @Override void fo...
@Test public void testBucketRateLimiterBasic() { RateLimiter<String> rateLimiter = new BucketRateLimiter<>(2, 1, Duration.ofMinutes(10)); assertEquals(Duration.ZERO, rateLimiter.when("one")); assertEquals(Duration.ZERO, rateLimiter.when("one")); Duration waitDuration = rateLimiter.when("one"); Duration expectDuration =...
ItemExponentialFailureRateLimiter implements RateLimiter<T> { public ItemExponentialFailureRateLimiter(Duration baseDelay, Duration maxDelay) { this.baseDelay = baseDelay; this.maxDelay = maxDelay; failures = AtomicLongMap.create(); } ItemExponentialFailureRateLimiter(Duration baseDelay, Duration maxDelay); @Override D...
@Test public void testItemExponentialFailureRateLimiter() { RateLimiter<String> rateLimiter = new ItemExponentialFailureRateLimiter<>(Duration.ofMillis(1), Duration.ofSeconds(1)); assertEquals(Duration.ofMillis(1), rateLimiter.when("one")); assertEquals(Duration.ofMillis(2), rateLimiter.when("one")); assertEquals(Durat...
ItemExponentialFailureRateLimiter implements RateLimiter<T> { @Override public Duration when(T item) { long exp = failures.getAndIncrement(item); long d = maxDelay.toMillis() >> exp; return d > baseDelay.toMillis() ? baseDelay.multipliedBy(1 << exp) : maxDelay; } ItemExponentialFailureRateLimiter(Duration baseDelay, Du...
@Test public void testItemExponentialFailureRateLimiterOverFlow() { RateLimiter<String> rateLimiter = new ItemExponentialFailureRateLimiter<>(Duration.ofMillis(1), Duration.ofSeconds(1000)); for (int i = 0; i < 5; i++) { rateLimiter.when("one"); } assertEquals(Duration.ofMillis(32), rateLimiter.when("one")); for (int i...
ItemFastSlowRateLimiter implements RateLimiter<T> { @Override public Duration when(T item) { long attempts = failures.incrementAndGet(item); if (attempts <= maxFastAttempts) { return fastDelay; } return slowDelay; } ItemFastSlowRateLimiter(Duration fastDelay, Duration slowDelay, int maxFastAttempts); @Override Duration...
@Test public void testNegativeOrZeroAttempts() { RateLimiter<String> rateLimiter = new ItemFastSlowRateLimiter<>(Duration.ofMillis(5), Duration.ofSeconds(10), -1); assertEquals(Duration.ofSeconds(10), rateLimiter.when("one")); assertEquals(Duration.ofSeconds(10), rateLimiter.when("one")); assertEquals(Duration.ofSecond...
Yaml { public static Object load(String content) throws IOException { return load(new StringReader(content)); } static Object load(String content); static Object load(File f); static Object load(Reader reader); static T loadAs(String content, Class<T> clazz); static T loadAs(File f, Class<T> clazz); static T loadAs(Re...
@Test public void testLoad() { for (int i = 0; i < kinds.length; i++) { String className = classNames[i]; try { Object obj = Yaml.load( new StringReader(input.replace("XXXX", kinds[i]).replace("YYYY", apiVersions[i]))); Method m = obj.getClass().getMethod("getMetadata"); V1ObjectMeta metadata = (V1ObjectMeta) m.invoke(...
LeaderElectingController implements Controller { public LeaderElectingController(LeaderElector leaderElector, Controller delegateController) { this.delegateController = delegateController; this.leaderElector = leaderElector; } LeaderElectingController(LeaderElector leaderElector, Controller delegateController); @Overri...
@Test public void testLeaderElectingController() throws ApiException { AtomicReference<LeaderElectionRecord> record = new AtomicReference<>(); record.set(new LeaderElectionRecord()); when(mockLock.identity()).thenReturn("foo"); doAnswer(invocationOnMock -> record.get()).when(mockLock).get(); doAnswer( invocationOnMock ...
DefaultControllerBuilder { public Controller build() throws IllegalStateException { if (this.reconciler == null) { throw new IllegalStateException("Missing reconciler when building controller."); } DefaultController controller = new DefaultController( this.reconciler, this.workQueue, this.readyFuncs.stream().toArray(Su...
@Test(expected = IllegalStateException.class) public void testDummyBuildShouldFail() { ControllerBuilder.defaultBuilder(informerFactory).build(); }
KubectlDrain extends KubectlCordon { @Override public V1Node execute() throws KubectlException { try { return doDrain(); } catch (ApiException | IOException ex) { throw new KubectlException(ex); } } KubectlDrain(); KubectlDrain gracePeriod(int gracePeriodSeconds); KubectlDrain force(); KubectlDrain ignoreDaemonSets(); ...
@Test public void testDrainNodeNoPods() throws KubectlException, IOException { wireMockRule.stubFor( patch(urlPathEqualTo("/api/v1/nodes/node1")) .willReturn( aResponse().withStatus(200).withBody("{\"metadata\": { \"name\": \"node1\" } }"))); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/pods")) .withQueryParam("fi...
Yaml { public static List<Object> loadAll(String content) throws IOException { return loadAll(new StringReader(content)); } static Object load(String content); static Object load(File f); static Object load(Reader reader); static T loadAs(String content, Class<T> clazz); static T loadAs(File f, Class<T> clazz); static...
@Test public void testLoadAll() throws IOException { StringBuilder sb = new StringBuilder(); for (int i = 0; i < kinds.length; i++) { sb.append(input.replace("XXXX", kinds[i]).replace("YYYY", apiVersions[i])); sb.append("\n---\n"); } List<Object> list = null; list = (List<Object>) Yaml.loadAll(sb.toString()); for (int ...
Yaml { public static <T> T loadAs(String content, Class<T> clazz) { return getSnakeYaml().loadAs(new StringReader(content), clazz); } static Object load(String content); static Object load(File f); static Object load(Reader reader); static T loadAs(String content, Class<T> clazz); static T loadAs(File f, Class<T> claz...
@Test public void testLoadIntOrString() { try { String strInput = "targetPort: test"; String intInput = "targetPort: 1"; V1ServicePort stringPort = Yaml.loadAs(strInput, V1ServicePort.class); V1ServicePort intPort = Yaml.loadAs(intInput, V1ServicePort.class); assertFalse( "Target port for 'stringPort' was parsed to an ...
AccessTokenAuthentication implements Authentication { @Override public void provide(ApiClient client) { client.setApiKeyPrefix("Bearer"); client.setApiKey(token); } AccessTokenAuthentication(final String token); @Override void provide(ApiClient client); }
@Test public void testTokenProvided() { final ApiClient client = new ApiClient(); new AccessTokenAuthentication("token").provide(client); assertThat(getApiKeyAuthFromClient(client).getApiKeyPrefix(), is("Bearer")); assertThat(getApiKeyAuthFromClient(client).getApiKey(), is("token")); }
ClientCertificateAuthentication implements Authentication { @Override public void provide(ApiClient client) { String dataString = new String(key); String algo = ""; if (dataString.indexOf("BEGIN EC PRIVATE KEY") != -1) { algo = "EC"; } if (dataString.indexOf("BEGIN RSA PRIVATE KEY") != -1) { algo = "RSA"; } try { final...
@Test public void testValidCertificates() throws Exception { final ApiClient client = new ApiClient(); final byte[] certificate = Files.readAllBytes(Paths.get(CLIENT_CERT_PATH)); final byte[] key = Files.readAllBytes(Paths.get(CLIENT_KEY_PATH)); new ClientCertificateAuthentication(certificate, key).provide(client); } @...
UsernamePasswordAuthentication implements Authentication { @Override public void provide(ApiClient client) { final String usernameAndPassword = username + ":" + password; client.setApiKeyPrefix("Basic"); client.setApiKey( ByteString.of(usernameAndPassword.getBytes(StandardCharsets.ISO_8859_1)).base64()); } UsernamePass...
@Test public void testUsernamePasswordProvided() { final ApiClient client = new ApiClient(); new UsernamePasswordAuthentication(USERNAME, PASSWORD).provide(client); assertThat(getApiKeyAuthFromClient(client).getApiKeyPrefix(), is("Basic")); assertThat( getApiKeyAuthFromClient(client).getApiKey(), is(ByteString.of(USERN...
Labels { public static void addLabels(KubernetesObject kubernetesObject, String label, String value) { Map<String, String> mergingLabels = new HashMap<>(); mergingLabels.put(label, value); addLabels(kubernetesObject, mergingLabels); } static void addLabels(KubernetesObject kubernetesObject, String label, String value)...
@Test public void testAddLabels() { V1Pod pod = new V1Pod().metadata(new V1ObjectMeta()); Labels.addLabels(pod, "foo", "bar"); assertEquals(pod.getMetadata().getLabels().get("foo"), "bar"); } @Test public void testAddMultipleLabels() { V1Pod pod = new V1Pod().metadata(new V1ObjectMeta()); Map<String, String> newLabels ...
Config { public static ApiClient defaultClient() throws IOException { return ClientBuilder.standard().build(); } static ApiClient fromCluster(); static ApiClient fromUrl(String url); static ApiClient fromUrl(String url, boolean validateSSL); static ApiClient fromUserPassword(String url, String user, String password); ...
@Test public void testDefaultClientNothingPresent() { environmentVariables.set("HOME", "/non-existent"); try { ApiClient client = Config.defaultClient(); assertEquals("http: } catch (IOException ex) { fail("Unexpected exception: " + ex); } } @Test public void testDefaultClientHomeDir() { try { environmentVariables.set(...
Watch implements Watchable<T>, Closeable { protected Response<T> parseLine(String line) throws IOException { if (!isStatus(line)) { return json.deserialize(line, watchType); } Type statusType = new TypeToken<Response<V1Status>>() {}.getType(); Response<V1Status> status = json.deserialize(line, statusType); return new R...
@Test public void testWatchEnd() throws IOException { JSON json = new JSON(); Watch<V1ConfigMap> watch = new Watch<V1ConfigMap>( json, null, new TypeToken<Watch.Response<V1ConfigMap>>() {}.getType(), null); JsonObject metadata = new JsonObject(); metadata.addProperty("name", "foo"); metadata.addProperty("namespace", "b...
GenericKubernetesApi { public KubernetesApiResponse<ApiType> delete(String name) { return delete(name, new DeleteOptions()); } GenericKubernetesApi( Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass, String apiGroup, String apiVersion, String resourcePlural); GenericKuberne...
@Test public void deleteNamespacedJobReturningStatus() { V1Status status = new V1Status().kind("Status").code(200).message("good!"); stubFor( delete(urlEqualTo("/apis/batch/v1/namespaces/default/jobs/foo1")) .willReturn(aResponse().withStatus(200).withBody(new Gson().toJson(status)))); KubernetesApiResponse<V1Job> dele...
GenericKubernetesApi { public KubernetesApiResponse<ApiType> create(ApiType object) { return create(object, new CreateOptions()); } GenericKubernetesApi( Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass, String apiGroup, String apiVersion, String resourcePlural); GenericKu...
@Test public void createNamespacedJobReturningObject() { V1Job foo1 = new V1Job().kind("Job").metadata(new V1ObjectMeta().namespace("default").name("foo1")); stubFor( post(urlEqualTo("/apis/batch/v1/namespaces/default/jobs")) .willReturn(aResponse().withStatus(200).withBody(new Gson().toJson(foo1)))); KubernetesApiResp...
GenericKubernetesApi { public KubernetesApiResponse<ApiType> update(ApiType object) { return update(object, new UpdateOptions()); } GenericKubernetesApi( Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass, String apiGroup, String apiVersion, String resourcePlural); GenericKu...
@Test public void updateNamespacedJobReturningObject() { V1Job foo1 = new V1Job().kind("Job").metadata(new V1ObjectMeta().namespace("default").name("foo1")); stubFor( put(urlEqualTo("/apis/batch/v1/namespaces/default/jobs/foo1")) .willReturn(aResponse().withStatus(200).withBody(new Gson().toJson(foo1)))); KubernetesApi...
GenericKubernetesApi { public KubernetesApiResponse<ApiType> patch(String name, String patchType, V1Patch patch) { return patch(name, patchType, patch, new PatchOptions()); } GenericKubernetesApi( Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass, String apiGroup, String apiVersio...
@Test public void patchNamespacedJobReturningObject() { V1Patch v1Patch = new V1Patch("{}"); V1Job foo1 = new V1Job().kind("Job").metadata(new V1ObjectMeta().namespace("default").name("foo1")); stubFor( patch(urlEqualTo("/apis/batch/v1/namespaces/default/jobs/foo1")) .withHeader("Content-Type", containing(V1Patch.PATCH...
GenericKubernetesApi { public KubernetesApiResponse<ApiType> get(String name) { return get(name, new GetOptions()); } GenericKubernetesApi( Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass, String apiGroup, String apiVersion, String resourcePlural); GenericKubernetesApi( ...
@Test public void testReadTimeoutShouldThrowException() { ApiClient apiClient = new ClientBuilder().setBasePath("http: apiClient.setHttpClient( apiClient .getHttpClient() .newBuilder() .readTimeout(1, TimeUnit.MILLISECONDS) .build()); stubFor( get(urlEqualTo("/apis/batch/v1/namespaces/foo/jobs/test")) .willReturn(aResp...
FilePersister implements ConfigPersister { public void save( ArrayList<Object> contexts, ArrayList<Object> clusters, ArrayList<Object> users, Object preferences, String currentContext) throws IOException { HashMap<String, Object> config = new HashMap<>(); config.put("apiVersion", "v1"); config.put("kind", "Config"); co...
@Test public void testPersistence() throws IOException { File file = folder.newFile("testconfig"); FilePersister fp = new FilePersister(file.getPath()); KubeConfig config = KubeConfig.loadKubeConfig(new FileReader(KUBECONFIG_FILE_PATH)); fp.save( config.getContexts(), config.getClusters(), config.getUsers(), config.get...
Version { public VersionInfo getVersion() throws ApiException, IOException { Call call = versionApi.getCodeCall(null); Response response = null; try { response = call.execute(); } catch (IOException e) { throw new ApiException(e); } if (!response.isSuccessful()) { throw new ApiException(response.code(), "Version reques...
@Test public void testUrl() throws InterruptedException, IOException, ApiException { wireMockRule.stubFor( get(urlPathEqualTo("/version/")) .willReturn( aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{}"))); Version versionUtil = new Version(client); try { VersionInfo versionInf...
PortForward { public PortForwardResult forward(V1Pod pod, List<Integer> ports) throws ApiException, IOException { return forward(pod.getMetadata().getNamespace(), pod.getMetadata().getName(), ports); } PortForward(); PortForward(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Po...
@Test public void testUrl() throws IOException, ApiException, InterruptedException { PortForward forward = new PortForward(client); V1Pod pod = new V1Pod().metadata(new V1ObjectMeta().name(podName).namespace(namespace)); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "...
Discovery { public Set<APIResource> groupResourcesByName( String group, List<String> versions, String preferredVersion, V1APIResourceList resourceList) { Set<APIResource> resources = resourceList.getResources().stream() .filter(r -> !getSubResourceNameIfPossible(r.getName()).isPresent()) .map( r -> new APIResource( gro...
@Test public void testGroupResourcesByName() { Discovery discovery = new Discovery(apiClient); Set<Discovery.APIResource> discoveredResources = discovery.groupResourcesByName( "foo", Arrays.asList("v1", "v2"), "v1", new V1APIResourceList() .resources( Arrays.asList( new V1APIResource() .name("meows") .kind("Meow") .nam...
ReflectorRunnable implements Runnable { public void stop() { isActive.set(false); } ReflectorRunnable( Class<ApiType> apiTypeClass, ListerWatcher listerWatcher, DeltaFIFO store); ReflectorRunnable( Class<ApiType> apiTypeClass, ListerWatcher listerWatcher, DeltaFIFO store, BiConsumer<Class...
@Test public void testReflectorRunOnce() throws InterruptedException, ApiException { String mockResourceVersion = "1000"; when(listerWatcher.list(any())) .thenReturn( new V1PodList().metadata(new V1ListMeta().resourceVersion(mockResourceVersion))); when(listerWatcher.watch(any())) .then( (v) -> { Thread.sleep(999999L);...
Controller { public void stop() { synchronized (this) { if (reflectorFuture != null) { reflector.stop(); reflectorFuture.cancel(true); } } reflectExecutor.shutdown(); } Controller( Class<ApiType> apiTypeClass, DeltaFIFO queue, ListerWatcher<ApiType, ApiListType> listerWatcher, Consumer<Deque<Mut...
@Test public void testControllerProcessDeltas() throws InterruptedException { AtomicInteger receivingDeltasCount = new AtomicInteger(0); V1Pod foo1 = new V1Pod().metadata(new V1ObjectMeta().name("foo1").namespace("default")); V1Pod foo2 = new V1Pod().metadata(new V1ObjectMeta().name("foo2").namespace("default")); V1Pod...
Caches { public static String metaNamespaceKeyFunc(KubernetesObject obj) { V1ObjectMeta metadata = obj.getMetadata(); if (!Strings.isNullOrEmpty(metadata.getNamespace())) { return metadata.getNamespace() + "/" + metadata.getName(); } return metadata.getName(); } static String deletionHandlingMetaNamespaceKeyFunc( ...
@Test public void testDefaultNamespaceNameKey() { String testName = "test-name"; String testNamespace = "test-namespace"; V1Pod pod = new V1Pod().metadata(new V1ObjectMeta().name(testName).namespace(testNamespace)); assertEquals(testNamespace + "/" + testName, Caches.metaNamespaceKeyFunc(pod)); }
Caches { public static List<String> metaNamespaceIndexFunc(KubernetesObject obj) { V1ObjectMeta metadata = obj.getMetadata(); if (metadata == null) { return Collections.emptyList(); } return Collections.singletonList(metadata.getNamespace()); } static String deletionHandlingMetaNamespaceKeyFunc( ApiType object);...
@Test public void testDefaultNamespaceIndex() { String testName = "test-name"; String testNamespace = "test-namespace"; V1Pod pod = new V1Pod().metadata(new V1ObjectMeta().name(testName).namespace(testNamespace)); List<String> indices = Caches.metaNamespaceIndexFunc(pod); assertEquals(pod.getMetadata().getNamespace(), ...
Cache implements Indexer<ApiType> { @Override public void addIndexers(Map<String, Function<ApiType, List<String>>> newIndexers) { if (!items.isEmpty()) { throw new IllegalStateException("cannot add indexers to a non-empty cache"); } Set<String> oldKeys = indexers.keySet(); Set<String> newKeys = newIndexers.keySet(); Se...
@Test public void testAddIndexers() { Cache<V1Pod> podCache = new Cache<>(); String nodeIndex = "node-index"; String clusterIndex = "cluster-index"; Map<String, Function<V1Pod, List<String>>> indexers = new HashMap<>(); indexers.put( nodeIndex, (V1Pod pod) -> { return Arrays.asList(pod.getSpec().getNodeName()); }); ind...
ProcessorListener implements Runnable { public void add(Notification<ApiType> obj) { if (obj == null) { return; } this.queue.add(obj); } ProcessorListener(ResourceEventHandler<ApiType> handler, long resyncPeriod); @Override void run(); void add(Notification<ApiType> obj); void determineNextResync(DateTime now); boolean...
@Test public void testNotificationHandling() throws InterruptedException { V1Pod pod = new V1Pod().metadata(new V1ObjectMeta().name("foo").namespace("default")); ProcessorListener<V1Pod> listener = new ProcessorListener<>( new ResourceEventHandler<V1Pod>() { @Override public void onAdd(V1Pod obj) { assertEquals(pod, ob...
Copy extends Exec { public InputStream copyFileFromPod(String namespace, String pod, String srcPath) throws ApiException, IOException { return copyFileFromPod(namespace, pod, null, srcPath); } Copy(); Copy(ApiClient apiClient); InputStream copyFileFromPod(String namespace, String pod, String srcPath); InputStream copy...
@Test public void testUrl() throws IOException, ApiException, InterruptedException { Copy copy = new Copy(client); V1Pod pod = new V1Pod().metadata(new V1ObjectMeta().name(podName).namespace(namespace)); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec")) .willRet...
Copy extends Exec { public void copyFileToPod( String namespace, String pod, String container, Path srcPath, Path destPath) throws ApiException, IOException { final Process proc = execCopyToPod(namespace, pod, container, destPath); File srcFile = new File(srcPath.toUri()); try (ArchiveOutputStream archiveOutputStream =...
@Test public void testCopyFileToPod() throws IOException, InterruptedException { File testFile = File.createTempFile("testfile", null); testFile.deleteOnExit(); Copy copy = new Copy(client); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec")) .willReturn( aRespons...
GroupVersion { public static GroupVersion parse(String apiVersion) { if (Strings.isNullOrEmpty(apiVersion)) { throw new IllegalArgumentException("No apiVersion found on object"); } if ("v1".equals(apiVersion)) { return new GroupVersion("", "v1"); } String[] parts = apiVersion.split("/"); if (parts.length != 2) { throw ...
@Test public void parse() { assertEquals(new GroupVersion("", "v1"), GroupVersion.parse(new V1Pod().apiVersion("v1"))); assertEquals( new GroupVersion("apps", "v1"), GroupVersion.parse(new V1Deployment().apiVersion("apps/v1"))); assertThrows( IllegalArgumentException.class, () -> { GroupVersion.parse(new V1Pod()); Grou...
PodLogs { public InputStream streamNamespacedPodLog(V1Pod pod) throws ApiException, IOException { if (pod.getSpec() == null) { throw new ApiException("pod.spec is null and container isn't specified."); } if (pod.getSpec().getContainers() == null || pod.getSpec().getContainers().size() < 1) { throw new ApiException("pod...
@Test public void testNotFound() throws ApiException, IOException { V1Pod pod = new V1Pod() .metadata(new V1ObjectMeta().name(podName).namespace(namespace)) .spec( new V1PodSpec() .containers(Arrays.asList(new V1Container().name(container).image("nginx")))); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/namespaces/...
JSON { public String serialize(Object obj) { return gson.toJson(obj); } JSON(); static GsonBuilder createGson(); Gson getGson(); JSON setGson(Gson gson); JSON setLenientOnJson(boolean lenientOnJson); String serialize(Object obj); @SuppressWarnings("unchecked") T deserialize(String body, Type returnType); JSON setDateTi...
@Test public void testSerializeByteArray() { final JSON json = new JSON(); final String plainText = "string that contains '=' when encoded"; final String base64String = json.serialize(plainText.getBytes()); final String pureString = base64String.replaceAll("^\"|\"$", ""); final ByteString byteStr = ByteString.decodeBas...
IntOrString { public boolean isInteger() { return isInt; } IntOrString(final String value); IntOrString(final int value); boolean isInteger(); String getStrValue(); Integer getIntValue(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void whenCreatedWithInt_isInteger() { IntOrString intOrString = new IntOrString(17); assertThat(intOrString.isInteger(), is(true)); } @Test public void whenCreatedWithString_isNotInteger() { IntOrString intOrString = new IntOrString("17"); assertThat(intOrString.isInteger(), is(false)); }
IntOrString { public Integer getIntValue() { if (!isInt) { throw new IllegalStateException("Not an integer"); } return intValue; } IntOrString(final String value); IntOrString(final int value); boolean isInteger(); String getStrValue(); Integer getIntValue(); @Override String toString(); @Override boolean equals(Objec...
@Test public void whenCreatedWithInt_canRetrieveIntValue() { IntOrString intOrString = new IntOrString(17); assertThat(intOrString.getIntValue(), equalTo(17)); } @Test(expected = IllegalStateException.class) public void whenCreatedWithInt_cannotRetrieveIntValue() { IntOrString intOrString = new IntOrString("17"); intOr...
PatchUtils { public static <ApiType> ApiType patch( Class<ApiType> apiTypeClass, PatchCallFunc callFunc, String patchFormat) throws ApiException { return patch(apiTypeClass, callFunc, patchFormat, Configuration.getDefaultApiClient()); } static ApiType patch( Class<ApiType> apiTypeClass, PatchCallFunc callFunc, S...
@Test public void testJsonPatchPod() throws ApiException { CoreV1Api coreV1Api = new CoreV1Api(client); stubFor( patch(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")) .withHeader("Content-Type", containing(V1Patch.PATCH_FORMAT_JSON_PATCH)) .willReturn( aResponse() .withStatus(200) .withHeader("Content-Type", "ap...
IntOrString { public String getStrValue() { if (isInt) { throw new IllegalStateException("Not a string"); } return strValue; } IntOrString(final String value); IntOrString(final int value); boolean isInteger(); String getStrValue(); Integer getIntValue(); @Override String toString(); @Override boolean equals(Object o)...
@Test(expected = IllegalStateException.class) public void whenCreatedWithInt_cannotRetrieveStringValue() { IntOrString intOrString = new IntOrString(17); intOrString.getStrValue(); } @Test public void whenCreatedWithString_canRetrieveStringValue() { IntOrString intOrString = new IntOrString("17"); assertThat(intOrStrin...
QuantityFormatter { public Quantity parse(final String value) { if (value == null || value.isEmpty()) { throw new QuantityFormatException(""); } final String[] parts = value.split(PARTS_RE); final BigDecimal numericValue = parseNumericValue(parts[0]); final String suffix = value.substring(parts[0].length()); final Base...
@Test public void testParsePlain() { final Quantity quantity = new QuantityFormatter().parse("1"); assertThat(quantity.getFormat(), is(Quantity.Format.DECIMAL_SI)); assertThat(quantity.getNumber(), is(BigDecimal.valueOf(1))); } @Test public void testParseFractional() { final Quantity quantity = new QuantityFormatter()....
QuantityFormatter { public String format(final Quantity quantity) { switch (quantity.getFormat()) { case DECIMAL_SI: case DECIMAL_EXPONENT: return toBase10String(quantity); case BINARY_SI: if (isFractional(quantity)) { return toBase10String(new Quantity(quantity.getNumber(), Quantity.Format.DECIMAL_SI)); } return toBas...
@Test public void testFormatPlain() { final String formattedString = new QuantityFormatter() .format(new Quantity(new BigDecimal("100"), Quantity.Format.DECIMAL_SI)); assertThat(formattedString, is("100")); } @Test public void testFormatDecimalSi() { final String formattedString = new QuantityFormatter() .format(new Qu...
SuffixFormatter { public BaseExponent parse(final String suffix) { final BaseExponent decimalSuffix = suffixToDecimal.get(suffix); if (decimalSuffix != null) { return decimalSuffix; } final BaseExponent binarySuffix = suffixToBinary.get(suffix); if (binarySuffix != null) { return binarySuffix; } if (suffix.length() > 0...
@Test public void testParseBinaryKi() { final BaseExponent baseExponent = new SuffixFormatter().parse("Ki"); assertThat(baseExponent.getBase(), is(2)); assertThat(baseExponent.getExponent(), is(10)); assertThat(baseExponent.getFormat(), is(Quantity.Format.BINARY_SI)); } @Test public void testParseDecimalZero() { final ...
SuffixFormatter { public String format(final Quantity.Format format, final int exponent) { switch (format) { case DECIMAL_SI: return getDecimalSiSuffix(exponent); case BINARY_SI: return getBinarySiSuffix(exponent); case DECIMAL_EXPONENT: return exponent == 0 ? "" : "e" + exponent; default: throw new IllegalStateExcepti...
@Test public void testFormatZeroDecimalExponent() { final String formattedString = new SuffixFormatter().format(Quantity.Format.DECIMAL_EXPONENT, 0); assertThat(formattedString, is("")); } @Test public void testFormatDecimalExponent() { final String formattedString = new SuffixFormatter().format(Quantity.Format.DECIMAL...
ModelMapper { public static Class<?> getApiTypeClass(String apiGroupVersion, String kind) { String[] parts = apiGroupVersion.split("/"); String apiGroup; String apiVersion; if (parts.length == 1) { apiGroup = ""; apiVersion = apiGroupVersion; } else { apiGroup = parts[0]; apiVersion = parts[1]; } return getApiTypeClass...
@Test public void testPrebuiltModelMapping() { assertEquals(V1Pod.class, ModelMapper.getApiTypeClass("", "v1", "Pod")); assertEquals(V1Deployment.class, ModelMapper.getApiTypeClass("", "v1", "Deployment")); assertEquals( V1beta1CustomResourceDefinition.class, ModelMapper.getApiTypeClass("", "v1beta1", "CustomResourceDe...
ModelMapper { public static GroupVersionKind preBuiltGetGroupVersionKindByClass(Class<?> clazz) { return preBuiltClassesByGVK.entrySet().stream() .filter(e -> clazz.equals(e.getValue())) .map(e -> e.getKey()) .findFirst() .get(); } @Deprecated static void addModelMap(String apiGroupVersion, String kind, Class<?> clazz...
@Test public void testPreBuiltGetClassByKind() { assertEquals( new GroupVersionKind("", "v1", "Pod"), ModelMapper.preBuiltGetGroupVersionKindByClass(V1Pod.class)); assertEquals( new GroupVersionKind("", "v1", "Pod"), ModelMapper.preBuiltGetGroupVersionKindByClass(V1Pod.class)); assertEquals( new GroupVersionKind("", "v...
StringWrapper { public static String[] wrapString(@Nonnull String str, int maxWidth, @Nullable String[] output) { if (output == null) { output = new String[(int)((str.length() / maxWidth) * 1.5d + 1)]; } int lineStart = 0; int arrayIndex = 0; int i; for (i=0; i<str.length(); i++) { char c = str.charAt(i); if (c == '\n'...
@Test public void testWrapString() { validateResult( new String[]{"abc", "abcdef", "abcdef"}, StringWrapper.wrapString("abc\nabcdefabcdef", 6, null)); validateResult( new String[]{"abc"}, StringWrapper.wrapString("abc", 6, new String[3])); validateResult( new String[]{"abc"}, StringWrapper.wrapString("abc", 6, new Stri...
ClassFileNameHandler { @Nonnull static String shortenPathComponent(@Nonnull String pathComponent, int maxLength) { int toRemove = pathComponent.length() - maxLength + 1; int firstIndex = (pathComponent.length()/2) - (toRemove/2); return pathComponent.substring(0, firstIndex) + "#" + pathComponent.substring(firstIndex+t...
@Test public void testShortedPathComponent() { StringBuilder sb = new StringBuilder(); for (int i=0; i<300; i++) { sb.append((char)i); } String result = ClassFileNameHandler.shortenPathComponent(sb.toString(), 255); Assert.assertEquals(255, result.length()); }
BaseDexBuffer { public int readSmallUint(int offset) { byte[] buf = this.buf; int result = (buf[offset] & 0xff) | ((buf[offset+1] & 0xff) << 8) | ((buf[offset+2] & 0xff) << 16) | ((buf[offset+3]) << 24); if (result < 0) { throw new ExceptionWithContext("Encountered small uint that is out of range at offset 0x%x", offse...
@Test public void testReadSmallUintSuccess() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x11, 0x22, 0x33, 0x44}); Assert.assertEquals(0x44332211, dexBuf.readSmallUint(0)); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00, 0x00, 0x00}); Assert.assertEquals(0, dexBuf.readSmallUint(0)); dexBuf = new BaseDexBu...
BaseDexBuffer { public int readUshort(int offset) { byte[] buf = this.buf; return (buf[offset] & 0xff) | ((buf[offset+1] & 0xff) << 8); } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset);...
@Test public void testReadUshort() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x11, 0x22}); Assert.assertEquals(dexBuf.readUshort(0), 0x2211); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00}); Assert.assertEquals(dexBuf.readUshort(0), 0); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff}); A...
BaseDexBuffer { public int readUbyte(int offset) { return buf[offset] & 0xff; } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset); int readInt(int offset); int readShort(int offset); int r...
@Test public void testReadUbyte() { byte[] buf = new byte[1]; BaseDexBuffer dexBuf = new BaseDexBuffer(buf); for (int i=0; i<=0xff; i++) { buf[0] = (byte)i; Assert.assertEquals(i, dexBuf.readUbyte(0)); } }
BaseDexBuffer { public long readLong(int offset) { byte[] buf = this.buf; return (buf[offset] & 0xff) | ((buf[offset+1] & 0xff) << 8) | ((buf[offset+2] & 0xff) << 16) | ((buf[offset+3] & 0xffL) << 24) | ((buf[offset+4] & 0xffL) << 32) | ((buf[offset+5] & 0xffL) << 40) | ((buf[offset+6] & 0xffL) << 48) | (((long)buf[off...
@Test public void testReadLong() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}); Assert.assertEquals(0x7766554433221100L, dexBuf.readLong(0)); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); Assert.assertEquals(0, dexBuf.r...
BaseDexBuffer { public int readInt(int offset) { byte[] buf = this.buf; return (buf[offset] & 0xff) | ((buf[offset+1] & 0xff) << 8) | ((buf[offset+2] & 0xff) << 16) | (buf[offset+3] << 24); } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset);...
@Test public void testReadInt() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x11, 0x22, 0x33, 0x44}); Assert.assertEquals(0x44332211, dexBuf.readInt(0)); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00, 0x00, 0x00}); Assert.assertEquals(0, dexBuf.readInt(0)); dexBuf = new BaseDexBuffer(new byte[] {(byte)0x...
BaseDexBuffer { public int readShort(int offset) { byte[] buf = this.buf; return (buf[offset] & 0xff) | (buf[offset+1] << 8); } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset); int readI...
@Test public void testReadShort() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x11, 0x22}); Assert.assertEquals(dexBuf.readShort(0), 0x2211); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00}); Assert.assertEquals(dexBuf.readShort(0), 0); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff}); Asse...
BaseDexBuffer { public int readByte(int offset) { return buf[offset]; } BaseDexBuffer(@Nonnull byte[] buf); int readSmallUint(int offset); int readOptionalUint(int offset); int readUshort(int offset); int readUbyte(int offset); long readLong(int offset); int readInt(int offset); int readShort(int offset); int readByte(...
@Test public void testReadByte() { byte[] buf = new byte[1]; BaseDexBuffer dexBuf = new BaseDexBuffer(buf); for (int i=0; i<=0xff; i++) { buf[0] = (byte)i; Assert.assertEquals((byte)i, dexBuf.readByte(0)); } }
GenerateConfigMojo extends AbstractMojo { public String getSettingsForArtifact( String fullSettings, String groupId, String artifactId ) { if( fullSettings != null ) { for( String token : fullSettings.split( "," ) ) { int end = ( token.indexOf( "@" ) >= 0 ) ? token.indexOf( "@" ) : token.length(); String ga_part[] = to...
@Test public void testSettingsMatching() { assertEquals( "@42@bee", new GenerateConfigMojo().getSettingsForArtifact( "cheese:ham@1@nope,foo:bar@42@bee,fuel:oil@1@xx", "foo", "bar" ) ); assertEquals( "", new GenerateConfigMojo().getSettingsForArtifact( "cheese:ham@1@nope,foo:bar@42@bee,fuel:oil@1@xx", "xx", "bb" ) ); as...
CompositeScannerProvisionOption extends AbstractUrlProvisionOption<CompositeScannerProvisionOption> implements Scanner { public String getURL() { return new StringBuilder() .append( SCHEMA ) .append( SEPARATOR_SCHEME ) .append( super.getURL() ) .append( getOptions( this ) ) .toString(); } CompositeScannerProvisionOptio...
@Test public void urlAsReferenceViaFactoryMethod() { assertThat( "Scan composite url", scanComposite( url( "file:foo.composite" ) ).getURL(), is( equalTo( "scan-composite:file:foo.composite@update" ) ) ); } @Test public void urlAsMavenUrl() { assertThat( "Scan composite url", new CompositeScannerProvisionOption( maven(...
FileScannerProvisionOption extends AbstractUrlProvisionOption<FileScannerProvisionOption> implements Scanner { public String getURL() { return new StringBuilder() .append( SCHEMA ) .append( SEPARATOR_SCHEME ) .append( super.getURL() ) .append( getOptions( this ) ) .toString(); } FileScannerProvisionOption( final String...
@Test public void urlAsString() { assertThat( "Scan file url", new FileScannerProvisionOption( "file:foo.bundles" ).getURL(), is( equalTo( "scan-file:file:foo.bundles" ) ) ); } @Test public void urlAsStringViaFactoryMethod() { assertThat( "Scan file url", scanFile( "file:foo.bundles" ).getURL(), is( equalTo( "scan-file...
FeaturesScannerProvisionOption extends AbstractUrlProvisionOption<FeaturesScannerProvisionOption> implements Scanner { public String getURL() { final StringBuilder url = new StringBuilder() .append( SCHEMA ) .append( SEPARATOR_SCHEME ) .append( super.getURL() ) .append( SEPARATOR_FILTER ); boolean first = true; for( St...
@Test public void urlAsString() { assertThat( "Scan features url", new FeaturesScannerProvisionOption( "file:foo-features.xml", "f1", "f2/1.0.0" ).getURL(), is( equalTo( "scan-features:file:foo-features.xml!/f1,f2/1.0.0" ) ) ); } @Test public void urlAsStringViaFactoryMethod() { assertThat( "Scan features url", scanFea...
ConfigurationManager { static void setEnableDefaultload(boolean enabled){ enableDefaultload =enabled; } static Map<String,Map<String,String>> getAllProperties(); static Map<String,String> getPropertiesByConfigName(String configName); static Set<String> getConfigKeys(String configName); static synchronized boolean isCo...
@Test public void testGetDefaultAppPro(){ ConfigurationManager.setEnableDefaultload(true); System.out.println(ConfigurationManager.class.getProtectionDomain().getCodeSource().getLocation().toString()); URL url = getClass().getProtectionDomain().getCodeSource().getLocation(); try { InputStream in = ConfigurationManager....
ConfigurationManager { static void loadProperties(Properties properties) throws InitConfigurationException { if (instance == null) { instance = getConfigInstance(); } ConfigurationUtils.loadProperties(properties, instance); } static Map<String,Map<String,String>> getAllProperties(); static Map<String,String> getProper...
@Test public void testLoadProperties() throws Exception { ConfigurationManager.loadPropertiesFromResources("test.properties"); assertEquals("9", ConfigurationManager.getConfigInstance().getProperty("com.ctrip.config.samples.needCount")); assertEquals("9", ConfigurationManager.getConfigInstance().getString("com.ctrip.co...
ConfigurationManager { public static Configuration getConfigInstance() throws InitConfigurationException { if (instance == null) { synchronized (ConfigurationManager.class) { if (instance == null) { instance = createDefaultConfigInstance(); try { customProperties = Tools.loadPropertiesFromFile(TEMPFILENAME); } catch (T...
@Test public void testNumberProperties() throws Exception { Configuration config = ConfigurationManager.getConfigInstance(); double val = 12.3; config.setProperty("test-double",val); assertTrue(val == config.getDouble("test-double")); config.setProperty("test-int",10); assertTrue(10 == config.getDouble("test-int")); as...
ConfigurationManager { private static Properties loadCascadedProperties(String configName) throws IOException { String defaultConfigFileName = configName + ".properties"; ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL url = loader.getResource(defaultConfigFileName); if (url == null) { throw ne...
@Test public void testLoadCascadedProperties() throws Exception { ConfigurationManager.loadCascadedPropertiesFromResources("config/test"); assertEquals("7", ConfigurationManager.getConfigInstance().getProperty("com.ctrip.config.samples.needCount")); assertEquals("1", ConfigurationManager.getConfigInstance().getProperty...
VIApiHandler { public ExeResult executeService(String path,String user,Map<String,Object> params){ long startTime = System.nanoTime(); Object rtn=null; int responseCode = SC_OK; int permission = Permission.ALL.getValue(); EventLogger eventLogger = EventLoggerFactory.getTransLogger(getClass()); if(path == null){ return ...
@Test public void testConfig(){ String path = "/config/all"; VIApiHandler.ExeResult rtn = handler.executeService(path, user, null); Map<String,Object> data = (Map<String, Object>) rtn.getData(); assertTrue(data.size()>0); assertTrue(data.containsKey("test")); } @Test public void testThreading(){ String path = "/threadi...
VIServer { public VIServer(int listenPort,boolean useVIAuthentication) throws Exception { server = new Server(listenPort); handler = bind(server, String.valueOf(listenPort),useVIAuthentication); } VIServer(int listenPort,boolean useVIAuthentication); VIServer(int listenPort); static ServletHandler bind(Server server,S...
@Test public void testVIServer() throws Exception { int port = 1998; VIServer server = new VIServer(port); server.start(); URL url = new URL("http: Gson gson = new Gson(); List<CInfo> infos= new ArrayList<>(); String content = IOUtils.readAll((InputStream)url.getContent()); System.out.println(IgniteManager.getStatus()....
EventBusDispatcher implements IEventDispatcher { @Override public void dispatch(String name, Object event) { logger.debug("DispatchEvent: {} ({})", name, event); final Object[] args = event!=null?new Object[]{event}:new Object[]{}; dispatch(name, args); } EventBusDispatcher(EventBusManager ebManager, EventBus eb); @Ove...
@Test public void testDispatch_withArgumentAndExistingMethod_willSuccess() { testEventBus.testEventWithArgument(THE_ARG); replay(testEventBus); eventBusDispatcher.dispatch("testEventWithArgument", THE_ARG); verify(testEventBus); } @Test public void testDispatch_withoutArgumentAndExistingMethod_willSuccess() { testEvent...
UiBinder { public <T extends Component> T bind(Class<T> viewClass, Locale locale, IEventBinder eventBinder) throws UiBinderException { try { T view = (T) viewClass.newInstance(); view = bind(viewClass.getName(), view, locale, eventBinder); return (T) view; } catch (InstantiationException e) { throw new UiConstraintExce...
@Test public void testBindUiFields() throws Exception { UiBinderView view = instance.bind(UiBinderView.class, new Locale("en"), null); assertNotNull("button ui field not bound", view.save); assertNotNull("label ui field not bound", view.labelOne); assertNotNull("label ui field not bound", view.labelTwo); } @Test public...