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 getLatestArrival(); @Override VehicleType getType(); @Override String getId(); @Override boolean isReturnToDepot(); @Override Location getStartLocation(); @Override Location getEndLocation(); @Override Skills getSkills(); @Override Break getBreak(); @Override int hashCode(); @Override boolean equals(Object obj); } | @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); }
@Test public void whenStartLocationCoordIsSet_itIsDoneCorrectly() { 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 getLatestArrival(); @Override VehicleType getType(); @Override String getId(); @Override boolean isReturnToDepot(); @Override Location getStartLocation(); @Override Location getEndLocation(); @Override Skills getSkills(); @Override Break getBreak(); @Override int hashCode(); @Override boolean equals(Object obj); } | @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_itShouldBeSetCorrectly() { Vehicle v = VehicleImpl.Builder.newInstance("v").setEarliestStart(10.0).setStartLocation(Location.newInstance(1, 2)).build(); assertEquals(10.0, v.getEarliestDeparture(), 0.01); } |
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 getLatestArrival(); @Override VehicleType getType(); @Override String getId(); @Override boolean isReturnToDepot(); @Override Location getStartLocation(); @Override Location getEndLocation(); @Override Skills getSkills(); @Override Break getBreak(); @Override int hashCode(); @Override boolean equals(Object obj); } | @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 whenVehicleIsBuiltAndLatestArrivalIsSet_itShouldBeSetCorrectly() { Vehicle v = VehicleImpl.Builder.newInstance("v").setLatestArrival(30.0).setStartLocation(Location.newInstance(1, 2)).build(); assertEquals(30.0, v.getLatestArrival(), 0.01); } |
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("登录权限")}) @ApiResponses(value = { @ApiResponse(code = 401, message = "未登录"), @ApiResponse(code = 404, message = "查询模式未找到"), @ApiResponse(code = 403, message = "只有管理员或用户自己能查询自己的用户信息"), }) public UserDO findByKey(@PathVariable("key") @ApiParam(value = "查询关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "查询模式,可以是id或username或phone或email", required = true) String mode) { QueryUserHandler handler = SpringContextUtil.getBean("QueryUserHandler", StringUtils.lowerCase(mode)); if (handler == null) { throw new QueryUserModeNotFoundException(mode); } UserDO userDO = handler.handle(key); if (userDO == null) { throw new UserNotFoundException(key); } return userDO; } @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("登录权限")}) @ApiResponses(value = { @ApiResponse(code = 401, message = "未登录"), @ApiResponse(code = 404, message = "查询模式未找到"), @ApiResponse(code = 403, message = "只有管理员或用户自己能查询自己的用户信息"), }) UserDO findByKey(@PathVariable("key") @ApiParam(value = "查询关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "查询模式,可以是id或username或phone或email", required = true) String mode) {; @ResponseStatus(HttpStatus.CREATED) @RequestMapping(method = RequestMethod.POST) @ApiOperation(value = "创建用户,为用户发送验证邮件,等待用户激活,若24小时内未激活需要重新注册", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 409, message = "用户名已存在"), @ApiResponse(code = 400, message = "用户属性校验失败") }) void createUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{id}/avatar", method = RequestMethod.GET) @ApiOperation(value = "获取用户的头像图片", response = Byte.class) @ApiResponses(value = { @ApiResponse(code = 404, message = "文件不存在"), @ApiResponse(code = 400, message = "文件传输失败") }) void getUserAvatar(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response); @RequestMapping(value = "/{id}/activation", method = RequestMethod.GET) @ApiOperation(value = "用户激活,前置条件是用户已注册且在24小时内", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 401, message = "未注册或超时或激活码错误") }) void activate(@PathVariable("id") @ApiParam(value = "用户Id", required = true) Long id, @RequestParam("activationCode") @ApiParam(value = "激活码", required = true) String activationCode) {; @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 = 404, message = "用户属性校验失败"), @ApiResponse(code = 403, message = "只有管理员或用户自己能更新用户信息"), }) void updateUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{key}/password/reset_validation", method = RequestMethod.GET) @ApiOperation(value = "发送忘记密码的邮箱验证", notes = "属性可以是id,sername或email或手机号", response = UserDO.class) void forgetPassword(@PathVariable("key") @ApiParam(value = "关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "验证模式,可以是username或phone或email", required = true) String mode) {; @RequestMapping(value="/principles",method = RequestMethod.GET) String getPrinciples(@AuthenticationPrincipal JWTUser jwtUser); @RequestMapping(value = "/{id}/password", method = RequestMethod.PUT) @ApiOperation(value = "忘记密码后可以修改密码") void resetPassword(@PathVariable("id") Long id, @RequestParam("forgetPasswordCode") @ApiParam(value = "验证码", required = true) String forgetPasswordCode, @RequestParam("password") @ApiParam(value = "新密码", required = true) String password) {; @RequestMapping(value = "/{username}/duplication", method = RequestMethod.GET) @ApiOperation(value = "查询用户名是否重复", response = Boolean.class) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) boolean isUsernameDuplicated(@PathVariable("username") String username); @RequestMapping(method = RequestMethod.GET) @PreAuthorize("hasRole('ADMIN')") @ApiOperation(value = "分页查询用户信息", response = PageInfo.class, authorizations = {@Authorization("登录权限")}) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) PageInfo<UserDO> findAllUsers(@RequestParam("pageNum") @ApiParam(value = "页码,从1开始", defaultValue = "1") Integer pageNum, @RequestParam("pageSize") @ApiParam(value = "每页记录数", defaultValue = "5") Integer pageSize) {; } | @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 createUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) { log.info("{}",user); if (isUsernameDuplicated(user.getUsername())) { throw new UsernameExistedException(user.getUsername()); } else if (result.hasErrors()) { throw new ValidationException(result.getFieldErrors()); } String activationCode = UUIDUtil.uuid(); service.save(user); verificationManager.createVerificationCode(activationCode, String.valueOf(user.getId()), authenticationProperties.getActivationCodeExpireTime()); log.info("{} {}",user.getEmail(),user.getId()); Map<String, Object> params = new HashMap<>(); params.put("id", user.getId()); params.put("activationCode", activationCode); emailService.sendHTML(user.getEmail(), "activation", params, null); } @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("登录权限")}) @ApiResponses(value = { @ApiResponse(code = 401, message = "未登录"), @ApiResponse(code = 404, message = "查询模式未找到"), @ApiResponse(code = 403, message = "只有管理员或用户自己能查询自己的用户信息"), }) UserDO findByKey(@PathVariable("key") @ApiParam(value = "查询关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "查询模式,可以是id或username或phone或email", required = true) String mode) {; @ResponseStatus(HttpStatus.CREATED) @RequestMapping(method = RequestMethod.POST) @ApiOperation(value = "创建用户,为用户发送验证邮件,等待用户激活,若24小时内未激活需要重新注册", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 409, message = "用户名已存在"), @ApiResponse(code = 400, message = "用户属性校验失败") }) void createUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{id}/avatar", method = RequestMethod.GET) @ApiOperation(value = "获取用户的头像图片", response = Byte.class) @ApiResponses(value = { @ApiResponse(code = 404, message = "文件不存在"), @ApiResponse(code = 400, message = "文件传输失败") }) void getUserAvatar(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response); @RequestMapping(value = "/{id}/activation", method = RequestMethod.GET) @ApiOperation(value = "用户激活,前置条件是用户已注册且在24小时内", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 401, message = "未注册或超时或激活码错误") }) void activate(@PathVariable("id") @ApiParam(value = "用户Id", required = true) Long id, @RequestParam("activationCode") @ApiParam(value = "激活码", required = true) String activationCode) {; @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 = 404, message = "用户属性校验失败"), @ApiResponse(code = 403, message = "只有管理员或用户自己能更新用户信息"), }) void updateUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{key}/password/reset_validation", method = RequestMethod.GET) @ApiOperation(value = "发送忘记密码的邮箱验证", notes = "属性可以是id,sername或email或手机号", response = UserDO.class) void forgetPassword(@PathVariable("key") @ApiParam(value = "关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "验证模式,可以是username或phone或email", required = true) String mode) {; @RequestMapping(value="/principles",method = RequestMethod.GET) String getPrinciples(@AuthenticationPrincipal JWTUser jwtUser); @RequestMapping(value = "/{id}/password", method = RequestMethod.PUT) @ApiOperation(value = "忘记密码后可以修改密码") void resetPassword(@PathVariable("id") Long id, @RequestParam("forgetPasswordCode") @ApiParam(value = "验证码", required = true) String forgetPasswordCode, @RequestParam("password") @ApiParam(value = "新密码", required = true) String password) {; @RequestMapping(value = "/{username}/duplication", method = RequestMethod.GET) @ApiOperation(value = "查询用户名是否重复", response = Boolean.class) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) boolean isUsernameDuplicated(@PathVariable("username") String username); @RequestMapping(method = RequestMethod.GET) @PreAuthorize("hasRole('ADMIN')") @ApiOperation(value = "分页查询用户信息", response = PageInfo.class, authorizations = {@Authorization("登录权限")}) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) PageInfo<UserDO> findAllUsers(@RequestParam("pageNum") @ApiParam(value = "页码,从1开始", defaultValue = "1") Integer pageNum, @RequestParam("pageSize") @ApiParam(value = "每页记录数", defaultValue = "5") Integer pageSize) {; } | @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, HttpServletRequest request, HttpServletResponse response) { String relativePath = service.findAvatarById(id); FileUtil.download(relativePath, request.getServletContext(), response); } @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("登录权限")}) @ApiResponses(value = { @ApiResponse(code = 401, message = "未登录"), @ApiResponse(code = 404, message = "查询模式未找到"), @ApiResponse(code = 403, message = "只有管理员或用户自己能查询自己的用户信息"), }) UserDO findByKey(@PathVariable("key") @ApiParam(value = "查询关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "查询模式,可以是id或username或phone或email", required = true) String mode) {; @ResponseStatus(HttpStatus.CREATED) @RequestMapping(method = RequestMethod.POST) @ApiOperation(value = "创建用户,为用户发送验证邮件,等待用户激活,若24小时内未激活需要重新注册", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 409, message = "用户名已存在"), @ApiResponse(code = 400, message = "用户属性校验失败") }) void createUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{id}/avatar", method = RequestMethod.GET) @ApiOperation(value = "获取用户的头像图片", response = Byte.class) @ApiResponses(value = { @ApiResponse(code = 404, message = "文件不存在"), @ApiResponse(code = 400, message = "文件传输失败") }) void getUserAvatar(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response); @RequestMapping(value = "/{id}/activation", method = RequestMethod.GET) @ApiOperation(value = "用户激活,前置条件是用户已注册且在24小时内", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 401, message = "未注册或超时或激活码错误") }) void activate(@PathVariable("id") @ApiParam(value = "用户Id", required = true) Long id, @RequestParam("activationCode") @ApiParam(value = "激活码", required = true) String activationCode) {; @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 = 404, message = "用户属性校验失败"), @ApiResponse(code = 403, message = "只有管理员或用户自己能更新用户信息"), }) void updateUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{key}/password/reset_validation", method = RequestMethod.GET) @ApiOperation(value = "发送忘记密码的邮箱验证", notes = "属性可以是id,sername或email或手机号", response = UserDO.class) void forgetPassword(@PathVariable("key") @ApiParam(value = "关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "验证模式,可以是username或phone或email", required = true) String mode) {; @RequestMapping(value="/principles",method = RequestMethod.GET) String getPrinciples(@AuthenticationPrincipal JWTUser jwtUser); @RequestMapping(value = "/{id}/password", method = RequestMethod.PUT) @ApiOperation(value = "忘记密码后可以修改密码") void resetPassword(@PathVariable("id") Long id, @RequestParam("forgetPasswordCode") @ApiParam(value = "验证码", required = true) String forgetPasswordCode, @RequestParam("password") @ApiParam(value = "新密码", required = true) String password) {; @RequestMapping(value = "/{username}/duplication", method = RequestMethod.GET) @ApiOperation(value = "查询用户名是否重复", response = Boolean.class) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) boolean isUsernameDuplicated(@PathVariable("username") String username); @RequestMapping(method = RequestMethod.GET) @PreAuthorize("hasRole('ADMIN')") @ApiOperation(value = "分页查询用户信息", response = PageInfo.class, authorizations = {@Authorization("登录权限")}) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) PageInfo<UserDO> findAllUsers(@RequestParam("pageNum") @ApiParam(value = "页码,从1开始", defaultValue = "1") Integer pageNum, @RequestParam("pageSize") @ApiParam(value = "每页记录数", defaultValue = "5") Integer pageSize) {; } | @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) Long id, @RequestParam("activationCode") @ApiParam(value = "激活码", required = true) String activationCode) { UserDO user = service.findById(id); if (!verificationManager.checkVerificationCode(activationCode, String.valueOf(id))) { verificationManager.deleteVerificationCode(activationCode); throw new ActivationCodeValidationException(activationCode); } user.setUserStatus(UserStatus.ACTIVATED); verificationManager.deleteVerificationCode(activationCode); service.update(user); } @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("登录权限")}) @ApiResponses(value = { @ApiResponse(code = 401, message = "未登录"), @ApiResponse(code = 404, message = "查询模式未找到"), @ApiResponse(code = 403, message = "只有管理员或用户自己能查询自己的用户信息"), }) UserDO findByKey(@PathVariable("key") @ApiParam(value = "查询关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "查询模式,可以是id或username或phone或email", required = true) String mode) {; @ResponseStatus(HttpStatus.CREATED) @RequestMapping(method = RequestMethod.POST) @ApiOperation(value = "创建用户,为用户发送验证邮件,等待用户激活,若24小时内未激活需要重新注册", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 409, message = "用户名已存在"), @ApiResponse(code = 400, message = "用户属性校验失败") }) void createUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{id}/avatar", method = RequestMethod.GET) @ApiOperation(value = "获取用户的头像图片", response = Byte.class) @ApiResponses(value = { @ApiResponse(code = 404, message = "文件不存在"), @ApiResponse(code = 400, message = "文件传输失败") }) void getUserAvatar(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response); @RequestMapping(value = "/{id}/activation", method = RequestMethod.GET) @ApiOperation(value = "用户激活,前置条件是用户已注册且在24小时内", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 401, message = "未注册或超时或激活码错误") }) void activate(@PathVariable("id") @ApiParam(value = "用户Id", required = true) Long id, @RequestParam("activationCode") @ApiParam(value = "激活码", required = true) String activationCode) {; @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 = 404, message = "用户属性校验失败"), @ApiResponse(code = 403, message = "只有管理员或用户自己能更新用户信息"), }) void updateUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{key}/password/reset_validation", method = RequestMethod.GET) @ApiOperation(value = "发送忘记密码的邮箱验证", notes = "属性可以是id,sername或email或手机号", response = UserDO.class) void forgetPassword(@PathVariable("key") @ApiParam(value = "关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "验证模式,可以是username或phone或email", required = true) String mode) {; @RequestMapping(value="/principles",method = RequestMethod.GET) String getPrinciples(@AuthenticationPrincipal JWTUser jwtUser); @RequestMapping(value = "/{id}/password", method = RequestMethod.PUT) @ApiOperation(value = "忘记密码后可以修改密码") void resetPassword(@PathVariable("id") Long id, @RequestParam("forgetPasswordCode") @ApiParam(value = "验证码", required = true) String forgetPasswordCode, @RequestParam("password") @ApiParam(value = "新密码", required = true) String password) {; @RequestMapping(value = "/{username}/duplication", method = RequestMethod.GET) @ApiOperation(value = "查询用户名是否重复", response = Boolean.class) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) boolean isUsernameDuplicated(@PathVariable("username") String username); @RequestMapping(method = RequestMethod.GET) @PreAuthorize("hasRole('ADMIN')") @ApiOperation(value = "分页查询用户信息", response = PageInfo.class, authorizations = {@Authorization("登录权限")}) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) PageInfo<UserDO> findAllUsers(@RequestParam("pageNum") @ApiParam(value = "页码,从1开始", defaultValue = "1") Integer pageNum, @RequestParam("pageSize") @ApiParam(value = "每页记录数", defaultValue = "5") Integer pageSize) {; } | @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 = 404, message = "用户属性校验失败"), @ApiResponse(code = 403, message = "只有管理员或用户自己能更新用户信息"), }) public void updateUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) { if (result.hasErrors()) { throw new ValidationException(result.getFieldErrors()); } service.update(user); } @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("登录权限")}) @ApiResponses(value = { @ApiResponse(code = 401, message = "未登录"), @ApiResponse(code = 404, message = "查询模式未找到"), @ApiResponse(code = 403, message = "只有管理员或用户自己能查询自己的用户信息"), }) UserDO findByKey(@PathVariable("key") @ApiParam(value = "查询关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "查询模式,可以是id或username或phone或email", required = true) String mode) {; @ResponseStatus(HttpStatus.CREATED) @RequestMapping(method = RequestMethod.POST) @ApiOperation(value = "创建用户,为用户发送验证邮件,等待用户激活,若24小时内未激活需要重新注册", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 409, message = "用户名已存在"), @ApiResponse(code = 400, message = "用户属性校验失败") }) void createUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{id}/avatar", method = RequestMethod.GET) @ApiOperation(value = "获取用户的头像图片", response = Byte.class) @ApiResponses(value = { @ApiResponse(code = 404, message = "文件不存在"), @ApiResponse(code = 400, message = "文件传输失败") }) void getUserAvatar(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response); @RequestMapping(value = "/{id}/activation", method = RequestMethod.GET) @ApiOperation(value = "用户激活,前置条件是用户已注册且在24小时内", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 401, message = "未注册或超时或激活码错误") }) void activate(@PathVariable("id") @ApiParam(value = "用户Id", required = true) Long id, @RequestParam("activationCode") @ApiParam(value = "激活码", required = true) String activationCode) {; @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 = 404, message = "用户属性校验失败"), @ApiResponse(code = 403, message = "只有管理员或用户自己能更新用户信息"), }) void updateUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{key}/password/reset_validation", method = RequestMethod.GET) @ApiOperation(value = "发送忘记密码的邮箱验证", notes = "属性可以是id,sername或email或手机号", response = UserDO.class) void forgetPassword(@PathVariable("key") @ApiParam(value = "关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "验证模式,可以是username或phone或email", required = true) String mode) {; @RequestMapping(value="/principles",method = RequestMethod.GET) String getPrinciples(@AuthenticationPrincipal JWTUser jwtUser); @RequestMapping(value = "/{id}/password", method = RequestMethod.PUT) @ApiOperation(value = "忘记密码后可以修改密码") void resetPassword(@PathVariable("id") Long id, @RequestParam("forgetPasswordCode") @ApiParam(value = "验证码", required = true) String forgetPasswordCode, @RequestParam("password") @ApiParam(value = "新密码", required = true) String password) {; @RequestMapping(value = "/{username}/duplication", method = RequestMethod.GET) @ApiOperation(value = "查询用户名是否重复", response = Boolean.class) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) boolean isUsernameDuplicated(@PathVariable("username") String username); @RequestMapping(method = RequestMethod.GET) @PreAuthorize("hasRole('ADMIN')") @ApiOperation(value = "分页查询用户信息", response = PageInfo.class, authorizations = {@Authorization("登录权限")}) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) PageInfo<UserDO> findAllUsers(@RequestParam("pageNum") @ApiParam(value = "页码,从1开始", defaultValue = "1") Integer pageNum, @RequestParam("pageSize") @ApiParam(value = "每页记录数", defaultValue = "5") Integer pageSize) {; } | @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("mode") @ApiParam(value = "验证模式,可以是username或phone或email", required = true) String mode) { UserDO user = findByKey(key, mode); String forgetPasswordCode = UUIDUtil.uuid(); verificationManager.createVerificationCode(forgetPasswordCode, String.valueOf(user.getId()), authenticationProperties.getForgetNameExpireTime()); log.info("{} {}",user.getEmail(),user.getId()); Map<String, Object> params = new HashMap<>(); params.put("id", user.getId()); params.put("forgetPasswordCode", forgetPasswordCode); emailService.sendHTML(user.getEmail(), "forgetPassword", params, null); } @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("登录权限")}) @ApiResponses(value = { @ApiResponse(code = 401, message = "未登录"), @ApiResponse(code = 404, message = "查询模式未找到"), @ApiResponse(code = 403, message = "只有管理员或用户自己能查询自己的用户信息"), }) UserDO findByKey(@PathVariable("key") @ApiParam(value = "查询关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "查询模式,可以是id或username或phone或email", required = true) String mode) {; @ResponseStatus(HttpStatus.CREATED) @RequestMapping(method = RequestMethod.POST) @ApiOperation(value = "创建用户,为用户发送验证邮件,等待用户激活,若24小时内未激活需要重新注册", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 409, message = "用户名已存在"), @ApiResponse(code = 400, message = "用户属性校验失败") }) void createUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{id}/avatar", method = RequestMethod.GET) @ApiOperation(value = "获取用户的头像图片", response = Byte.class) @ApiResponses(value = { @ApiResponse(code = 404, message = "文件不存在"), @ApiResponse(code = 400, message = "文件传输失败") }) void getUserAvatar(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response); @RequestMapping(value = "/{id}/activation", method = RequestMethod.GET) @ApiOperation(value = "用户激活,前置条件是用户已注册且在24小时内", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 401, message = "未注册或超时或激活码错误") }) void activate(@PathVariable("id") @ApiParam(value = "用户Id", required = true) Long id, @RequestParam("activationCode") @ApiParam(value = "激活码", required = true) String activationCode) {; @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 = 404, message = "用户属性校验失败"), @ApiResponse(code = 403, message = "只有管理员或用户自己能更新用户信息"), }) void updateUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{key}/password/reset_validation", method = RequestMethod.GET) @ApiOperation(value = "发送忘记密码的邮箱验证", notes = "属性可以是id,sername或email或手机号", response = UserDO.class) void forgetPassword(@PathVariable("key") @ApiParam(value = "关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "验证模式,可以是username或phone或email", required = true) String mode) {; @RequestMapping(value="/principles",method = RequestMethod.GET) String getPrinciples(@AuthenticationPrincipal JWTUser jwtUser); @RequestMapping(value = "/{id}/password", method = RequestMethod.PUT) @ApiOperation(value = "忘记密码后可以修改密码") void resetPassword(@PathVariable("id") Long id, @RequestParam("forgetPasswordCode") @ApiParam(value = "验证码", required = true) String forgetPasswordCode, @RequestParam("password") @ApiParam(value = "新密码", required = true) String password) {; @RequestMapping(value = "/{username}/duplication", method = RequestMethod.GET) @ApiOperation(value = "查询用户名是否重复", response = Boolean.class) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) boolean isUsernameDuplicated(@PathVariable("username") String username); @RequestMapping(method = RequestMethod.GET) @PreAuthorize("hasRole('ADMIN')") @ApiOperation(value = "分页查询用户信息", response = PageInfo.class, authorizations = {@Authorization("登录权限")}) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) PageInfo<UserDO> findAllUsers(@RequestParam("pageNum") @ApiParam(value = "页码,从1开始", defaultValue = "1") Integer pageNum, @RequestParam("pageSize") @ApiParam(value = "每页记录数", defaultValue = "5") Integer pageSize) {; } | @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(value = "新密码", required = true) String password) { if (!verificationManager.checkVerificationCode(forgetPasswordCode, String.valueOf(id))) { verificationManager.deleteVerificationCode(forgetPasswordCode); throw new ActivationCodeValidationException(forgetPasswordCode); } verificationManager.deleteVerificationCode(forgetPasswordCode); service.resetPassword(id,password); } @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("登录权限")}) @ApiResponses(value = { @ApiResponse(code = 401, message = "未登录"), @ApiResponse(code = 404, message = "查询模式未找到"), @ApiResponse(code = 403, message = "只有管理员或用户自己能查询自己的用户信息"), }) UserDO findByKey(@PathVariable("key") @ApiParam(value = "查询关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "查询模式,可以是id或username或phone或email", required = true) String mode) {; @ResponseStatus(HttpStatus.CREATED) @RequestMapping(method = RequestMethod.POST) @ApiOperation(value = "创建用户,为用户发送验证邮件,等待用户激活,若24小时内未激活需要重新注册", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 409, message = "用户名已存在"), @ApiResponse(code = 400, message = "用户属性校验失败") }) void createUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{id}/avatar", method = RequestMethod.GET) @ApiOperation(value = "获取用户的头像图片", response = Byte.class) @ApiResponses(value = { @ApiResponse(code = 404, message = "文件不存在"), @ApiResponse(code = 400, message = "文件传输失败") }) void getUserAvatar(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response); @RequestMapping(value = "/{id}/activation", method = RequestMethod.GET) @ApiOperation(value = "用户激活,前置条件是用户已注册且在24小时内", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 401, message = "未注册或超时或激活码错误") }) void activate(@PathVariable("id") @ApiParam(value = "用户Id", required = true) Long id, @RequestParam("activationCode") @ApiParam(value = "激活码", required = true) String activationCode) {; @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 = 404, message = "用户属性校验失败"), @ApiResponse(code = 403, message = "只有管理员或用户自己能更新用户信息"), }) void updateUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{key}/password/reset_validation", method = RequestMethod.GET) @ApiOperation(value = "发送忘记密码的邮箱验证", notes = "属性可以是id,sername或email或手机号", response = UserDO.class) void forgetPassword(@PathVariable("key") @ApiParam(value = "关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "验证模式,可以是username或phone或email", required = true) String mode) {; @RequestMapping(value="/principles",method = RequestMethod.GET) String getPrinciples(@AuthenticationPrincipal JWTUser jwtUser); @RequestMapping(value = "/{id}/password", method = RequestMethod.PUT) @ApiOperation(value = "忘记密码后可以修改密码") void resetPassword(@PathVariable("id") Long id, @RequestParam("forgetPasswordCode") @ApiParam(value = "验证码", required = true) String forgetPasswordCode, @RequestParam("password") @ApiParam(value = "新密码", required = true) String password) {; @RequestMapping(value = "/{username}/duplication", method = RequestMethod.GET) @ApiOperation(value = "查询用户名是否重复", response = Boolean.class) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) boolean isUsernameDuplicated(@PathVariable("username") String username); @RequestMapping(method = RequestMethod.GET) @PreAuthorize("hasRole('ADMIN')") @ApiOperation(value = "分页查询用户信息", response = PageInfo.class, authorizations = {@Authorization("登录权限")}) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) PageInfo<UserDO> findAllUsers(@RequestParam("pageNum") @ApiParam(value = "页码,从1开始", defaultValue = "1") Integer pageNum, @RequestParam("pageSize") @ApiParam(value = "每页记录数", defaultValue = "5") Integer pageSize) {; } | @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.findByUsername(username) == null) { return false; } return true; } @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("登录权限")}) @ApiResponses(value = { @ApiResponse(code = 401, message = "未登录"), @ApiResponse(code = 404, message = "查询模式未找到"), @ApiResponse(code = 403, message = "只有管理员或用户自己能查询自己的用户信息"), }) UserDO findByKey(@PathVariable("key") @ApiParam(value = "查询关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "查询模式,可以是id或username或phone或email", required = true) String mode) {; @ResponseStatus(HttpStatus.CREATED) @RequestMapping(method = RequestMethod.POST) @ApiOperation(value = "创建用户,为用户发送验证邮件,等待用户激活,若24小时内未激活需要重新注册", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 409, message = "用户名已存在"), @ApiResponse(code = 400, message = "用户属性校验失败") }) void createUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{id}/avatar", method = RequestMethod.GET) @ApiOperation(value = "获取用户的头像图片", response = Byte.class) @ApiResponses(value = { @ApiResponse(code = 404, message = "文件不存在"), @ApiResponse(code = 400, message = "文件传输失败") }) void getUserAvatar(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response); @RequestMapping(value = "/{id}/activation", method = RequestMethod.GET) @ApiOperation(value = "用户激活,前置条件是用户已注册且在24小时内", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 401, message = "未注册或超时或激活码错误") }) void activate(@PathVariable("id") @ApiParam(value = "用户Id", required = true) Long id, @RequestParam("activationCode") @ApiParam(value = "激活码", required = true) String activationCode) {; @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 = 404, message = "用户属性校验失败"), @ApiResponse(code = 403, message = "只有管理员或用户自己能更新用户信息"), }) void updateUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{key}/password/reset_validation", method = RequestMethod.GET) @ApiOperation(value = "发送忘记密码的邮箱验证", notes = "属性可以是id,sername或email或手机号", response = UserDO.class) void forgetPassword(@PathVariable("key") @ApiParam(value = "关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "验证模式,可以是username或phone或email", required = true) String mode) {; @RequestMapping(value="/principles",method = RequestMethod.GET) String getPrinciples(@AuthenticationPrincipal JWTUser jwtUser); @RequestMapping(value = "/{id}/password", method = RequestMethod.PUT) @ApiOperation(value = "忘记密码后可以修改密码") void resetPassword(@PathVariable("id") Long id, @RequestParam("forgetPasswordCode") @ApiParam(value = "验证码", required = true) String forgetPasswordCode, @RequestParam("password") @ApiParam(value = "新密码", required = true) String password) {; @RequestMapping(value = "/{username}/duplication", method = RequestMethod.GET) @ApiOperation(value = "查询用户名是否重复", response = Boolean.class) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) boolean isUsernameDuplicated(@PathVariable("username") String username); @RequestMapping(method = RequestMethod.GET) @PreAuthorize("hasRole('ADMIN')") @ApiOperation(value = "分页查询用户信息", response = PageInfo.class, authorizations = {@Authorization("登录权限")}) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) PageInfo<UserDO> findAllUsers(@RequestParam("pageNum") @ApiParam(value = "页码,从1开始", defaultValue = "1") Integer pageNum, @RequestParam("pageSize") @ApiParam(value = "每页记录数", defaultValue = "5") Integer pageSize) {; } | @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("pageNum") @ApiParam(value = "页码,从1开始", defaultValue = "1") Integer pageNum, @RequestParam("pageSize") @ApiParam(value = "每页记录数", defaultValue = "5") Integer pageSize) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); log.info("Authentication:{}",authentication.getAuthorities()); return service.findAll(pageNum, pageSize); } @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("登录权限")}) @ApiResponses(value = { @ApiResponse(code = 401, message = "未登录"), @ApiResponse(code = 404, message = "查询模式未找到"), @ApiResponse(code = 403, message = "只有管理员或用户自己能查询自己的用户信息"), }) UserDO findByKey(@PathVariable("key") @ApiParam(value = "查询关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "查询模式,可以是id或username或phone或email", required = true) String mode) {; @ResponseStatus(HttpStatus.CREATED) @RequestMapping(method = RequestMethod.POST) @ApiOperation(value = "创建用户,为用户发送验证邮件,等待用户激活,若24小时内未激活需要重新注册", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 409, message = "用户名已存在"), @ApiResponse(code = 400, message = "用户属性校验失败") }) void createUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{id}/avatar", method = RequestMethod.GET) @ApiOperation(value = "获取用户的头像图片", response = Byte.class) @ApiResponses(value = { @ApiResponse(code = 404, message = "文件不存在"), @ApiResponse(code = 400, message = "文件传输失败") }) void getUserAvatar(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response); @RequestMapping(value = "/{id}/activation", method = RequestMethod.GET) @ApiOperation(value = "用户激活,前置条件是用户已注册且在24小时内", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 401, message = "未注册或超时或激活码错误") }) void activate(@PathVariable("id") @ApiParam(value = "用户Id", required = true) Long id, @RequestParam("activationCode") @ApiParam(value = "激活码", required = true) String activationCode) {; @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 = 404, message = "用户属性校验失败"), @ApiResponse(code = 403, message = "只有管理员或用户自己能更新用户信息"), }) void updateUser(@RequestBody @Valid @ApiParam(value = "用户信息,用户的用户名、密码、昵称、邮箱不可为空", required = true) UserDO user, BindingResult result) {; @RequestMapping(value = "/{key}/password/reset_validation", method = RequestMethod.GET) @ApiOperation(value = "发送忘记密码的邮箱验证", notes = "属性可以是id,sername或email或手机号", response = UserDO.class) void forgetPassword(@PathVariable("key") @ApiParam(value = "关键字", required = true) String key, @RequestParam("mode") @ApiParam(value = "验证模式,可以是username或phone或email", required = true) String mode) {; @RequestMapping(value="/principles",method = RequestMethod.GET) String getPrinciples(@AuthenticationPrincipal JWTUser jwtUser); @RequestMapping(value = "/{id}/password", method = RequestMethod.PUT) @ApiOperation(value = "忘记密码后可以修改密码") void resetPassword(@PathVariable("id") Long id, @RequestParam("forgetPasswordCode") @ApiParam(value = "验证码", required = true) String forgetPasswordCode, @RequestParam("password") @ApiParam(value = "新密码", required = true) String password) {; @RequestMapping(value = "/{username}/duplication", method = RequestMethod.GET) @ApiOperation(value = "查询用户名是否重复", response = Boolean.class) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) boolean isUsernameDuplicated(@PathVariable("username") String username); @RequestMapping(method = RequestMethod.GET) @PreAuthorize("hasRole('ADMIN')") @ApiOperation(value = "分页查询用户信息", response = PageInfo.class, authorizations = {@Authorization("登录权限")}) @ApiResponses(value = {@ApiResponse(code = 401, message = "未登录")}) PageInfo<UserDO> findAllUsers(@RequestParam("pageNum") @ApiParam(value = "页码,从1开始", defaultValue = "1") Integer pageNum, @RequestParam("pageSize") @ApiParam(value = "每页记录数", defaultValue = "5") Integer pageSize) {; } | @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.replace("§", "\\S "); output = output.replace("&", "\\&"); output = output.replace("%", "\\%"); output = output.replace("$", "\\$"); output = output.replace("#", "\\#"); output = output.replace("_", "\\_"); output = output.replace("{", "\\{"); output = output.replace("}", "\\}"); output = output.replace("~", "\\textasciitilde "); output = output.replace("^", "\\textasciicircum "); return output; } String escape(final String input); } | @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 ")); assertThat(tool.escape("&"), is("\\&")); assertThat(tool.escape("%"), is("\\%")); assertThat(tool.escape("$"), is("\\$")); assertThat(tool.escape("#"), is("\\#")); assertThat(tool.escape("_"), is("\\_")); assertThat(tool.escape("{"), is("\\{")); assertThat(tool.escape("}"), is("\\}")); assertThat(tool.escape("~"), is("\\textasciitilde ")); assertThat(tool.escape("^"), is("\\textasciicircum ")); }
@Test public void testMultipleCharacters() { final String expected = "!\"\\S '\\$\\%\\&/()=¿?[]\\{\\}\\euro @\\textasciicircum \\textasciitilde \\textbackslash \\#ßôâéè\\textless \\textgreater "; assertThat(tool.escape("!\"§'$%&/()=¿?[]{}€@^~\\#ßôâéè<>"), is(expected)); } |
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 template); final String populateFrom(final LatexContext context); } | @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 void processNullContext() { new LatexTemplate("").populateFrom(null); fail(); }
@Test(expected = LatexTemplateProcessingException.class) public void processIncompleteTemplate() { LatexTemplate template = new LatexTemplate("${incompleteTemplate"); template.populateFrom(new LatexContext()); fail(); } |
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().iterator(); } void setCollection(DBCollection col); Iterator<DBObject> simpleAggregation(); Iterator<DBObject> compoundAggregation(); Iterator<DBObject> sumPrices(); Iterator<DBObject> averagePrices(); Iterator<DBObject> addToSet(); Iterator<DBObject> push(); Iterator<DBObject> maxPrice(); Iterator<DBObject> doubleGroupStages(); Iterator<DBObject> project(); Iterator<DBObject> match(); Iterator<DBObject> sort(); Iterator<DBObject> limitAndSkip(); Iterator<DBObject> unwind(); Iterator<DBObject> doubleUnwind(); } | @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))); else if(i < 95 ) collection.insert(new BasicDBObject("manufacturer", vals.get(2))); else collection.insert(new BasicDBObject("manufacturer", vals.get(3))); } Iterator<DBObject> iter = agg.simpleAggregation(); while(iter.hasNext()) { System.out.println(iter.next()); } collection.drop(); } |
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 = new BasicDBObjectBuilder(); project.push("$project"); project.add("_id", 0); project.add("city", "$_id"); project.add("population", 1); project.pop(); BasicDBObjectBuilder sort = new BasicDBObjectBuilder(); sort.push("$sort"); sort.add("population", -1); sort.pop(); return col.aggregate(match.get(), group.get(), project.get(), sort.get()).results().iterator(); } void setCollection(DBCollection col); Iterator<DBObject> simpleAggregation(); Iterator<DBObject> compoundAggregation(); Iterator<DBObject> sumPrices(); Iterator<DBObject> averagePrices(); Iterator<DBObject> addToSet(); Iterator<DBObject> push(); Iterator<DBObject> maxPrice(); Iterator<DBObject> doubleGroupStages(); Iterator<DBObject> project(); Iterator<DBObject> match(); Iterator<DBObject> sort(); Iterator<DBObject> limitAndSkip(); Iterator<DBObject> unwind(); Iterator<DBObject> doubleUnwind(); } | @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 project = new BasicDBObjectBuilder(); project.push("$project"); project.add("_id", 0); project.add("city", "$_id"); project.add("population", 1); project.pop(); BasicDBObjectBuilder sort = new BasicDBObjectBuilder(); sort.push("$sort"); sort.add("population", -1); sort.pop(); BasicDBObject skip = new BasicDBObject("$skip", 10); BasicDBObject limit = new BasicDBObject("$limit", 5); return col.aggregate(match.get(), group.get(), project.get(), sort.get(), skip, limit).results().iterator(); } void setCollection(DBCollection col); Iterator<DBObject> simpleAggregation(); Iterator<DBObject> compoundAggregation(); Iterator<DBObject> sumPrices(); Iterator<DBObject> averagePrices(); Iterator<DBObject> addToSet(); Iterator<DBObject> push(); Iterator<DBObject> maxPrice(); Iterator<DBObject> doubleGroupStages(); Iterator<DBObject> project(); Iterator<DBObject> match(); Iterator<DBObject> sort(); Iterator<DBObject> limitAndSkip(); Iterator<DBObject> unwind(); Iterator<DBObject> doubleUnwind(); } | @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 = new BasicDBObjectBuilder(); sort.push("$sort"); sort.add("count", -1); sort.pop(); BasicDBObject limit = new BasicDBObject("$limit", 10); BasicDBObjectBuilder project = new BasicDBObjectBuilder(); project.push("$project"); project.add("_id", 0); project.add("tag", "$_id"); project.add("count", 1); return col.aggregate(unwind, group.get(), sort.get(), limit, project.get()).results().iterator(); } void setCollection(DBCollection col); Iterator<DBObject> simpleAggregation(); Iterator<DBObject> compoundAggregation(); Iterator<DBObject> sumPrices(); Iterator<DBObject> averagePrices(); Iterator<DBObject> addToSet(); Iterator<DBObject> push(); Iterator<DBObject> maxPrice(); Iterator<DBObject> doubleGroupStages(); Iterator<DBObject> project(); Iterator<DBObject> match(); Iterator<DBObject> sort(); Iterator<DBObject> limitAndSkip(); Iterator<DBObject> unwind(); Iterator<DBObject> doubleUnwind(); } | @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", "$sizes"); group.add("color", "$colors"); group.pop(); group.push("count"); group.add("$sum", 1); group.pop(); group.pop(); return col.aggregate(unwindSizes, unwindColors, group.get()).results().iterator(); } void setCollection(DBCollection col); Iterator<DBObject> simpleAggregation(); Iterator<DBObject> compoundAggregation(); Iterator<DBObject> sumPrices(); Iterator<DBObject> averagePrices(); Iterator<DBObject> addToSet(); Iterator<DBObject> push(); Iterator<DBObject> maxPrice(); Iterator<DBObject> doubleGroupStages(); Iterator<DBObject> project(); Iterator<DBObject> match(); Iterator<DBObject> sort(); Iterator<DBObject> limitAndSkip(); Iterator<DBObject> unwind(); Iterator<DBObject> doubleUnwind(); } | @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","oragne","red"})); inventoryCollection.insert(new BasicDBObject("name","T-Shirt").append("sizes",new String[] {"Small", "Medium","Large", "X-Large"}).append("colors", new String[] {"navy","black","oragne","red"})); inventoryCollection.insert(new BasicDBObject("name","Chino Pants").append("sizes",new String[] {"32x32", "31x30","36x32"}).append("colors", new String[] {"navy","white","oragne","violet"})); Iterator<DBObject> iter = agg.doubleUnwind(); while(iter.hasNext()) { System.out.println(iter.next()); } inventoryCollection.drop(); } |
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("$sum", 1); builder.pop(); builder.pop(); return col.aggregate(builder.get()).results().iterator(); } void setCollection(DBCollection col); Iterator<DBObject> simpleAggregation(); Iterator<DBObject> compoundAggregation(); Iterator<DBObject> sumPrices(); Iterator<DBObject> averagePrices(); Iterator<DBObject> addToSet(); Iterator<DBObject> push(); Iterator<DBObject> maxPrice(); Iterator<DBObject> doubleGroupStages(); Iterator<DBObject> project(); Iterator<DBObject> match(); Iterator<DBObject> sort(); Iterator<DBObject> limitAndSkip(); Iterator<DBObject> unwind(); Iterator<DBObject> doubleUnwind(); } | @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(RandomUtils.nextInt(categories.size())))); else if(i < 75 ) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(1)).append("category", categories.get(RandomUtils.nextInt(categories.size())))); else if(i < 95 ) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(2)).append("category", categories.get(RandomUtils.nextInt(categories.size())))); else collection.insert(new BasicDBObject("manufacturer", manufacturers.get(3)).append("category", categories.get(RandomUtils.nextInt(categories.size())))); } Iterator<DBObject> iter = agg.compoundAggregation(); while(iter.hasNext()) { System.out.println(iter.next()); } collection.drop(); } |
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().iterator(); } void setCollection(DBCollection col); Iterator<DBObject> simpleAggregation(); Iterator<DBObject> compoundAggregation(); Iterator<DBObject> sumPrices(); Iterator<DBObject> averagePrices(); Iterator<DBObject> addToSet(); Iterator<DBObject> push(); Iterator<DBObject> maxPrice(); Iterator<DBObject> doubleGroupStages(); Iterator<DBObject> project(); Iterator<DBObject> match(); Iterator<DBObject> sort(); Iterator<DBObject> limitAndSkip(); Iterator<DBObject> unwind(); Iterator<DBObject> doubleUnwind(); } | @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(prices.size())))); else if(i < 75 ) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(1)).append("price", prices.get(RandomUtils.nextInt(prices.size())))); else if(i < 95 ) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(2)).append("price", prices.get(RandomUtils.nextInt(prices.size())))); else collection.insert(new BasicDBObject("manufacturer", manufacturers.get(3)).append("price", prices.get(RandomUtils.nextInt(prices.size())))); } Iterator<DBObject> iter = agg.sumPrices(); while(iter.hasNext()) { System.out.println(iter.next()); } collection.drop(); } |
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().iterator(); } void setCollection(DBCollection col); Iterator<DBObject> simpleAggregation(); Iterator<DBObject> compoundAggregation(); Iterator<DBObject> sumPrices(); Iterator<DBObject> averagePrices(); Iterator<DBObject> addToSet(); Iterator<DBObject> push(); Iterator<DBObject> maxPrice(); Iterator<DBObject> doubleGroupStages(); Iterator<DBObject> project(); Iterator<DBObject> match(); Iterator<DBObject> sort(); Iterator<DBObject> limitAndSkip(); Iterator<DBObject> unwind(); Iterator<DBObject> doubleUnwind(); } | @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())))); else if(i < 75 ) collection.insert(new BasicDBObject("category", categories.get(1)).append("price", prices.get(RandomUtils.nextInt(prices.size())))); else if(i < 95 ) collection.insert(new BasicDBObject("category", categories.get(2)).append("price", prices.get(RandomUtils.nextInt(prices.size())))); else collection.insert(new BasicDBObject("category", categories.get(3)).append("price", prices.get(RandomUtils.nextInt(prices.size())))); } Iterator<DBObject> iter = agg.averagePrices(); while(iter.hasNext()) { System.out.println(iter.next()); } collection.drop(); } |
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(); return col.aggregate(builder.get()).results().iterator(); } void setCollection(DBCollection col); Iterator<DBObject> simpleAggregation(); Iterator<DBObject> compoundAggregation(); Iterator<DBObject> sumPrices(); Iterator<DBObject> averagePrices(); Iterator<DBObject> addToSet(); Iterator<DBObject> push(); Iterator<DBObject> maxPrice(); Iterator<DBObject> doubleGroupStages(); Iterator<DBObject> project(); Iterator<DBObject> match(); Iterator<DBObject> sort(); Iterator<DBObject> limitAndSkip(); Iterator<DBObject> unwind(); Iterator<DBObject> doubleUnwind(); } | @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(RandomUtils.nextInt(categories.size())))); else if(i < 75 ) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(1)).append("category", categories.get(RandomUtils.nextInt(categories.size())))); else if(i < 95 ) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(2)).append("category", categories.get(RandomUtils.nextInt(categories.size())))); else collection.insert(new BasicDBObject("manufacturer", manufacturers.get(3)).append("category", categories.get(RandomUtils.nextInt(categories.size())))); } Iterator<DBObject> iter = agg.addToSet(); while(iter.hasNext()) { System.out.println(iter.next()); } collection.drop(); } |
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.aggregate(builder.get()).results().iterator(); } void setCollection(DBCollection col); Iterator<DBObject> simpleAggregation(); Iterator<DBObject> compoundAggregation(); Iterator<DBObject> sumPrices(); Iterator<DBObject> averagePrices(); Iterator<DBObject> addToSet(); Iterator<DBObject> push(); Iterator<DBObject> maxPrice(); Iterator<DBObject> doubleGroupStages(); Iterator<DBObject> project(); Iterator<DBObject> match(); Iterator<DBObject> sort(); Iterator<DBObject> limitAndSkip(); Iterator<DBObject> unwind(); Iterator<DBObject> doubleUnwind(); } | @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(RandomUtils.nextInt(categories.size())))); else if(i < 75 ) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(1)).append("category", categories.get(RandomUtils.nextInt(categories.size())))); else if(i < 95 ) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(2)).append("category", categories.get(RandomUtils.nextInt(categories.size())))); else collection.insert(new BasicDBObject("manufacturer", manufacturers.get(3)).append("category", categories.get(RandomUtils.nextInt(categories.size())))); } Iterator<DBObject> iter = agg.push(); while(iter.hasNext()) { System.out.println(iter.next()); } collection.drop(); } |
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.aggregate(builder.get()).results().iterator(); } void setCollection(DBCollection col); Iterator<DBObject> simpleAggregation(); Iterator<DBObject> compoundAggregation(); Iterator<DBObject> sumPrices(); Iterator<DBObject> averagePrices(); Iterator<DBObject> addToSet(); Iterator<DBObject> push(); Iterator<DBObject> maxPrice(); Iterator<DBObject> doubleGroupStages(); Iterator<DBObject> project(); Iterator<DBObject> match(); Iterator<DBObject> sort(); Iterator<DBObject> limitAndSkip(); Iterator<DBObject> unwind(); Iterator<DBObject> doubleUnwind(); } | @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(prices.size())))); else if(i < 75 ) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(1)).append("price", prices.get(RandomUtils.nextInt(prices.size())))); else if(i < 95 ) collection.insert(new BasicDBObject("manufacturer", manufacturers.get(2)).append("price", prices.get(RandomUtils.nextInt(prices.size())))); else collection.insert(new BasicDBObject("manufacturer", manufacturers.get(3)).append("price", prices.get(RandomUtils.nextInt(prices.size())))); } Iterator<DBObject> iter = agg.maxPrice(); while(iter.hasNext()) { System.out.println(iter.next()); } collection.drop(); } |
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"); group_1.pop(); group_1.pop(); BasicDBObjectBuilder group_2 = new BasicDBObjectBuilder(); group_2.push("$group"); group_2.add("_id", "$_id.class_id"); group_2.push("average"); group_2.add("$avg", "$average"); group_2.pop(); group_2.pop(); return col.aggregate(group_1.get(), group_2.get()).results().iterator(); } void setCollection(DBCollection col); Iterator<DBObject> simpleAggregation(); Iterator<DBObject> compoundAggregation(); Iterator<DBObject> sumPrices(); Iterator<DBObject> averagePrices(); Iterator<DBObject> addToSet(); Iterator<DBObject> push(); Iterator<DBObject> maxPrice(); Iterator<DBObject> doubleGroupStages(); Iterator<DBObject> project(); Iterator<DBObject> match(); Iterator<DBObject> sort(); Iterator<DBObject> limitAndSkip(); Iterator<DBObject> unwind(); Iterator<DBObject> doubleUnwind(); } | @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(new BasicDBObject("class_id", class_id[cls]).append("student_id", student_id[student] ).append("score", RandomUtils.nextInt(100))); } } Iterator<DBObject> iter = agg.doubleGroupStages(); while(iter.hasNext()) { System.out.println(iter.next()); } grades.drop(); } |
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.push("price"); builder.add("$multiply", new Object[] { "$price", 10 }); builder.pop(); builder.pop(); builder.add("item", "$name"); builder.pop(); return col.aggregate(builder.get()).results().iterator(); } void setCollection(DBCollection col); Iterator<DBObject> simpleAggregation(); Iterator<DBObject> compoundAggregation(); Iterator<DBObject> sumPrices(); Iterator<DBObject> averagePrices(); Iterator<DBObject> addToSet(); Iterator<DBObject> push(); Iterator<DBObject> maxPrice(); Iterator<DBObject> doubleGroupStages(); Iterator<DBObject> project(); Iterator<DBObject> match(); Iterator<DBObject> sort(); Iterator<DBObject> limitAndSkip(); Iterator<DBObject> unwind(); Iterator<DBObject> doubleUnwind(); } | @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("$addToSet", "$_id"); group.pop(); group.pop(); return col.aggregate(match.get(), group.get()).results().iterator(); } void setCollection(DBCollection col); Iterator<DBObject> simpleAggregation(); Iterator<DBObject> compoundAggregation(); Iterator<DBObject> sumPrices(); Iterator<DBObject> averagePrices(); Iterator<DBObject> addToSet(); Iterator<DBObject> push(); Iterator<DBObject> maxPrice(); Iterator<DBObject> doubleGroupStages(); Iterator<DBObject> project(); Iterator<DBObject> match(); Iterator<DBObject> sort(); Iterator<DBObject> limitAndSkip(); Iterator<DBObject> unwind(); Iterator<DBObject> doubleUnwind(); } | @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, returnType); if (status == null) { return -1; } if (V1STATUS_SUCCESS.equals(status.getStatus())) return 0; if (V1STATUS_REASON_NONZEROEXITCODE.equals(status.getReason())) { V1StatusDetails details = status.getDetails(); if (details != null) { List<V1StatusCause> causes = details.getCauses(); if (causes != null) { for (V1StatusCause cause : causes) { if (V1STATUS_CAUSE_REASON_EXITCODE.equals(cause.getReason())) { try { return Integer.parseInt(cause.getMessage()); } catch (NumberFormatException nfe) { log.error("Error parsing exit code from status channel response", nfe); } } } } } } } catch (Throwable t) { log.error("Error parsing exit code from status channel response", t); } return -1; } Exec(); Exec(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); ExecutionBuilder newExecutionBuilder(String namespace, String name, String[] command); Process exec(String namespace, String name, String[] command, boolean stdin); Process exec(V1Pod pod, String[] command, boolean stdin); Process exec(String namespace, String name, String[] command, boolean stdin, boolean tty); Process exec(V1Pod pod, String[] command, boolean stdin, boolean tty); Process exec(V1Pod pod, String[] command, String container, boolean stdin, boolean tty); Process exec(
String namespace, String name, String[] command, String container, boolean stdin, boolean tty); } | @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(StandardCharsets.UTF_8)); int exitCode = Exec.parseExitCode(client, inputStream); assertEquals(1, exitCode); }
@Test public void testExit126() { InputStream inputStream = new ByteArrayInputStream(OUTPUT_EXIT126.getBytes(StandardCharsets.UTF_8)); int exitCode = Exec.parseExitCode(client, inputStream); assertEquals(126, exitCode); }
@Test public void testIncompleteData1() { InputStream inputStream = new ByteArrayInputStream(BAD_OUTPUT_INCOMPLETE_MSG1.getBytes(StandardCharsets.UTF_8)); int exitCode = Exec.parseExitCode(client, inputStream); assertEquals(-1, exitCode); }
@Test public void testNonZeroBadIntExit() { InputStream inputStream = new ByteArrayInputStream(OUTPUT_EXIT_BAD_INT.getBytes(StandardCharsets.UTF_8)); int exitCode = Exec.parseExitCode(client, inputStream); assertEquals(-1, exitCode); } |
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.waitingForAddQueue.offer(entry); } DefaultDelayingQueue(ExecutorService waitingWorker); DefaultDelayingQueue(); void addAfter(T item, Duration duration); static Duration heartBeatInterval; } | @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(third, Duration.ofMillis(250)); assertTrue(waitForWaitingQueueToFill(queue)); assertTrue("should not have added", queue.length() == 0); Thread.sleep(2000L); assertTrue(waitForAdded(queue, 3)); String actualFirst = queue.get(); assertEquals(actualFirst, third); String actualSecond = queue.get(); assertEquals(actualSecond, second); String actualThird = queue.get(); assertEquals(actualThird, first); }
@Test public void testSimpleDelayingQueue() throws Exception { DefaultDelayingQueue<String> queue = new DefaultDelayingQueue<>(); queue.addAfter("foo", Duration.ofMillis(50)); assertTrue(waitForWaitingQueueToFill(queue)); assertTrue(queue.length() == 0); Thread.sleep(60L); assertTrue(waitForAdded(queue, 1)); String item = queue.get(); queue.done(item); Thread.sleep(10 * 1000L); assertTrue(queue.length() == 0); }
@Test public void testDeduping() throws Exception { DefaultDelayingQueue<String> queue = new DefaultDelayingQueue<>(); String item = "foo"; queue.addAfter(item, Duration.ofMillis(50)); assertTrue(waitForWaitingQueueToFill(queue)); queue.addAfter(item, Duration.ofMillis(70)); assertTrue(waitForWaitingQueueToFill(queue)); assertTrue("should not have added", queue.length() == 0); Thread.sleep(60L); assertTrue(waitForAdded(queue, 1)); item = queue.get(); queue.done(item); Thread.sleep(20L); assertTrue("should not have added", queue.length() == 0); queue.addAfter(item, Duration.ofMillis(50)); queue.addAfter(item, Duration.ofMillis(30)); assertTrue(waitForWaitingQueueToFill(queue)); assertTrue("should not have added", queue.length() == 0); Thread.sleep(40L); assertTrue(waitForAdded(queue, 1)); item = queue.get(); queue.done(item); Thread.sleep(1L); assertTrue("should not have added", queue.length() == 0); } |
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); @Override void forget(T item); @Override int numRequeues(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("one")); assertEquals(Duration.ofMillis(5), rateLimiter.when("one")); assertEquals(Duration.ofMillis(5), rateLimiter.when("one")); assertEquals(Duration.ofSeconds(3), rateLimiter.when("one")); assertEquals(Duration.ofSeconds(3), rateLimiter.when("one")); assertEquals(5, rateLimiter.numRequeues("one")); assertEquals(Duration.ofMillis(5), rateLimiter.when("two")); assertEquals(Duration.ofMillis(5), rateLimiter.when("two")); assertEquals(2, rateLimiter.numRequeues("two")); rateLimiter.forget("one"); assertEquals(0, rateLimiter.numRequeues("one")); assertEquals(Duration.ofMillis(5), rateLimiter.when("one")); } |
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); @SafeVarargs @SuppressWarnings("varargs") MaxOfRateLimiter(RateLimiter<T>... rateLimiters); @Override Duration when(T item); @Override void forget(T item); @Override int numRequeues(T item); } | @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 < 20; i++) { rateLimiter.when("one"); } assertEquals(Duration.ofSeconds(1000), rateLimiter.when("one")); assertEquals(Duration.ofSeconds(1000), rateLimiter.when("one")); for (int i = 0; i < 75; i++) { rateLimiter.when("one"); } assertTrue(rateLimiter.when("one").getSeconds() > 0); assertTrue(rateLimiter.when("two").getSeconds() > 0); } |
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 forget(T item); @Override int numRequeues(T item); } | @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 = Duration.ofMinutes(10); Duration diff = waitDuration.minus(expectDuration); assertTrue(diff.isZero() || (diff.isNegative() && !diff.plusSeconds(1).isNegative())); waitDuration = rateLimiter.when("one"); expectDuration = Duration.ofMinutes(20); diff = waitDuration.minus(expectDuration); assertTrue(diff.isZero() || (diff.isNegative() && !diff.plusSeconds(1).isNegative())); }
@Test public void testBucketRateLimiterTokenAdded() throws InterruptedException { RateLimiter<String> rateLimiter = new BucketRateLimiter<>(2, 1, Duration.ofSeconds(2)); assertEquals(Duration.ZERO, rateLimiter.when("one")); assertEquals(Duration.ZERO, rateLimiter.when("one")); Duration waitDuration = rateLimiter.when("one"); assertTrue(waitDuration.getSeconds() > 0); Thread.sleep(4000); assertEquals(Duration.ZERO, rateLimiter.when("two")); waitDuration = rateLimiter.when("two"); assertTrue(waitDuration.getSeconds() > 0); } |
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 Duration when(T item); @Override void forget(T item); @Override int numRequeues(T item); } | @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(Duration.ofMillis(4), rateLimiter.when("one")); assertEquals(Duration.ofMillis(8), rateLimiter.when("one")); assertEquals(Duration.ofMillis(16), rateLimiter.when("one")); assertEquals(5, rateLimiter.numRequeues("one")); assertEquals(Duration.ofMillis(1), rateLimiter.when("two")); assertEquals(Duration.ofMillis(2), rateLimiter.when("two")); assertEquals(2, rateLimiter.numRequeues("two")); rateLimiter.forget("one"); assertEquals(0, rateLimiter.numRequeues("one")); assertEquals(Duration.ofMillis(1), rateLimiter.when("one")); } |
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, Duration maxDelay); @Override Duration when(T item); @Override void forget(T item); @Override int numRequeues(T item); } | @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 = 0; i < 1000; i++) { rateLimiter.when("overflow1"); } assertEquals(Duration.ofSeconds(1000), rateLimiter.when("overflow1")); rateLimiter = new ItemExponentialFailureRateLimiter<>(Duration.ofMinutes(1), Duration.ofHours(1000)); for (int i = 0; i < 2; i++) { rateLimiter.when("two"); } assertEquals(Duration.ofMinutes(4), rateLimiter.when("two")); for (int i = 0; i < 1000; i++) { rateLimiter.when("overflow2"); } assertEquals(Duration.ofHours(1000), rateLimiter.when("overflow2")); }
@Test public void testNegativeBaseDelay() { 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 = 0; i < 1000; i++) { rateLimiter.when("overflow1"); } assertTrue(rateLimiter.when("overflow1").isNegative()); }
@Test public void testNegativeMaxDelay() { RateLimiter<String> rateLimiter = new ItemExponentialFailureRateLimiter<>(Duration.ofMillis(1), Duration.ofSeconds(-1000)); assertEquals(Duration.ofSeconds(-1000), rateLimiter.when("one")); assertEquals(Duration.ofSeconds(-1000), rateLimiter.when("one")); assertEquals(Duration.ofSeconds(-1000), rateLimiter.when("one")); assertEquals(Duration.ofSeconds(-1000), rateLimiter.when("one")); } |
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 when(T item); @Override void forget(T item); @Override int numRequeues(T item); } | @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.ofSeconds(10), rateLimiter.when("one")); rateLimiter = new ItemFastSlowRateLimiter<>(Duration.ofMillis(5), Duration.ofSeconds(10), 0); assertEquals(Duration.ofSeconds(10), rateLimiter.when("two")); assertEquals(Duration.ofSeconds(10), rateLimiter.when("two")); assertEquals(Duration.ofSeconds(10), rateLimiter.when("two")); } |
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(Reader reader, Class<T> clazz); static List<Object> loadAll(String content); static List<Object> loadAll(File f); static List<Object> loadAll(Reader reader); static String dump(Object object); static void dump(Object object, Writer writer); static String dumpAll(Iterator<? extends KubernetesType> data); static void dumpAll(Iterator<? extends KubernetesType> data, Writer output); static org.yaml.snakeyaml.Yaml getSnakeYaml(); @Deprecated static void addModelMap(String apiGroupVersion, String kind, Class<?> clazz); } | @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(obj); assertEquals("foo", metadata.getName()); assertEquals(className, obj.getClass().getSimpleName()); } catch (Exception ex) { assertNull("Unexpected exception: " + ex.toString(), ex); } } } |
LeaderElectingController implements Controller { public LeaderElectingController(LeaderElector leaderElector, Controller delegateController) { this.delegateController = delegateController; this.leaderElector = leaderElector; } LeaderElectingController(LeaderElector leaderElector, Controller delegateController); @Override void shutdown(); @Override void run(); } | @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 -> { record.set(invocationOnMock.getArgument(0)); return true; }) .when(mockLock) .create(any()); doReturn(false).when(mockLock).update(any()); LeaderElectingController leaderElectingController = new LeaderElectingController( new LeaderElector( new LeaderElectionConfig( mockLock, Duration.ofMillis(300), Duration.ofMillis(200), Duration.ofMillis(100))), mockController); Thread controllerThread = new Thread(leaderElectingController::run); controllerThread.start(); cooldown(); controllerThread.interrupt(); verify(mockLock, times(1)).create(any()); verify(mockLock, atLeastOnce()).update(any()); verify(mockController, times(1)).run(); verify(mockController, times(1)).shutdown(); } |
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(Supplier[]::new)); controller.setName(this.controllerName); controller.setWorkerCount(this.workerCount); controller.setWorkerThreadPool( Executors.newScheduledThreadPool( this.workerCount, Controllers.namedControllerThreadFactory(this.controllerName))); controller.setReconciler(this.reconciler); return controller; } DefaultControllerBuilder(); DefaultControllerBuilder(SharedInformerFactory informerFactory); DefaultControllerBuilder watch(
Function<WorkQueue<Request>, ControllerWatch<ApiType>> controllerWatchGetter); DefaultControllerBuilder withName(String controllerName); DefaultControllerBuilder withWorkQueue(RateLimitingQueue<Request> workQueue); DefaultControllerBuilder withReadyFunc(Supplier<Boolean> readyFunc); DefaultControllerBuilder withWorkerCount(int workerCount); DefaultControllerBuilder withReconciler(Reconciler reconciler); Controller build(); } | @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(); @Override V1Node execute(); } | @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("fieldSelector", equalTo("spec.nodeName=node1")) .willReturn(aResponse().withStatus(200).withBody("{}"))); V1Node node = new KubectlDrain().apiClient(apiClient).name("node1").execute(); wireMockRule.verify(1, patchRequestedFor(urlPathEqualTo("/api/v1/nodes/node1"))); wireMockRule.verify(1, getRequestedFor(urlPathEqualTo("/api/v1/pods"))); assertEquals("node1", node.getMetadata().getName()); }
@Test public void testDrainNodePods() 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("fieldSelector", equalTo("spec.nodeName=node1")) .willReturn( aResponse() .withStatus(200) .withBody(new String(Files.readAllBytes(Paths.get(POD_LIST_API)))))); wireMockRule.stubFor( delete(urlPathEqualTo("/api/v1/namespaces/mssql/pods/mssql-75b8b44f6b-znftp")) .willReturn(aResponse().withStatus(200).withBody("{}"))); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/namespaces/mssql/pods/mssql-75b8b44f6b-znftp")) .willReturn(aResponse().withStatus(404).withBody("{}"))); V1Node node = new KubectlDrain().apiClient(apiClient).name("node1").execute(); wireMockRule.verify(1, patchRequestedFor(urlPathEqualTo("/api/v1/nodes/node1"))); wireMockRule.verify(1, getRequestedFor(urlPathEqualTo("/api/v1/pods"))); wireMockRule.verify( 1, deleteRequestedFor(urlPathEqualTo("/api/v1/namespaces/mssql/pods/mssql-75b8b44f6b-znftp"))); wireMockRule.verify( 1, getRequestedFor(urlPathEqualTo("/api/v1/namespaces/mssql/pods/mssql-75b8b44f6b-znftp"))); assertEquals("node1", node.getMetadata().getName()); assertEquals(0, findUnmatchedRequests().size()); } |
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 T loadAs(Reader reader, Class<T> clazz); static List<Object> loadAll(String content); static List<Object> loadAll(File f); static List<Object> loadAll(Reader reader); static String dump(Object object); static void dump(Object object, Writer writer); static String dumpAll(Iterator<? extends KubernetesType> data); static void dumpAll(Iterator<? extends KubernetesType> data, Writer output); static org.yaml.snakeyaml.Yaml getSnakeYaml(); @Deprecated static void addModelMap(String apiGroupVersion, String kind, Class<?> clazz); } | @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 i = 0; i < kinds.length; i++) { String className = classNames[i]; try { Object obj = list.get(i); Method m = obj.getClass().getMethod("getMetadata"); V1ObjectMeta metadata = (V1ObjectMeta) m.invoke(obj); assertEquals("foo", metadata.getName()); assertEquals(className, obj.getClass().getSimpleName()); } catch (Exception ex) { assertNull("Unexpected exception: " + ex.toString(), ex); } } } |
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> clazz); static T loadAs(Reader reader, Class<T> clazz); static List<Object> loadAll(String content); static List<Object> loadAll(File f); static List<Object> loadAll(Reader reader); static String dump(Object object); static void dump(Object object, Writer writer); static String dumpAll(Iterator<? extends KubernetesType> data); static void dumpAll(Iterator<? extends KubernetesType> data, Writer output); static org.yaml.snakeyaml.Yaml getSnakeYaml(); @Deprecated static void addModelMap(String apiGroupVersion, String kind, Class<?> clazz); } | @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 integer, string expected.", stringPort.getTargetPort().isInteger()); assertEquals("test", stringPort.getTargetPort().getStrValue()); assertTrue( "Target port for 'intPort' was parsed to a string, integer expected.", intPort.getTargetPort().isInteger()); assertEquals(1L, (long) intPort.getTargetPort().getIntValue()); } catch (Exception ex) { assertNull("Unexpected exception: " + ex.toString(), ex); } }
@Test public void testLoadBytes() { try { String strInput = "data:\n hello: aGVsbG8="; V1Secret secret = Yaml.loadAs(strInput, V1Secret.class); assertEquals( "Incorrect value loaded for Base64 encoded secret", "hello", new String(secret.getData().get("hello"), UTF_8)); } catch (Exception ex) { assertNull("Unexpected exception: " + ex.toString(), ex); } }
@Test public void testDateTime() { try { String strInput = "apiVersion: v1\n" + "kind: Pod\n" + "metadata:\n" + " creationTimestamp: 2018-09-06T15:12:24Z"; V1Pod pod = Yaml.loadAs(strInput, V1Pod.class); assertEquals( "Incorrect value loaded for creationTimestamp", "2018-09-06T15:12:24.000Z", new String(pod.getMetadata().getCreationTimestamp().toString().getBytes(), UTF_8)); } catch (Exception ex) { assertNull("Unexpected exception: " + ex.toString(), ex); } } |
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 KeyManager[] keyManagers = SSLUtils.keyManagers(certificate, key, algo, "", null, null); client.setKeyManagers(keyManagers); } catch (NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException | KeyStoreException | InvalidKeySpecException | IOException e) { log.warn("Could not create key manager for Client Certificate authentication.", e); throw new RuntimeException(e); } } ClientCertificateAuthentication(final byte[] certificate, final byte[] key); @Override void provide(ApiClient client); } | @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); }
@Test(expected = RuntimeException.class) public void testInvalidCertificates() { final ApiClient client = new ApiClient(); new ClientCertificateAuthentication(new byte[] {}, new byte[] {}).provide(client); }
@Test public void testValidECCertificates() throws Exception { try { final ApiClient client = new ApiClient(); final byte[] certificate = Files.readAllBytes(Paths.get(CLIENT_EC_CERT_PATH)); final byte[] key = Files.readAllBytes(Paths.get(CLIENT_EC_KEY_PATH)); new ClientCertificateAuthentication(certificate, key).provide(client); } catch (Exception ex) { ex.printStackTrace(); } }
@Test public void testValidCertificatesChain() throws Exception { try { final ApiClient client = new ApiClient(); final byte[] certificate = Files.readAllBytes(Paths.get(CLIENT_CERT_CHAIN_PATH)); final byte[] key = Files.readAllBytes(Paths.get(CLIENT_CERT_CHAIN_KEY_PATH)); new ClientCertificateAuthentication(certificate, key).provide(client); } catch (Exception ex) { ex.printStackTrace(); } }
@Test public void testValidOldECCertificates() throws Exception { try { final ApiClient client = new ApiClient(); final byte[] certificate = Files.readAllBytes(Paths.get(CLIENT_EC_CERT_PATH)); final byte[] key = Files.readAllBytes(Paths.get(CLIENT_EC_KEY_OLD_PATH)); new ClientCertificateAuthentication(certificate, key).provide(client); } catch (Exception ex) { ex.printStackTrace(); } } |
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()); } UsernamePasswordAuthentication(final String username, final String password); @Override void provide(ApiClient client); } | @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(USERNAME_PASSWORD_BYTES).base64())); } |
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); static void addLabels(
KubernetesObject kubernetesObject, Map<String, String> mergingLabels); } | @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 = new HashMap<>(); newLabels.put("foo1", "bar1"); newLabels.put("foo2", "bar2"); Labels.addLabels(pod, newLabels); assertEquals(pod.getMetadata().getLabels().get("foo1"), "bar1"); assertEquals(pod.getMetadata().getLabels().get("foo2"), "bar2"); } |
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); static ApiClient fromUserPassword(
String url, String user, String password, boolean validateSSL); static ApiClient fromToken(String url, String token); static ApiClient fromToken(String url, String token, boolean validateSSL); static ApiClient fromConfig(String fileName); static ApiClient fromConfig(InputStream stream); static ApiClient fromConfig(Reader input); static ApiClient fromConfig(KubeConfig config); static ApiClient defaultClient(); static final String SERVICEACCOUNT_ROOT; static final String SERVICEACCOUNT_CA_PATH; static final String SERVICEACCOUNT_TOKEN_PATH; static final String ENV_KUBECONFIG; static final String ENV_SERVICE_HOST; static final String ENV_SERVICE_PORT; static final String DEFAULT_FALLBACK_HOST; } | @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("HOME", dir.getCanonicalPath()); ApiClient client = Config.defaultClient(); assertEquals("http: } catch (Exception ex) { ex.printStackTrace(); fail("Unexpected exception: " + ex); } }
@Test public void testDefaultClientKubeConfig() { try { environmentVariables.set("KUBECONFIG", configFile.getCanonicalPath()); ApiClient client = Config.defaultClient(); assertEquals("http: } catch (Exception ex) { ex.printStackTrace(); fail("Unexpected exception: " + ex); } }
@Test public void testDefaultClientPrecedence() { try { environmentVariables.set("HOME", dir.getCanonicalPath()); environmentVariables.set("KUBECONFIG", configFile.getCanonicalPath()); ApiClient client = Config.defaultClient(); assertEquals("http: } catch (Exception ex) { ex.printStackTrace(); fail("Unexpected exception: " + ex); } } |
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 Response<T>(status.type, status.object); } protected Watch(JSON json, ResponseBody body, Type watchType, Call call); static Watch<T> createWatch(ApiClient client, Call call, Type watchType); Response<T> next(); boolean hasNext(); Iterator<Response<T>> iterator(); void remove(); void close(); } | @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", "bar"); JsonObject status = new JsonObject(); status.add("metadata", metadata); status.addProperty("kind", "Status"); status.addProperty("apiVersion", "v1"); status.addProperty("status", "failure"); status.addProperty("message", "too old resource version"); status.addProperty("reason", "Gone"); status.addProperty("code", 410); JsonObject obj = new JsonObject(); obj.addProperty("type", "ERROR"); obj.add("object", status); String data = json.getGson().toJson(obj); Watch.Response<V1ConfigMap> response = watch.parseLine(data); assertEquals(null, response.object); } |
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); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
ApiClient apiClient); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
CustomObjectsApi customObjectsApi); KubernetesApiResponse<ApiType> get(String name); KubernetesApiResponse<ApiType> get(String namespace, String name); KubernetesApiResponse<ApiListType> list(); KubernetesApiResponse<ApiListType> list(String namespace); KubernetesApiResponse<ApiType> create(ApiType object); KubernetesApiResponse<ApiType> update(ApiType object); KubernetesApiResponse<ApiType> patch(String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> patch(
String namespace, String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> delete(String name); KubernetesApiResponse<ApiType> delete(String namespace, String name); Watchable<ApiType> watch(); Watchable<ApiType> watch(String namespace); KubernetesApiResponse<ApiType> get(String name, final GetOptions getOptions); KubernetesApiResponse<ApiType> get(
String namespace, String name, final GetOptions getOptions); KubernetesApiResponse<ApiListType> list(final ListOptions listOptions); KubernetesApiResponse<ApiListType> list(String namespace, final ListOptions listOptions); KubernetesApiResponse<ApiType> create(ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> create(
String namespace, ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> update(ApiType object, final UpdateOptions updateOptions); KubernetesApiResponse<ApiType> patch(
String name, String patchType, V1Patch patch, final PatchOptions patchOptions); KubernetesApiResponse<ApiType> patch(
String namespace,
String name,
String patchType,
V1Patch patch,
final PatchOptions patchOptions); KubernetesApiResponse<ApiType> delete(String name, final DeleteOptions deleteOptions); KubernetesApiResponse<ApiType> delete(
String namespace, String name, final DeleteOptions deleteOptions); Watchable<ApiType> watch(final ListOptions listOptions); Watchable<ApiType> watch(String namespace, final ListOptions listOptions); } | @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> deleteJobResp = jobClient.delete("default", "foo1", null); assertTrue(deleteJobResp.isSuccess()); assertEquals(status, deleteJobResp.getStatus()); assertNull(deleteJobResp.getObject()); verify(1, deleteRequestedFor(urlPathEqualTo("/apis/batch/v1/namespaces/default/jobs/foo1"))); }
@Test public void deleteNamespacedJobReturningDeletedObject() { V1Job foo1 = new V1Job().kind("Job").metadata(new V1ObjectMeta().namespace("default").name("foo1")); stubFor( delete(urlEqualTo("/apis/batch/v1/namespaces/default/jobs/foo1")) .willReturn(aResponse().withStatus(200).withBody(new Gson().toJson(foo1)))); KubernetesApiResponse<V1Job> deleteJobResp = jobClient.delete("default", "foo1"); assertTrue(deleteJobResp.isSuccess()); assertEquals(foo1, deleteJobResp.getObject()); assertNull(deleteJobResp.getStatus()); verify(1, deleteRequestedFor(urlPathEqualTo("/apis/batch/v1/namespaces/default/jobs/foo1"))); }
@Test public void deleteNamespacedJobReturningForbiddenStatus() { V1Status status = new V1Status().kind("Status").code(403).message("good!"); stubFor( delete(urlEqualTo("/apis/batch/v1/namespaces/default/jobs/foo1")) .willReturn(aResponse().withStatus(403).withBody(new Gson().toJson(status)))); KubernetesApiResponse<V1Job> deleteJobResp = jobClient.delete("default", "foo1"); assertFalse(deleteJobResp.isSuccess()); assertEquals(status, deleteJobResp.getStatus()); assertNull(deleteJobResp.getObject()); verify(1, deleteRequestedFor(urlPathEqualTo("/apis/batch/v1/namespaces/default/jobs/foo1"))); } |
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); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
ApiClient apiClient); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
CustomObjectsApi customObjectsApi); KubernetesApiResponse<ApiType> get(String name); KubernetesApiResponse<ApiType> get(String namespace, String name); KubernetesApiResponse<ApiListType> list(); KubernetesApiResponse<ApiListType> list(String namespace); KubernetesApiResponse<ApiType> create(ApiType object); KubernetesApiResponse<ApiType> update(ApiType object); KubernetesApiResponse<ApiType> patch(String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> patch(
String namespace, String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> delete(String name); KubernetesApiResponse<ApiType> delete(String namespace, String name); Watchable<ApiType> watch(); Watchable<ApiType> watch(String namespace); KubernetesApiResponse<ApiType> get(String name, final GetOptions getOptions); KubernetesApiResponse<ApiType> get(
String namespace, String name, final GetOptions getOptions); KubernetesApiResponse<ApiListType> list(final ListOptions listOptions); KubernetesApiResponse<ApiListType> list(String namespace, final ListOptions listOptions); KubernetesApiResponse<ApiType> create(ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> create(
String namespace, ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> update(ApiType object, final UpdateOptions updateOptions); KubernetesApiResponse<ApiType> patch(
String name, String patchType, V1Patch patch, final PatchOptions patchOptions); KubernetesApiResponse<ApiType> patch(
String namespace,
String name,
String patchType,
V1Patch patch,
final PatchOptions patchOptions); KubernetesApiResponse<ApiType> delete(String name, final DeleteOptions deleteOptions); KubernetesApiResponse<ApiType> delete(
String namespace, String name, final DeleteOptions deleteOptions); Watchable<ApiType> watch(final ListOptions listOptions); Watchable<ApiType> watch(String namespace, final ListOptions listOptions); } | @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)))); KubernetesApiResponse<V1Job> jobListResp = jobClient.create(foo1); assertTrue(jobListResp.isSuccess()); assertEquals(foo1, jobListResp.getObject()); assertNull(jobListResp.getStatus()); verify(1, postRequestedFor(urlPathEqualTo("/apis/batch/v1/namespaces/default/jobs"))); } |
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); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
ApiClient apiClient); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
CustomObjectsApi customObjectsApi); KubernetesApiResponse<ApiType> get(String name); KubernetesApiResponse<ApiType> get(String namespace, String name); KubernetesApiResponse<ApiListType> list(); KubernetesApiResponse<ApiListType> list(String namespace); KubernetesApiResponse<ApiType> create(ApiType object); KubernetesApiResponse<ApiType> update(ApiType object); KubernetesApiResponse<ApiType> patch(String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> patch(
String namespace, String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> delete(String name); KubernetesApiResponse<ApiType> delete(String namespace, String name); Watchable<ApiType> watch(); Watchable<ApiType> watch(String namespace); KubernetesApiResponse<ApiType> get(String name, final GetOptions getOptions); KubernetesApiResponse<ApiType> get(
String namespace, String name, final GetOptions getOptions); KubernetesApiResponse<ApiListType> list(final ListOptions listOptions); KubernetesApiResponse<ApiListType> list(String namespace, final ListOptions listOptions); KubernetesApiResponse<ApiType> create(ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> create(
String namespace, ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> update(ApiType object, final UpdateOptions updateOptions); KubernetesApiResponse<ApiType> patch(
String name, String patchType, V1Patch patch, final PatchOptions patchOptions); KubernetesApiResponse<ApiType> patch(
String namespace,
String name,
String patchType,
V1Patch patch,
final PatchOptions patchOptions); KubernetesApiResponse<ApiType> delete(String name, final DeleteOptions deleteOptions); KubernetesApiResponse<ApiType> delete(
String namespace, String name, final DeleteOptions deleteOptions); Watchable<ApiType> watch(final ListOptions listOptions); Watchable<ApiType> watch(String namespace, final ListOptions listOptions); } | @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)))); KubernetesApiResponse<V1Job> jobListResp = jobClient.update(foo1); assertTrue(jobListResp.isSuccess()); assertEquals(foo1, jobListResp.getObject()); assertNull(jobListResp.getStatus()); verify(1, putRequestedFor(urlPathEqualTo("/apis/batch/v1/namespaces/default/jobs/foo1"))); } |
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 apiVersion,
String resourcePlural); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
ApiClient apiClient); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
CustomObjectsApi customObjectsApi); KubernetesApiResponse<ApiType> get(String name); KubernetesApiResponse<ApiType> get(String namespace, String name); KubernetesApiResponse<ApiListType> list(); KubernetesApiResponse<ApiListType> list(String namespace); KubernetesApiResponse<ApiType> create(ApiType object); KubernetesApiResponse<ApiType> update(ApiType object); KubernetesApiResponse<ApiType> patch(String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> patch(
String namespace, String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> delete(String name); KubernetesApiResponse<ApiType> delete(String namespace, String name); Watchable<ApiType> watch(); Watchable<ApiType> watch(String namespace); KubernetesApiResponse<ApiType> get(String name, final GetOptions getOptions); KubernetesApiResponse<ApiType> get(
String namespace, String name, final GetOptions getOptions); KubernetesApiResponse<ApiListType> list(final ListOptions listOptions); KubernetesApiResponse<ApiListType> list(String namespace, final ListOptions listOptions); KubernetesApiResponse<ApiType> create(ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> create(
String namespace, ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> update(ApiType object, final UpdateOptions updateOptions); KubernetesApiResponse<ApiType> patch(
String name, String patchType, V1Patch patch, final PatchOptions patchOptions); KubernetesApiResponse<ApiType> patch(
String namespace,
String name,
String patchType,
V1Patch patch,
final PatchOptions patchOptions); KubernetesApiResponse<ApiType> delete(String name, final DeleteOptions deleteOptions); KubernetesApiResponse<ApiType> delete(
String namespace, String name, final DeleteOptions deleteOptions); Watchable<ApiType> watch(final ListOptions listOptions); Watchable<ApiType> watch(String namespace, final ListOptions listOptions); } | @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_FORMAT_STRATEGIC_MERGE_PATCH)) .willReturn(aResponse().withStatus(200).withBody(new Gson().toJson(foo1)))); KubernetesApiResponse<V1Job> jobPatchResp = jobClient.patch("default", "foo1", V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH, v1Patch); assertTrue(jobPatchResp.isSuccess()); assertEquals(foo1, jobPatchResp.getObject()); assertNull(jobPatchResp.getStatus()); verify(1, patchRequestedFor(urlPathEqualTo("/apis/batch/v1/namespaces/default/jobs/foo1"))); } |
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(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
ApiClient apiClient); GenericKubernetesApi(
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass,
String apiGroup,
String apiVersion,
String resourcePlural,
CustomObjectsApi customObjectsApi); KubernetesApiResponse<ApiType> get(String name); KubernetesApiResponse<ApiType> get(String namespace, String name); KubernetesApiResponse<ApiListType> list(); KubernetesApiResponse<ApiListType> list(String namespace); KubernetesApiResponse<ApiType> create(ApiType object); KubernetesApiResponse<ApiType> update(ApiType object); KubernetesApiResponse<ApiType> patch(String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> patch(
String namespace, String name, String patchType, V1Patch patch); KubernetesApiResponse<ApiType> delete(String name); KubernetesApiResponse<ApiType> delete(String namespace, String name); Watchable<ApiType> watch(); Watchable<ApiType> watch(String namespace); KubernetesApiResponse<ApiType> get(String name, final GetOptions getOptions); KubernetesApiResponse<ApiType> get(
String namespace, String name, final GetOptions getOptions); KubernetesApiResponse<ApiListType> list(final ListOptions listOptions); KubernetesApiResponse<ApiListType> list(String namespace, final ListOptions listOptions); KubernetesApiResponse<ApiType> create(ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> create(
String namespace, ApiType object, final CreateOptions createOptions); KubernetesApiResponse<ApiType> update(ApiType object, final UpdateOptions updateOptions); KubernetesApiResponse<ApiType> patch(
String name, String patchType, V1Patch patch, final PatchOptions patchOptions); KubernetesApiResponse<ApiType> patch(
String namespace,
String name,
String patchType,
V1Patch patch,
final PatchOptions patchOptions); KubernetesApiResponse<ApiType> delete(String name, final DeleteOptions deleteOptions); KubernetesApiResponse<ApiType> delete(
String namespace, String name, final DeleteOptions deleteOptions); Watchable<ApiType> watch(final ListOptions listOptions); Watchable<ApiType> watch(String namespace, final ListOptions listOptions); } | @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(aResponse().withFixedDelay(99999).withStatus(200).withBody(""))); jobClient = new GenericKubernetesApi<>(V1Job.class, V1JobList.class, "batch", "v1", "jobs", apiClient); try { KubernetesApiResponse<V1Job> response = jobClient.get("foo", "test"); } catch (Throwable t) { assertTrue(t.getCause() instanceof SocketTimeoutException); return; } fail("no exception happened"); } |
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"); config.put("current-context", currentContext); config.put("preferences", preferences); config.put("clusters", clusters); config.put("contexts", contexts); config.put("users", users); synchronized (configFile) { try (FileWriter fw = new FileWriter(configFile)) { Yaml yaml = new Yaml(); yaml.dump(config, fw); fw.flush(); } } } FilePersister(String filename); FilePersister(File file); void save(
ArrayList<Object> contexts,
ArrayList<Object> clusters,
ArrayList<Object> users,
Object preferences,
String currentContext); } | @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.getPreferences(), config.getCurrentContext()); KubeConfig configOut = KubeConfig.loadKubeConfig(new FileReader(file)); assertEquals(config.getCurrentContext(), configOut.getCurrentContext()); assertEquals(config.getClusters(), configOut.getClusters()); assertEquals(config.getContexts(), configOut.getContexts()); assertEquals(config.getUsers(), configOut.getUsers()); } |
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 request failed: " + response.code()); } return this.versionApi .getApiClient() .getJSON() .deserialize(response.body().string(), VersionInfo.class); } Version(); Version(ApiClient apiClient); VersionInfo getVersion(); } | @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 versionInfo = versionUtil.getVersion(); } catch (ApiException ex) { } verify( getRequestedFor(urlPathEqualTo("/version/")) .withHeader("Content-Type", equalTo("application/json")) .withHeader("Accept", equalTo("application/json"))); }
@Test public void testFailure() throws InterruptedException, IOException, ApiException { wireMockRule.stubFor( get(urlPathEqualTo("/version/")) .willReturn( aResponse() .withStatus(401) .withHeader("Content-Type", "application/json") .withBody("{}"))); Version versionUtil = new Version(client); boolean thrown = false; try { VersionInfo versionInfo = versionUtil.getVersion(); } catch (ApiException ex) { assertEquals(401, ex.getCode()); thrown = true; } assertEquals(thrown, true); verify( getRequestedFor(urlPathEqualTo("/version/")) .withHeader("Content-Type", equalTo("application/json")) .withHeader("Accept", equalTo("application/json"))); } |
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); PortForwardResult forward(V1Pod pod, List<Integer> ports); PortForwardResult forward(String namespace, String name, List<Integer> ports); } | @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 + "/portforward")) .willReturn( aResponse() .withStatus(404) .withHeader("Content-Type", "application/json") .withBody("{}"))); int portNumber = 8080; List<Integer> ports = new ArrayList<>(); ports.add(portNumber); assertThrows( ApiException.class, () -> { forward.forward(pod, ports); }); Thread.sleep(2000); wireMockRule.verify( getRequestedFor( urlPathEqualTo( "/api/v1/namespaces/" + namespace + "/pods/" + podName + "/portforward")) .withQueryParam("ports", equalTo(Integer.toString(portNumber)))); } |
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( group, versions, preferredVersion, r.getKind(), r.getNamespaced(), r.getName(), r.getSingularName())) .collect(Collectors.toSet()); Map<String, Set<String>> subResources = manageRelationFromResourceToSubResources(resourceList); resources.stream() .forEach( r -> { if (subResources.containsKey(r.getResourcePlural())) { r.subResources.addAll(subResources.get(r.getResourcePlural())); } }); return resources; } Discovery(); Discovery(ApiClient apiClient); Set<APIResource> findAll(); Set<APIResource> findAll(String group, List<String> versions, String preferredVersion); Set<APIResource> findAll(
String group, List<String> versions, String preferredVersion, String path); Set<APIResource> groupResourcesByName(
String group,
List<String> versions,
String preferredVersion,
V1APIResourceList resourceList); V1APIVersions legacyCoreApi(); V1APIGroupList groupDiscovery(String path); V1APIVersions versionDiscovery(String path); V1APIResourceList resourceDiscovery(String path); } | @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") .namespaced(true) .singularName("meow"), new V1APIResource() .name("meows/mouse") .kind("MeowMouse") .namespaced(true) .singularName(""), new V1APIResource() .name("zigs") .kind("Zig") .namespaced(false) .singularName("zig")))); assertEquals(2, discoveredResources.size()); Discovery.APIResource meow = discoveredResources.stream() .filter(r -> r.getResourcePlural().equals("meows")) .findFirst() .get(); assertEquals(1, meow.getSubResources().size()); assertEquals("meows", meow.getResourcePlural()); assertEquals("meow", meow.getResourceSingular()); assertEquals(true, meow.getNamespaced()); assertEquals("mouse", meow.getSubResources().get(0)); } |
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<ApiType>, Throwable> exceptionHandler); void run(); void stop(); String getLastSyncResourceVersion(); } | @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); return null; }); ReflectorRunnable<V1Pod, V1PodList> reflectorRunnable = new ReflectorRunnable<V1Pod, V1PodList>(V1Pod.class, listerWatcher, deltaFIFO); try { Thread thread = new Thread(reflectorRunnable::run); thread.setDaemon(true); thread.start(); Thread.sleep(1000); verify(deltaFIFO, times(1)).replace(any(), any()); verify(deltaFIFO, never()).add(any()); verify(listerWatcher, times(1)).list(any()); verify(listerWatcher, times(1)).watch(any()); } finally { reflectorRunnable.stop(); } }
@Test public void testReflectorWatchConnectionCloseOnError() throws InterruptedException { Watchable<V1Pod> watch = new MockWatch<V1Pod>( new Watch.Response<V1Pod>(EventType.ERROR.name(), new V1Status().status("403"))); ReflectorRunnable<V1Pod, V1PodList> reflectorRunnable = new ReflectorRunnable<>( V1Pod.class, new ListerWatcher<V1Pod, V1PodList>() { @Override public V1PodList list(CallGeneratorParams params) throws ApiException { return new V1PodList().metadata(new V1ListMeta()); } @Override public Watchable<V1Pod> watch(CallGeneratorParams params) throws ApiException { return watch; } }, deltaFIFO); try { Thread thread = new Thread(reflectorRunnable::run); thread.setDaemon(true); thread.start(); Thread.sleep(1000); assertTrue(((MockWatch<V1Pod>) watch).isClosed()); } finally { reflectorRunnable.stop(); } }
@Test public void testReflectorRunnableCaptureListException() throws ApiException, InterruptedException { RuntimeException expectedException = new RuntimeException("noxu"); AtomicReference<Throwable> actualException = new AtomicReference<>(); when(listerWatcher.list(any())).thenThrow(expectedException); ReflectorRunnable<V1Pod, V1PodList> reflectorRunnable = new ReflectorRunnable<>( V1Pod.class, listerWatcher, deltaFIFO, (apiType, t) -> { actualException.set(t); }); try { Thread thread = new Thread(reflectorRunnable::run); thread.setDaemon(true); thread.start(); Thread.sleep(1000); } finally { reflectorRunnable.stop(); } assertEquals(expectedException, actualException.get()); }
@Test public void testReflectorRunnableCaptureWatchException() throws ApiException, InterruptedException { RuntimeException expectedException = new RuntimeException("noxu"); AtomicReference<Throwable> actualException = new AtomicReference<>(); when(listerWatcher.list(any())).thenReturn(new V1PodList().metadata(new V1ListMeta())); when(listerWatcher.watch(any())).thenThrow(expectedException); ReflectorRunnable<V1Pod, V1PodList> reflectorRunnable = new ReflectorRunnable<>( V1Pod.class, listerWatcher, deltaFIFO, (apiType, t) -> { actualException.set(t); }); try { Thread thread = new Thread(reflectorRunnable::run); thread.setDaemon(true); thread.start(); Thread.sleep(1000); } finally { reflectorRunnable.stop(); } assertEquals(expectedException, actualException.get()); } |
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<MutablePair<DeltaFIFO.DeltaType, KubernetesObject>>> processFunc,
Supplier<Boolean> resyncFunc,
long fullResyncPeriod); Controller(
Class<ApiType> apiTypeClass,
DeltaFIFO queue,
ListerWatcher<ApiType, ApiListType> listerWatcher,
Consumer<Deque<MutablePair<DeltaFIFO.DeltaType, KubernetesObject>>> popProcessFunc); void run(); void stop(); boolean hasSynced(); String lastSyncResourceVersion(); } | @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 foo3 = new V1Pod().metadata(new V1ObjectMeta().name("foo3").namespace("default")); V1PodList podList = new V1PodList().metadata(new V1ListMeta()).items(Arrays.asList(foo1, foo2, foo3)); DeltaFIFO deltaFIFO = new DeltaFIFO(Caches::deletionHandlingMetaNamespaceKeyFunc, new Cache()); AtomicBoolean runOnce = new AtomicBoolean(false); ListerWatcher<V1Pod, V1PodList> listerWatcher = new MockRunOnceListerWatcher<V1Pod, V1PodList>( podList, new Watch.Response<V1Pod>(EventType.MODIFIED.name(), foo3)); Controller<V1Pod, V1PodList> controller = new Controller<>( V1Pod.class, deltaFIFO, listerWatcher, (deltas) -> { receivingDeltasCount.incrementAndGet(); }); Thread controllerThread = new Thread(controller::run); controllerThread.setDaemon(true); controllerThread.start(); Thread.sleep(1000); try { assertEquals(4, receivingDeltasCount.get()); } catch (Throwable t) { throw new RuntimeException(t); } finally { controller.stop(); } } |
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(
ApiType object); static String metaNamespaceKeyFunc(KubernetesObject obj); static List<String> metaNamespaceIndexFunc(KubernetesObject obj); static final String NAMESPACE_INDEX; } | @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); static String metaNamespaceKeyFunc(KubernetesObject obj); static List<String> metaNamespaceIndexFunc(KubernetesObject obj); static final String NAMESPACE_INDEX; } | @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(), indices.get(0)); } |
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(); Set<String> intersection = new HashSet<>(oldKeys); intersection.retainAll(newKeys); if (!intersection.isEmpty()) { throw new IllegalArgumentException("indexer conflict: " + intersection); } for (Map.Entry<String, Function<ApiType, List<String>>> indexEntry : newIndexers.entrySet()) { addIndexFunc(indexEntry.getKey(), indexEntry.getValue()); } } Cache(); Cache(
String indexName,
Function<ApiType, List<String>> indexFunc,
Function<ApiType, String> keyFunc); @Override void add(ApiType obj); @Override void update(ApiType obj); @Override void delete(ApiType obj); @Override synchronized void replace(List<ApiType> list, String resourceVersion); @Override void resync(); @Override synchronized List<String> listKeys(); @Override ApiType get(ApiType obj); @Override synchronized List<ApiType> list(); @Override synchronized ApiType getByKey(String key); @Override synchronized List<ApiType> index(String indexName, ApiType obj); @Override synchronized List<String> indexKeys(String indexName, String indexKey); @Override synchronized List<ApiType> byIndex(String indexName, String indexKey); @Override Map<String, Function<ApiType, List<String>>> getIndexers(); @Override void addIndexers(Map<String, Function<ApiType, List<String>>> newIndexers); void updateIndices(ApiType oldObj, ApiType newObj, String key); void addIndexFunc(String indexName, Function<ApiType, List<String>> indexFunc); Function<ApiType, String> getKeyFunc(); void setKeyFunc(Function<ApiType, String> keyFunc); } | @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()); }); indexers.put( clusterIndex, (V1Pod pod) -> { return Arrays.asList(pod.getMetadata().getClusterName()); }); podCache.addIndexers(indexers); V1Pod testPod = new V1Pod() .metadata(new V1ObjectMeta().namespace("ns").name("n").clusterName("cluster1")) .spec(new V1PodSpec().nodeName("node1")); podCache.add(testPod); List<V1Pod> namespaceIndexedPods = podCache.byIndex(Caches.NAMESPACE_INDEX, "ns"); assertEquals(1, namespaceIndexedPods.size()); List<V1Pod> nodeNameIndexedPods = podCache.byIndex(nodeIndex, "node1"); assertEquals(1, nodeNameIndexedPods.size()); List<V1Pod> clusterNameIndexedPods = podCache.byIndex(clusterIndex, "cluster1"); assertEquals(1, clusterNameIndexedPods.size()); } |
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 shouldResync(DateTime now); } | @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, obj); addNotificationReceived = true; } @Override public void onUpdate(V1Pod oldObj, V1Pod newObj) { assertEquals(pod, newObj); updateNotificationReceived = true; } @Override public void onDelete(V1Pod obj, boolean deletedFinalStateUnknown) { assertEquals(pod, obj); deleteNotificationReceived = true; } }, 0); listener.add(new ProcessorListener.AddNotification<>(pod)); listener.add(new ProcessorListener.UpdateNotification<>(null, pod)); listener.add(new ProcessorListener.DeleteNotification<>(pod)); Thread listenerThread = new Thread(listener::run); listenerThread.setDaemon(true); listenerThread.start(); Thread.sleep(1000); assertTrue(addNotificationReceived); assertTrue(updateNotificationReceived); assertTrue(deleteNotificationReceived); }
@Test public void testMultipleNotificationsHandling() throws InterruptedException { V1Pod pod = new V1Pod().metadata(new V1ObjectMeta().name("foo").namespace("default")); final int[] count = {0}; ProcessorListener<V1Pod> listener = new ProcessorListener<>( new ResourceEventHandler<V1Pod>() { @Override public void onAdd(V1Pod obj) { assertEquals(pod, obj); count[0]++; } @Override public void onUpdate(V1Pod oldObj, V1Pod newObj) {} @Override public void onDelete(V1Pod obj, boolean deletedFinalStateUnknown) {} }, 0); for (int i = 0; i < 2000; i++) { listener.add(new ProcessorListener.AddNotification<>(pod)); } Thread listenerThread = new Thread(listener); listenerThread.setDaemon(true); listenerThread.start(); Thread.sleep(2000); assertEquals(count[0], 2000); } |
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 copyFileFromPod(V1Pod pod, String srcPath); InputStream copyFileFromPod(V1Pod pod, String container, String srcPath); InputStream copyFileFromPod(String namespace, String pod, String container, String srcPath); void copyFileFromPod(
String namespace, String name, String container, String srcPath, Path destination); void copyDirectoryFromPod(V1Pod pod, String srcPath, Path destination); void copyDirectoryFromPod(V1Pod pod, String container, String srcPath, Path destination); void copyDirectoryFromPod(String namespace, String pod, String srcPath, Path destination); void copyDirectoryFromPod(
String namespace, String pod, String container, String srcPath, Path destination); void copyDirectoryFromPod(
String namespace,
String pod,
String container,
String srcPath,
Path destination,
boolean enableTarCompressing); static void copyFileFromPod(String namespace, String pod, String srcPath, Path dest); void copyFileToPod(
String namespace, String pod, String container, Path srcPath, Path destPath); void copyFileToPod(
String namespace, String pod, String container, byte[] src, Path destPath); } | @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")) .willReturn( aResponse() .withStatus(404) .withHeader("Content-Type", "application/json") .withBody("{}"))); try { copy.copyFileFromPod(pod, "container", "/some/path/to/file"); } catch (IOException | ApiException e) { e.printStackTrace(); } Thread.sleep(2000); wireMockRule.verify( getRequestedFor( urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec")) .withQueryParam("stdin", equalTo("false")) .withQueryParam("stdout", equalTo("true")) .withQueryParam("stderr", equalTo("true")) .withQueryParam("tty", equalTo("false")) .withQueryParam("command", new AnythingPattern())); } |
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 = new TarArchiveOutputStream( new Base64OutputStream(proc.getOutputStream(), true, 0, null)); FileInputStream input = new FileInputStream(srcFile)) { ArchiveEntry tarEntry = new TarArchiveEntry(srcFile, destPath.getFileName().toString()); archiveOutputStream.putArchiveEntry(tarEntry); ByteStreams.copy(input, archiveOutputStream); archiveOutputStream.closeArchiveEntry(); } finally { proc.destroy(); } } Copy(); Copy(ApiClient apiClient); InputStream copyFileFromPod(String namespace, String pod, String srcPath); InputStream copyFileFromPod(V1Pod pod, String srcPath); InputStream copyFileFromPod(V1Pod pod, String container, String srcPath); InputStream copyFileFromPod(String namespace, String pod, String container, String srcPath); void copyFileFromPod(
String namespace, String name, String container, String srcPath, Path destination); void copyDirectoryFromPod(V1Pod pod, String srcPath, Path destination); void copyDirectoryFromPod(V1Pod pod, String container, String srcPath, Path destination); void copyDirectoryFromPod(String namespace, String pod, String srcPath, Path destination); void copyDirectoryFromPod(
String namespace, String pod, String container, String srcPath, Path destination); void copyDirectoryFromPod(
String namespace,
String pod,
String container,
String srcPath,
Path destination,
boolean enableTarCompressing); static void copyFileFromPod(String namespace, String pod, String srcPath, Path dest); void copyFileToPod(
String namespace, String pod, String container, Path srcPath, Path destPath); void copyFileToPod(
String namespace, String pod, String container, byte[] src, Path destPath); } | @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( aResponse() .withStatus(404) .withHeader("Content-Type", "application/json") .withBody("{}"))); Thread t = new Thread( new Runnable() { public void run() { try { copy.copyFileToPod( namespace, podName, "", testFile.toPath(), Paths.get("/copied-testfile")); } catch (IOException | ApiException ex) { ex.printStackTrace(); } } }); t.start(); Thread.sleep(2000); t.interrupt(); wireMockRule.verify( getRequestedFor( urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec")) .withQueryParam("stdin", equalTo("true")) .withQueryParam("stdout", equalTo("true")) .withQueryParam("stderr", equalTo("true")) .withQueryParam("tty", equalTo("false")) .withQueryParam("command", equalTo("sh")) .withQueryParam("command", equalTo("-c")) .withQueryParam("command", equalTo("base64 -d | tar -xmf - -C /"))); }
@Test public void testCopyBinaryDataToPod() throws InterruptedException { byte[] testSrc = new byte[0]; Copy copy = new Copy(client); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec")) .willReturn( aResponse() .withStatus(404) .withHeader("Content-Type", "application/json") .withBody("{}"))); Thread t = new Thread( new Runnable() { public void run() { try { copy.copyFileToPod( namespace, podName, "", testSrc, Paths.get("/copied-binarydata")); } catch (IOException | ApiException ex) { ex.printStackTrace(); } } }); t.start(); Thread.sleep(2000); t.interrupt(); wireMockRule.verify( getRequestedFor( urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec")) .withQueryParam("stdin", equalTo("true")) .withQueryParam("stdout", equalTo("true")) .withQueryParam("stderr", equalTo("true")) .withQueryParam("tty", equalTo("false")) .withQueryParam("command", equalTo("sh")) .withQueryParam("command", equalTo("-c")) .withQueryParam("command", equalTo("base64 -d | tar -xmf - -C /"))); } |
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 new IllegalArgumentException("Invalid apiVersion found on object: " + apiVersion); } return new GroupVersion(parts[0], parts[1]); } GroupVersion(String group, String version); static GroupVersion parse(String apiVersion); static GroupVersion parse(KubernetesObject obj); String getGroup(); String getVersion(); @Override boolean equals(Object o); @Override int hashCode(); } | @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()); GroupVersion.parse(new V1Pod().apiVersion(null)); GroupVersion.parse(new V1Pod().apiVersion("foo/bar/f")); }); } |
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.spec.containers has no containers"); } return streamNamespacedPodLog( pod.getMetadata().getNamespace(), pod.getMetadata().getName(), pod.getSpec().getContainers().get(0).getName()); } PodLogs(); PodLogs(ApiClient apiClient); ApiClient getApiClient(); InputStream streamNamespacedPodLog(V1Pod pod); InputStream streamNamespacedPodLog(String namespace, String name, String container); InputStream streamNamespacedPodLog(
String namespace,
String name,
String container,
Integer sinceSeconds,
Integer tailLines,
boolean timestamps); } | @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/" + namespace + "/pods/" + podName + "/log")) .willReturn( aResponse() .withStatus(404) .withHeader("Content-Type", "text/plain") .withBody("Not Found"))); PodLogs logs = new PodLogs(client); boolean thrown = false; try { logs.streamNamespacedPodLog(pod); } catch (ApiException ex) { assertEquals(404, ex.getCode()); thrown = true; } assertEquals(thrown, true); wireMockRule.verify( getRequestedFor( urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/log")) .withQueryParam("container", equalTo(container)) .withQueryParam("follow", equalTo("true")) .withQueryParam("pretty", equalTo("false")) .withQueryParam("previous", equalTo("false")) .withQueryParam("timestamps", equalTo("false"))); }
@Test public void testStream() 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")))); String content = "this is some\n content for \n various logs \n done"; wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/log")) .willReturn( aResponse() .withStatus(200) .withHeader("Content-Type", "text/plain") .withBody(content))); PodLogs logs = new PodLogs(client); InputStream is = logs.streamNamespacedPodLog(pod); wireMockRule.verify( getRequestedFor( urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/log")) .withQueryParam("container", equalTo(container)) .withQueryParam("follow", equalTo("true")) .withQueryParam("pretty", equalTo("false")) .withQueryParam("previous", equalTo("false")) .withQueryParam("timestamps", equalTo("false"))); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteStreams.copy(is, bos); assertEquals(content, bos.toString()); } |
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 setDateTimeFormat(DateTimeFormatter dateFormat); JSON setLocalDateFormat(DateTimeFormatter dateFormat); JSON setDateFormat(DateFormat dateFormat); JSON setSqlDateFormat(DateFormat dateFormat); } | @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.decodeBase64(pureString); assertNotNull(byteStr); final String decodedText = new String(byteStr.toByteArray()); assertThat(decodedText, is(plainText)); } |
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(Object o); @Override int hashCode(); } | @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"); intOrString.getIntValue(); } |
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, String patchFormat); static ApiType patch(
Class<ApiType> apiTypeClass, PatchCallFunc callFunc, String patchFormat, ApiClient apiClient); } | @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", "application/json") .withBody("{}"))); PatchUtils.patch( V1Pod.class, () -> coreV1Api.patchNamespacedPodCall( "foo", "default", new V1Patch("[]"), null, null, null, null, null), V1Patch.PATCH_FORMAT_JSON_PATCH, client); verify(1, patchRequestedFor(urlPathEqualTo("/api/v1/namespaces/default/pods/foo"))); }
@Test public void testMergePatchPod() throws ApiException { CoreV1Api coreV1Api = new CoreV1Api(client); stubFor( patch(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")) .withHeader("Content-Type", containing(V1Patch.PATCH_FORMAT_JSON_MERGE_PATCH)) .willReturn( aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{}"))); PatchUtils.patch( V1Pod.class, () -> coreV1Api.patchNamespacedPodCall( "foo", "default", new V1Patch("[]"), null, null, null, null, null), V1Patch.PATCH_FORMAT_JSON_MERGE_PATCH, client); verify(1, patchRequestedFor(urlPathEqualTo("/api/v1/namespaces/default/pods/foo"))); }
@Test public void testStrategicMergePatchPod() throws ApiException { CoreV1Api coreV1Api = new CoreV1Api(client); stubFor( patch(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")) .withHeader("Content-Type", containing(V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH)) .willReturn( aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{}"))); PatchUtils.patch( V1Pod.class, () -> coreV1Api.patchNamespacedPodCall( "foo", "default", new V1Patch("[]"), null, null, null, null, null), V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH, client); verify(1, patchRequestedFor(urlPathEqualTo("/api/v1/namespaces/default/pods/foo"))); } |
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); @Override int hashCode(); } | @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(intOrString.getStrValue(), equalTo("17")); } |
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 BaseExponent baseExponent = new SuffixFormatter().parse(suffix); final BigDecimal unitMultiplier = BigDecimal.valueOf(baseExponent.getBase()) .pow(baseExponent.getExponent(), MathContext.DECIMAL64); final BigDecimal unitlessValue = numericValue.multiply(unitMultiplier); return new Quantity(unitlessValue, baseExponent.getFormat()); } Quantity parse(final String value); String format(final Quantity quantity); } | @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().parse("0.001"); assertThat(quantity.getFormat(), is(Quantity.Format.DECIMAL_SI)); assertThat(quantity.getNumber(), is(BigDecimal.valueOf(0.001))); }
@Test public void testParseFractionalUnit() { final Quantity quantity = new QuantityFormatter().parse("0.001m"); assertThat(quantity.getFormat(), is(Quantity.Format.DECIMAL_SI)); assertThat(quantity.getNumber(), is(new BigDecimal("0.000001"))); }
@Test public void testParseBinarySi() { final Quantity quantity = new QuantityFormatter().parse("1Ki"); assertThat(quantity.getFormat(), is(Quantity.Format.BINARY_SI)); assertThat(quantity.getNumber(), is(BigDecimal.valueOf(1024))); }
@Test public void testParseLargeNumeratorBinarySi() { final Quantity quantity = new QuantityFormatter().parse("32Mi"); assertThat(quantity.getFormat(), is(Quantity.Format.BINARY_SI)); assertThat( quantity.getNumber(), is(BigDecimal.valueOf(2).pow(20).multiply(BigDecimal.valueOf(32)))); }
@Test public void testParseExponent() { final Quantity quantity = new QuantityFormatter().parse("1e3"); assertThat(quantity.getFormat(), is(Quantity.Format.DECIMAL_EXPONENT)); assertThat(quantity.getNumber(), is(BigDecimal.valueOf(1000))); }
@Test public void testParseNegativeExponent() { final Quantity quantity = new QuantityFormatter().parse("1e-3"); assertThat(quantity.getFormat(), is(Quantity.Format.DECIMAL_EXPONENT)); assertThat(quantity.getNumber(), is(BigDecimal.valueOf(0.001))); }
@Test(expected = QuantityFormatException.class) public void testParseBad() { new QuantityFormatter().parse("4e9e"); } |
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 toBase1024String(quantity); default: throw new IllegalArgumentException("Can't format a " + quantity.getFormat() + " quantity"); } } Quantity parse(final String value); String format(final Quantity quantity); } | @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 Quantity(new BigDecimal("100000"), Quantity.Format.DECIMAL_SI)); assertThat(formattedString, is("100k")); }
@Test public void testFormatFractionalDecimalSi() { final String formattedString = new QuantityFormatter() .format(new Quantity(new BigDecimal("100.001"), Quantity.Format.DECIMAL_SI)); assertThat(formattedString, is("100001m")); }
@Test public void testFormatBinarySi() { final String formattedString = new QuantityFormatter() .format(new Quantity(new BigDecimal(2).pow(20), Quantity.Format.BINARY_SI)); assertThat(formattedString, is("1Mi")); }
@Test public void testFormatLessThan1024BinarySi() { final String formattedString = new QuantityFormatter() .format(new Quantity(BigDecimal.valueOf(128), Quantity.Format.BINARY_SI)); assertThat(formattedString, is("128")); }
@Test public void testFormatNon1024BinarySi() { final String formattedString = new QuantityFormatter() .format(new Quantity(BigDecimal.valueOf(2056), Quantity.Format.BINARY_SI)); assertThat(formattedString, is("2056")); }
@Test public void testFormatFractionalBinarySi() { final String formattedString = new QuantityFormatter() .format(new Quantity(BigDecimal.valueOf(123.123), Quantity.Format.BINARY_SI)); assertThat(formattedString, is("123123m")); }
@Test public void testFormatDecimalExponent() { final String formattedString = new QuantityFormatter() .format(new Quantity(BigDecimal.valueOf(1000000), Quantity.Format.DECIMAL_EXPONENT)); assertThat(formattedString, is("1e6")); }
@Test public void testFormatEnforceExpOf3DecimalExponent() { final String formattedString = new QuantityFormatter() .format(new Quantity(BigDecimal.valueOf(100000), Quantity.Format.DECIMAL_EXPONENT)); assertThat(formattedString, is("100e3")); }
@Test public void testFormatNoExpDecimalExponent() { final String formattedString = new QuantityFormatter() .format(new Quantity(BigDecimal.valueOf(12345), Quantity.Format.DECIMAL_EXPONENT)); assertThat(formattedString, is("12345")); } |
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 && (suffix.charAt(0) == 'E' || suffix.charAt(0) == 'e')) { return extractDecimalExponent(suffix); } throw new QuantityFormatException("Could not parse suffix"); } BaseExponent parse(final String suffix); String format(final Quantity.Format format, final int exponent); } | @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 BaseExponent baseExponent = new SuffixFormatter().parse(""); assertThat(baseExponent.getBase(), is(10)); assertThat(baseExponent.getExponent(), is(0)); assertThat(baseExponent.getFormat(), is(Quantity.Format.DECIMAL_SI)); }
@Test public void testParseDecimalK() { final BaseExponent baseExponent = new SuffixFormatter().parse("k"); assertThat(baseExponent.getBase(), is(10)); assertThat(baseExponent.getExponent(), is(3)); assertThat(baseExponent.getFormat(), is(Quantity.Format.DECIMAL_SI)); }
@Test public void testParseDecimalExponent() { final BaseExponent baseExponent = new SuffixFormatter().parse("E2"); assertThat(baseExponent.getBase(), is(10)); assertThat(baseExponent.getExponent(), is(2)); assertThat(baseExponent.getFormat(), is(Quantity.Format.DECIMAL_EXPONENT)); }
@Test public void testParseDecimalExponentPositive() { final BaseExponent baseExponent = new SuffixFormatter().parse("e+3"); assertThat(baseExponent.getBase(), is(10)); assertThat(baseExponent.getExponent(), is(3)); assertThat(baseExponent.getFormat(), is(Quantity.Format.DECIMAL_EXPONENT)); }
@Test public void testParseDecimalExponentNegative() { final BaseExponent baseExponent = new SuffixFormatter().parse("e-3"); assertThat(baseExponent.getBase(), is(10)); assertThat(baseExponent.getExponent(), is(-3)); assertThat(baseExponent.getFormat(), is(Quantity.Format.DECIMAL_EXPONENT)); }
@Test(expected = QuantityFormatException.class) public void testParseBad() { new SuffixFormatter().parse("eKi"); } |
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 IllegalStateException("Can't format " + format + " with exponent " + exponent); } } BaseExponent parse(final String suffix); String format(final Quantity.Format format, final int exponent); } | @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_EXPONENT, 3); assertThat(formattedString, is("e3")); }
@Test public void testFormatZeroDecimalSi() { final String formattedString = new SuffixFormatter().format(Quantity.Format.DECIMAL_SI, 0); assertThat(formattedString, is("")); }
@Test(expected = IllegalArgumentException.class) public void testFormatBadDecimalSi() { new SuffixFormatter().format(Quantity.Format.DECIMAL_SI, 2); }
@Test public void testFormatDecimalSi() { final String formattedString = new SuffixFormatter().format(Quantity.Format.DECIMAL_SI, 3); assertThat(formattedString, is("k")); }
@Test public void testFormatNegativeDecimalSi() { final String formattedString = new SuffixFormatter().format(Quantity.Format.DECIMAL_SI, -6); assertThat(formattedString, is("u")); }
@Test public void testFormatBinarySi() { final String formattedString = new SuffixFormatter().format(Quantity.Format.BINARY_SI, 10); assertThat(formattedString, is("Ki")); }
@Test public void testFormatNoExponentBinarySi() { final String formattedString = new SuffixFormatter().format(Quantity.Format.BINARY_SI, 0); assertThat(formattedString, is("")); }
@Test(expected = IllegalArgumentException.class) public void testFormatBadBinarySi() { new SuffixFormatter().format(Quantity.Format.BINARY_SI, 4); } |
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(apiGroup, apiVersion, kind); } @Deprecated static void addModelMap(String apiGroupVersion, String kind, Class<?> clazz); @Deprecated static void addModelMap(String group, String version, String kind, Class<?> clazz); static void addModelMap(
String group, String version, String kind, String resourceNamePlural, Class<?> clazz); static void addModelMap(
String group,
String version,
String kind,
String resourceNamePlural,
Boolean isNamespacedResource,
Class<?> clazz); static Class<?> getApiTypeClass(String apiGroupVersion, String kind); static Class<?> getApiTypeClass(String group, String version, String kind); static GroupVersionKind getGroupVersionKindByClass(Class<?> clazz); static GroupVersionResource getGroupVersionResourceByClass(Class<?> clazz); static Set<Discovery.APIResource> refresh(Discovery discovery); static Set<Discovery.APIResource> refresh(Discovery discovery, Duration refreshInterval); static boolean isApiDiscoveryRefreshed(); static Class<?> preBuiltGetApiTypeClass(String group, String version, String kind); static GroupVersionKind preBuiltGetGroupVersionKindByClass(Class<?> clazz); static Boolean isNamespaced(Class<?> clazz); static final Duration DEFAULT_DISCOVERY_REFRESH_INTERVAL; } | @Test public void testPrebuiltModelMapping() { assertEquals(V1Pod.class, ModelMapper.getApiTypeClass("", "v1", "Pod")); assertEquals(V1Deployment.class, ModelMapper.getApiTypeClass("", "v1", "Deployment")); assertEquals( V1beta1CustomResourceDefinition.class, ModelMapper.getApiTypeClass("", "v1beta1", "CustomResourceDefinition")); } |
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); @Deprecated static void addModelMap(String group, String version, String kind, Class<?> clazz); static void addModelMap(
String group, String version, String kind, String resourceNamePlural, Class<?> clazz); static void addModelMap(
String group,
String version,
String kind,
String resourceNamePlural,
Boolean isNamespacedResource,
Class<?> clazz); static Class<?> getApiTypeClass(String apiGroupVersion, String kind); static Class<?> getApiTypeClass(String group, String version, String kind); static GroupVersionKind getGroupVersionKindByClass(Class<?> clazz); static GroupVersionResource getGroupVersionResourceByClass(Class<?> clazz); static Set<Discovery.APIResource> refresh(Discovery discovery); static Set<Discovery.APIResource> refresh(Discovery discovery, Duration refreshInterval); static boolean isApiDiscoveryRefreshed(); static Class<?> preBuiltGetApiTypeClass(String group, String version, String kind); static GroupVersionKind preBuiltGetGroupVersionKindByClass(Class<?> clazz); static Boolean isNamespaced(Class<?> clazz); static final Duration DEFAULT_DISCOVERY_REFRESH_INTERVAL; } | @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("", "v1", "Deployment"), ModelMapper.preBuiltGetGroupVersionKindByClass(V1Deployment.class)); assertEquals( new GroupVersionKind("", "v1beta1", "CustomResourceDefinition"), ModelMapper.preBuiltGetGroupVersionKindByClass(V1beta1CustomResourceDefinition.class)); } |
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') { output = addString(output, str.substring(lineStart, i), arrayIndex++); lineStart = i+1; } else if (i - lineStart == maxWidth) { output = addString(output, str.substring(lineStart, i), arrayIndex++); lineStart = i; } } if (lineStart != i || i == 0) { output = addString(output, str.substring(lineStart), arrayIndex++, output.length+1); } if (arrayIndex < output.length) { output[arrayIndex] = null; } return output; } static String[] wrapString(@Nonnull String str, int maxWidth, @Nullable String[] output); } | @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 String[0])); validateResult( new String[]{"abc"}, StringWrapper.wrapString("abc", 6, new String[1])); validateResult( new String[]{""}, StringWrapper.wrapString("", 6, new String[3])); validateResult( new String[]{"abcdef"}, StringWrapper.wrapString("abcdef", 6, new String[3])); validateResult( new String[]{"abcdef", "abcdef"}, StringWrapper.wrapString("abcdef\nabcdef", 6, new String[3])); validateResult( new String[]{"abc", "", "def"}, StringWrapper.wrapString("abc\n\ndef", 6, new String[3])); validateResult( new String[]{"", "abcdef"}, StringWrapper.wrapString("\nabcdef", 6, new String[3])); validateResult( new String[]{"", "", "abcdef"}, StringWrapper.wrapString("\n\nabcdef", 6, new String[3])); validateResult( new String[]{"", "", "abcdef"}, StringWrapper.wrapString("\n\nabcdef", 6, new String[4])); validateResult( new String[]{"", "", "abcdef", ""}, StringWrapper.wrapString("\n\nabcdef\n\n", 6, new String[4])); validateResult( new String[]{"", "", "abcdef", "a", ""}, StringWrapper.wrapString("\n\nabcdefa\n\n", 6, new String[4])); validateResult( new String[]{"", "", "abcdef", "a", ""}, StringWrapper.wrapString("\n\nabcdefa\n\n", 6, new String[0])); validateResult( new String[]{"", "", "abcdef", "a", ""}, StringWrapper.wrapString("\n\nabcdefa\n\n", 6, new String[5])); validateResult( new String[]{"", "", "a", "b", "c", "d", "e", "f", "a", ""}, StringWrapper.wrapString("\n\nabcdefa\n\n", 1, new String[5])); } |
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+toRemove); } ClassFileNameHandler(File path, String fileExtension); File getUniqueFilenameForClass(String className); } | @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", offset); } return result; } 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(int offset); @Nonnull BaseDexReader readerAt(int offset); } | @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 BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, 0x7f}); Assert.assertEquals(0x7fffffff, dexBuf.readSmallUint(0)); }
@Test(expected=ExceptionWithContext.class) public void testReadSmallUintTooLarge1() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00, 0x00, (byte)0x80}); dexBuf.readSmallUint(0); }
@Test(expected=ExceptionWithContext.class) public void testReadSmallUintTooLarge2() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0x80}); dexBuf.readSmallUint(0); }
@Test(expected=ExceptionWithContext.class) public void testReadSmallUintTooLarge3() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff}); dexBuf.readSmallUint(0); }
@Test(expected=ExceptionWithContext.class) public void testReadOptionalUintTooLarge1() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00, 0x00, (byte)0x80}); dexBuf.readSmallUint(0); }
@Test(expected=ExceptionWithContext.class) public void testReadOptionalUintTooLarge2() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0x80}); dexBuf.readSmallUint(0); }
@Test(expected=ExceptionWithContext.class) public void testReadOptionalUintTooLarge3() { BaseDexBuffer dexBuf = new BaseDexBuffer(new byte[] {(byte)0xfe, (byte)0xff, (byte)0xff, (byte)0xff}); dexBuf.readSmallUint(0); } |
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); int readInt(int offset); int readShort(int offset); int readByte(int offset); @Nonnull BaseDexReader readerAt(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}); Assert.assertEquals(dexBuf.readUshort(0), 0xffff); dexBuf = new BaseDexBuffer(new byte[] {(byte)0x00, (byte)0x80}); Assert.assertEquals(dexBuf.readUshort(0), 0x8000); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0x7f}); Assert.assertEquals(dexBuf.readUshort(0), 0x7fff); } |
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 readByte(int offset); @Nonnull BaseDexReader readerAt(int offset); } | @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[offset+7]) << 56); } 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(int offset); @Nonnull BaseDexReader readerAt(int offset); } | @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.readLong(0)); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, 0x7f}); Assert.assertEquals(Long.MAX_VALUE, dexBuf.readLong(0)); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0x80}); Assert.assertEquals(Long.MIN_VALUE, dexBuf.readLong(0)); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x80}); Assert.assertEquals(0x80ffffffffffffffL, dexBuf.readLong(0)); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff}); Assert.assertEquals(-1, dexBuf.readLong(0)); }
@Test public void testReadLongRandom() { Random r = new Random(1234567890); ByteBuffer byteBuf = ByteBuffer.allocateDirect(8).order(ByteOrder.LITTLE_ENDIAN); byte[] buf = new byte[8]; BaseDexBuffer dexBuf = new BaseDexBuffer(buf); for (int i=0; i<10000; i++) { int val = r.nextInt(); byteBuf.putLong(0, val); byteBuf.position(0); byteBuf.get(buf); Assert.assertEquals(val, dexBuf.readLong(0)); } } |
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); int readUbyte(int offset); long readLong(int offset); int readInt(int offset); int readShort(int offset); int readByte(int offset); @Nonnull BaseDexReader readerAt(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)0xff, (byte)0xff, (byte)0xff, 0x7f}); Assert.assertEquals(Integer.MAX_VALUE, dexBuf.readInt(0)); dexBuf = new BaseDexBuffer(new byte[] {0x00, 0x00, 0x00, (byte)0x80}); Assert.assertEquals(Integer.MIN_VALUE, dexBuf.readInt(0)); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0x80}); Assert.assertEquals(0x80ffffff, dexBuf.readInt(0)); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff}); Assert.assertEquals(-1, dexBuf.readInt(0)); } |
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 readInt(int offset); int readShort(int offset); int readByte(int offset); @Nonnull BaseDexReader readerAt(int offset); } | @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}); Assert.assertEquals(dexBuf.readShort(0), -1); dexBuf = new BaseDexBuffer(new byte[] {(byte)0x00, (byte)0x80}); Assert.assertEquals(dexBuf.readShort(0), Short.MIN_VALUE); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0x7f}); Assert.assertEquals(dexBuf.readShort(0), 0x7fff); dexBuf = new BaseDexBuffer(new byte[] {(byte)0xff, (byte)0x80}); Assert.assertEquals(dexBuf.readShort(0), 0xffff80ff); } |
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(int offset); @Nonnull BaseDexReader readerAt(int offset); } | @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[] = token.substring( 0, end ).split( ":" ); if( ga_part[ 0 ].equals( groupId ) && ga_part[ 1 ].equals( artifactId ) ) { return token.substring( end ); } } } return ""; } void execute(); String getSettingsForArtifact( String fullSettings, String groupId, String artifactId ); } | @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" ) ); assertEquals( "", new GenerateConfigMojo().getSettingsForArtifact( "cheese:ham@1@nope,foo:bar@42@bee,fuel:oil@1@xx", "cheese", "bb" ) ); 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,ping:back", "ping", "back" ) ); } |
CompositeScannerProvisionOption extends AbstractUrlProvisionOption<CompositeScannerProvisionOption> implements Scanner { public String getURL() { return new StringBuilder() .append( SCHEMA ) .append( SEPARATOR_SCHEME ) .append( super.getURL() ) .append( getOptions( this ) ) .toString(); } CompositeScannerProvisionOption( final String url ); CompositeScannerProvisionOption( final UrlReference url ); String getURL(); } | @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().groupId( "bar" ).artifactId( "foo" ).type( "composite" ) ).getURL(), is( equalTo( "scan-composite:mvn:bar/foo ); }
@Test public void urlAsMavenUrlViaFactoryMethod() { assertThat( "Scan composite url", scanComposite( maven().groupId( "bar" ).artifactId( "foo" ).type( "composite" ) ).getURL(), is( equalTo( "scan-composite:mvn:bar/foo ); }
@Test public void urlAsString() { assertThat( "Scan composite url", new CompositeScannerProvisionOption( "file:foo.composite" ).getURL(), is( equalTo( "scan-composite:file:foo.composite@update" ) ) ); }
@Test public void urlAsStringViaFactoryMethod() { assertThat( "Scan composite url", scanComposite( "file:foo.composite" ).getURL(), is( equalTo( "scan-composite:file:foo.composite@update" ) ) ); }
@Test public void urlAsReference() { assertThat( "Scan composite url", new CompositeScannerProvisionOption( url( "file:foo.composite" ) ).getURL(), is( equalTo( "scan-composite:file:foo.composite@update" ) ) ); } |
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 url ); FileScannerProvisionOption( final UrlReference url ); String getURL(); } | @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:file:foo.bundles" ) ) ); }
@Test public void urlAsReference() { assertThat( "Scan file url", new FileScannerProvisionOption( url( "file:foo.bundles" ) ).getURL(), is( equalTo( "scan-file:file:foo.bundles" ) ) ); }
@Test public void urlAsReferenceViaFactoryMethod() { assertThat( "Scan file url", scanFile( url( "file:foo.bundles" ) ).getURL(), is( equalTo( "scan-file:file:foo.bundles" ) ) ); }
@Test public void urlAsMavenUrl() { assertThat( "Scan file url", new FileScannerProvisionOption( maven().groupId( "bar" ).artifactId( "foo" ).type( "bundles" ) ).getURL(), is( equalTo( "scan-file:mvn:bar/foo ); }
@Test public void urlAsMavenUrlViaFactoryMethod() { assertThat( "Scan file url", scanFile( maven().groupId( "bar" ).artifactId( "foo" ).type( "bundles" ) ).getURL(), is( equalTo( "scan-file:mvn:bar/foo ); } |
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( String feature : m_features ) { if( !first ) { url.append( FEATURE_SEPARATOR ); } first = false; url.append( feature ); } url.append( getOptions( this ) ); return url.toString(); } FeaturesScannerProvisionOption( final String repositoryUrl,
final String... features ); FeaturesScannerProvisionOption( final UrlReference repositoryUrl,
final String... features ); String getURL(); } | @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", scanFeatures( "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 urlAsReference() { assertThat( "Scan features url", new FeaturesScannerProvisionOption( url( "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 urlAsReferenceViaFactoryMethod() { assertThat( "Scan features url", scanFeatures( url( "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 urlAsMavenUrl() { assertThat( "Scan features url", new FeaturesScannerProvisionOption( maven().groupId( "bar" ).artifactId( "foo" ).classifier( "features" ).type( "xml" ), "f1", "f2/1.0.0" ).getURL(), is( equalTo( "scan-features:mvn:bar/foo ); }
@Test public void urlAsMavenUrlViaFactoryMethod() { assertThat( "Scan features url", scanFeatures( maven().groupId( "bar" ).artifactId( "foo" ).classifier( "features" ).type( "xml" ), "f1", "f2/1.0.0" ).getURL(), is( equalTo( "scan-features:mvn:bar/foo ); } |
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 isConfigurationInstalled(); static Configuration getConfigInstance(); static Configuration getConfigFromPropertiesFile(URL startingUrl); static Properties getPropertiesFromFile(URL startingUrl); static void installReadonlyProperties(Properties pros); } | @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.class.getClassLoader().getResourceAsStream("jar:"+url.toURI().toString()+"!/META-INF/MANIFEST.MF"); System.out.println(url.toURI().toString()); System.out.println(in); ZipInputStream zip = new ZipInputStream(url.openStream()); ZipEntry ze; while ((ze = zip.getNextEntry())!=null){ if(ze.getName().equals("META-INF/MANIFEST.MF")){ System.out.println(ze.getName()); break; } } System.out.println(IOUtils.readAll(zip)); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ConfigurationManager.setEnableDefaultload(false); } |
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> getPropertiesByConfigName(String configName); static Set<String> getConfigKeys(String configName); static synchronized boolean isConfigurationInstalled(); static Configuration getConfigInstance(); static Configuration getConfigFromPropertiesFile(URL startingUrl); static Properties getPropertiesFromFile(URL startingUrl); static void installReadonlyProperties(Properties pros); } | @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.config.samples.needCount")); assertEquals("100", ConfigurationManager.getConfigInstance().getString("no.exist","100")); } |
ConfigurationManager { public static Configuration getConfigInstance() throws InitConfigurationException { if (instance == null) { synchronized (ConfigurationManager.class) { if (instance == null) { instance = createDefaultConfigInstance(); try { customProperties = Tools.loadPropertiesFromFile(TEMPFILENAME); } catch (Throwable e) { logger.error("load temp custom properties failed!", e); } if(customProperties!=null) { Iterator<String> keys = customProperties.getKeys(); while (keys.hasNext()) { String key = keys.next(); if (instance.containsKey(key)) { instance.setProperty(key, customProperties.getString(key)); } } } } } } return instance; } static Map<String,Map<String,String>> getAllProperties(); static Map<String,String> getPropertiesByConfigName(String configName); static Set<String> getConfigKeys(String configName); static synchronized boolean isConfigurationInstalled(); static Configuration getConfigInstance(); static Configuration getConfigFromPropertiesFile(URL startingUrl); static Properties getPropertiesFromFile(URL startingUrl); static void installReadonlyProperties(Properties pros); } | @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")); assertTrue(0 == config.getDouble("test-int-emp")); assertTrue(20 == config.getInt("test-int-emp",20)); assertTrue(new Integer(23) == config.getInt("test-int-emp",new Integer(23))); assertEquals(false,config.getBoolean("test-boolean")); } |
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 new IOException("Cannot locate " + defaultConfigFileName + " as a classpath resource."); } Properties props = getPropertiesFromFile(url); String environment = EnFactory.getEnBase().getEnvType(); if(environment!=null) { environment = environment.toLowerCase(); } if (environment != null && environment.length() > 0) { String envConfigFileName = configName + "-" + environment + ".properties"; url = loader.getResource(envConfigFileName); if(url==null){ url = loader.getResource(configName.replace("config/",environment+"-config/") +".properties"); } if (url != null) { Properties envProps = getPropertiesFromFile(url); if (envProps != null) { props.putAll(envProps); } } } return props; } static Map<String,Map<String,String>> getAllProperties(); static Map<String,String> getPropertiesByConfigName(String configName); static Set<String> getConfigKeys(String configName); static synchronized boolean isConfigurationInstalled(); static Configuration getConfigInstance(); static Configuration getConfigFromPropertiesFile(URL startingUrl); static Properties getPropertiesFromFile(URL startingUrl); static void installReadonlyProperties(Properties pros); } | @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("cascaded.property")); } |
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 new ExeResult("NO PATH ERROR",0,SC_NOTFOUND); } path = path.toLowerCase(); boolean isHandled =false; try { eventLogger.fireEvent(EventLogger.TRANSSTART,path); switch (path) { case "/ip": rtn = params.get("req_ip"); isHandled = true; break; case "/status": case "/health": AppInfo appInfo = ComponentManager.getStatus(AppInfo.class); switch (appInfo.getStatus()) { case Uninitiated: responseCode = AppInfo.UNINITIATED; break; case Initiating: responseCode = AppInfo.INITIATING; break; case Initiated: responseCode = AppInfo.INITIATED; break; case InitiatedFailed: responseCode = AppInfo.INITIATEDFAILED; break; case MarkDown: responseCode = AppInfo.MARKDOWN; break; } rtn = appInfo.getStatus(); if(appInfo.getStatus() == AppStatus.MarkDown){ rtn = "markdown by "+appInfo.getMarkDownReason(); } isHandled = true; break; case "/status/detail": case "/health/detail": appInfo = ComponentManager.getStatus(AppInfo.class); Map<String,Object> statusDetail = new LinkedHashMap<>(); statusDetail.put("appStatus",appInfo.getStatus()); if(appInfo.getStatus()==AppStatus.MarkDown){ statusDetail.put("markDownReason",appInfo.getMarkDownReason()); } statusDetail.put("igniteDetail",ComponentManager.getStatus(IgniteStatus.class)); rtn = statusDetail; isHandled = true; break; default: for (String startPath : handlersMap.keySet()) { if (path.startsWith(startPath)) { isHandled = true; ViFunctionHandler functionHandler = handlersMap.get(startPath); permission = functionHandler.getPermission(user).getValue(); rtn = functionHandler.execute(path, user, permission, logger, params); break; } } break; } eventLogger.fireEvent(EventLogger.TRANSEND); }catch (Throwable e){ logger.warn("execute service error",e); e.printStackTrace(); eventLogger.fireEvent(EventLogger.TRANSEND,e); Throwable rootCause; if(e.getCause()!=null){ rootCause = e.getCause(); }else{ rootCause = e; } rtn = TextUtils.makeJSErrorMsg(rootCause.getMessage(),e.getClass().getName()); if(e instanceof NoPermissionException){ responseCode = SC_METHODNOTALLOWED; } }finally { eventLogger.fireEvent(EventLogger.TRANSFINALLY); } if(!isHandled){ rtn = path + " not found"; } long cost = (System.nanoTime()-startTime)/1000L; try { MetricsCollector.getCollector().record(Metrics.VIAPI, cost); }catch (Throwable e){ logger.error("metrics collect failed!",e); } return new ExeResult(rtn,permission,responseCode); } VIApiHandler(); static synchronized VIApiHandler getInstance(); boolean register(ViFunctionHandler apiHandler); ExeResult executeService(String path,String user,Map<String,Object> params); } | @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 = "/threading/all"; VIApiHandler.ExeResult rtn = handler.executeService(path, user, null); List<ThreadingManager.TInfo> data = (List<ThreadingManager.TInfo>) rtn.getData(); assertTrue(data.size()>0); }
@Test public void testGetThreadInfo(){ long threadId = 1; String path = "/threading/detail/"+threadId; VIApiHandler.ExeResult rtn = handler.executeService(path, user, null); ThreadInfo info = (ThreadInfo) rtn.getData(); assertEquals(threadId, info.getThreadId()); assertEquals("main", info.getThreadName()); final int maxDepth = 2; rtn = handler.executeService(path, user, new HashMap<String, Object>(){ { put("maxdepth",maxDepth+""); } }); info = (ThreadInfo) rtn.getData(); assertEquals(maxDepth,info.getStackTrace().length); rtn = handler.executeService(path, user, new HashMap<String, Object>(){ { put("maxdepth","abc"); } }); info = (ThreadInfo) rtn.getData(); assertEquals(3,info.getStackTrace().length); }
@Test public void testThreadStats(){ String path = "/threading/stats"; VIApiHandler.ExeResult rtn = handler.executeService(path, user, null); Map<String,Number> info = (Map<String, Number>) rtn.getData(); assertTrue(info.containsKey("currentThreadCount")); assertTrue(info.get("currentThreadCount").intValue()>0); assertTrue(info.containsKey("daemonThreadCount")); assertTrue(info.get("daemonThreadCount").intValue()>0); assertTrue(info.containsKey("totalStartedThreadCount")); assertTrue(info.get("totalStartedThreadCount").longValue() > 0); assertTrue(info.containsKey("peakThreadCount")); assertTrue(info.get("peakThreadCount").intValue()>0); } |
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,String id); static ServletHandler bind(Server server,String id,boolean useVIAuthentication); Server getInnerServer(); ServletHandler getHandler(); synchronized void start(); synchronized void stop(); } | @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().getMessages()); infos =gson.fromJson(content, infos.getClass()); Assert.assertTrue(infos.size()>=3); server.stop(); try{ infos =gson.fromJson(IOUtils.readAll((InputStream)url.getContent()), infos.getClass()); Assert.fail("can't reach there"); }catch (Exception e){ Assert.assertTrue(e instanceof ConnectException); } } |
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); @Override void dispatch(String name, Object event); @Override void dispatch(String name, Object... args); } | @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() { testEventBus.testEventWithoutArgument(); replay(testEventBus); eventBusDispatcher.dispatch("testEventWithoutArgument"); verify(testEventBus); }
@Test(expected = Exception.class) public void testDispatch_withoutArgument_exceptionOccurred_willBeRaised() { testEventBus.testEventWithoutArgument(); expectLastCall().andThrow(new RuntimeException("Faking an exception")); replay(testEventBus); eventBusDispatcher.dispatch("testEventWithoutArgument"); verify(testEventBus); }
@Test(expected = Exception.class) public void testDispatch_witArgument_exceptionOccurred_willBeRaised() { testEventBus.testEventWithArgument(THE_ARG); expectLastCall().andThrow(new RuntimeException("Faking an exception")); replay(testEventBus); eventBusDispatcher.dispatch("testEventWithArgument",THE_ARG); verify(testEventBus); }
@Test public void testDispatch_notExistingMethod() { replay(testEventBus); eventBusDispatcher.dispatch("notExistingMethod",THE_ARG); verify(testEventBus); } |
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 UiConstraintException("Failed to instantiate component type: " + viewClass.getName()); } catch (IllegalAccessException e) { throw new UiConstraintException("Failed to instantiate component type: " + viewClass.getName()); } } UiBinder(); void setUiMessageSource(IUiMessageSource messageSource); boolean isBindable(Class<?> viewClass); boolean isBindable(String viewName); T bind(Class<T> viewClass, Locale locale, IEventBinder eventBinder); Component bind(String viewName, Locale locale, IEventBinder eventBinder); } | @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 void testBindTranslations() throws Exception { UiBinderView view = instance.bind(UiBinderView.class, new Locale("en"), null); Label l = view.title; String caption = l.getCaption(); assertNotNull("caption is null", caption); assertEquals("wrong caption", "This is the view title", caption); assertEquals("de only message wrong", "Dieser Text steht nur in deutsch", view.labelTwo.getCaption()); }
@Test public void testBindSimpleComponentsInitialized() throws UiBinderException { UiBinderViewInit root = instance.bind(UiBinderViewInit.class, new Locale("en"), null); assertNotNull("component is null", root); assertTrue("component is not initialzed", root.initialized); }
@Test public void testBindSimpleComponents() throws UiBinderException { UiBinderView root = instance.bind(UiBinderView.class, new Locale("en"), null); assertNotNull("component is null", root); boolean isPanel = root instanceof Panel; assertTrue("not a panel", isPanel); Panel panel = (Panel) root; Component layout = panel.getContent(); assertTrue("first nested component should be a vertical layout", (layout instanceof VerticalLayout)); VerticalLayout verticalLayout = (VerticalLayout) layout; Component label = verticalLayout.getComponent(0); assertNotNull("label is null", label); assertTrue("not a label: " + label.getClass(), (label instanceof Label)); }
@Test public void testBindAttributes() throws Exception { UiBinderView root = instance.bind(UiBinderView.class, new Locale("en"), null); ComponentContainer content = root.getContent(); assertNotNull("content should be a layout", content); VerticalLayout layout = (VerticalLayout) content; float height = layout.getHeight(); assertEquals("height not set correctly", 67.0f, height, 0.0d); assertTrue("setSizeFull() has not been called", root.sizeFull); }
@Test public void testBindEventListener() throws Exception { UiBinderView root = instance.bind(UiBinderView.class, new Locale("en"), null); assertNotNull("event button not bound", root.eventButton); assertTrue("click listener not set", root.eventButton.clickListenerSet); }
@Test public void testBindCustomComponents() throws Exception { UiBinderCustomCompView view = instance.bind(UiBinderCustomCompView.class, new Locale("en"), null); assertNotNull("custom comp has not been added to the view", view.customComp); assertNotNull("custom comp content not added", view.customComp.getContent()); assertEquals("custom comp content is not a VerticalLayout", VerticalLayout.class, view.customComp.getContent().getClass()); assertEquals("custom comp content is not a Label", Label.class, view.customComp.getContent().getComponentIterator().next().getClass()); assertNotNull("custom comp field 'label' not bound to UiField", view.customComp.label); assertEquals("custom comp field 'label' not translated", "This is the view title", view.customComp.label.getCaption()); }
@Test public void testBindNestedComponents() throws UiBinderException { UiBinderView root = instance.bind(UiBinderView.class, new Locale("en"), null); assertNotNull("component is null", root); boolean isPanel = root instanceof Panel; assertTrue("not a panel", isPanel); Panel panel = (Panel) root; Component layout = panel.getContent(); assertTrue("first nested component should be a vertical layout", (layout instanceof VerticalLayout)); Component label = ((VerticalLayout) layout).getComponent(0); assertNotNull("label is null", label); assertTrue("not a label: " + label.getClass(), (label instanceof Label)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.