src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
CommodityExchangeController extends BaseController { @ApiOperation("查看充值卡卡密") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/show/code", method = {RequestMethod.POST, RequestMethod.GET}) public JSONObject exchangeToRechargeCard(@ApiParam("卡号") @RequestParam("code") String code) { return success("操作成功!", emService.cardPassword(code)); } @ApiOperation("查询商品兑换方式") @RequestMapping(value = "/api/v1/user/commodity/commexchways", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryCommExchangeWays(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("兑换现金") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp3", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToCash(@ApiParam("商品Id") @RequestParam("commId") Long commId, @ApiParam("平台名称(例:支付宝平台)") @RequestParam("TPName") String TPName, @ApiParam("平台账号") @RequestParam("TPAccount") String TPAccount) {; @ApiOperation("兑换闪币") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp4", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToGold(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("兑换充值卡") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/temp1", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToRechargeCardTemp1(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("查看充值卡卡密") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/show/code", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToRechargeCard(@ApiParam("卡号") @RequestParam("code") String code) {; @ApiOperation("可兑换充值卡方式详情") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/show", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryExchangeToRechargeCard(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("充值卡兑换流程详情") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/info", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryExchangeToRechargeCardInfo(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("快递收货") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp2", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToExpress(@ApiParam("商品Id") @RequestParam("commId") Long commId, @ApiParam("注册用户地址Id") @RequestParam("addressId") Long addressId) {; @ApiOperation("到店领取") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp5", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToLocale(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; }
@Test public void testExchangeToRechargeCard() throws Exception { }
CommodityExchangeController extends BaseController { @ApiOperation("可兑换充值卡方式详情") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/show", method = {RequestMethod.POST, RequestMethod.GET}) public JSONObject queryExchangeToRechargeCard(@ApiParam("商品Id") @RequestParam("commId") Long commId) { return success(emService.selectUserRechargeCardPrize(getUserId(), commId)); } @ApiOperation("查询商品兑换方式") @RequestMapping(value = "/api/v1/user/commodity/commexchways", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryCommExchangeWays(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("兑换现金") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp3", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToCash(@ApiParam("商品Id") @RequestParam("commId") Long commId, @ApiParam("平台名称(例:支付宝平台)") @RequestParam("TPName") String TPName, @ApiParam("平台账号") @RequestParam("TPAccount") String TPAccount) {; @ApiOperation("兑换闪币") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp4", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToGold(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("兑换充值卡") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/temp1", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToRechargeCardTemp1(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("查看充值卡卡密") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/show/code", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToRechargeCard(@ApiParam("卡号") @RequestParam("code") String code) {; @ApiOperation("可兑换充值卡方式详情") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/show", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryExchangeToRechargeCard(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("充值卡兑换流程详情") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/info", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryExchangeToRechargeCardInfo(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("快递收货") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp2", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToExpress(@ApiParam("商品Id") @RequestParam("commId") Long commId, @ApiParam("注册用户地址Id") @RequestParam("addressId") Long addressId) {; @ApiOperation("到店领取") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp5", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToLocale(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; }
@Test public void testQueryExchangeToRechargeCard() throws Exception { }
CommodityExchangeController extends BaseController { @ApiOperation("充值卡兑换流程详情") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/info", method = {RequestMethod.POST, RequestMethod.GET}) public JSONObject queryExchangeToRechargeCardInfo(@ApiParam("商品Id") @RequestParam("commId") Long commId) { return success(emService.selectUserRechargeCardExchangeProcess(getUserId(), commId)); } @ApiOperation("查询商品兑换方式") @RequestMapping(value = "/api/v1/user/commodity/commexchways", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryCommExchangeWays(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("兑换现金") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp3", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToCash(@ApiParam("商品Id") @RequestParam("commId") Long commId, @ApiParam("平台名称(例:支付宝平台)") @RequestParam("TPName") String TPName, @ApiParam("平台账号") @RequestParam("TPAccount") String TPAccount) {; @ApiOperation("兑换闪币") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp4", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToGold(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("兑换充值卡") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/temp1", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToRechargeCardTemp1(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("查看充值卡卡密") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/show/code", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToRechargeCard(@ApiParam("卡号") @RequestParam("code") String code) {; @ApiOperation("可兑换充值卡方式详情") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/show", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryExchangeToRechargeCard(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("充值卡兑换流程详情") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/info", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryExchangeToRechargeCardInfo(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("快递收货") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp2", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToExpress(@ApiParam("商品Id") @RequestParam("commId") Long commId, @ApiParam("注册用户地址Id") @RequestParam("addressId") Long addressId) {; @ApiOperation("到店领取") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp5", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToLocale(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; }
@Test public void testQueryExchangeToRechargeCardInfo() throws Exception { }
CommodityExchangeController extends BaseController { @ApiOperation("快递收货") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp2", method = {RequestMethod.POST, RequestMethod.GET}) public JSONObject exchangeToExpress(@ApiParam("商品Id") @RequestParam("commId") Long commId, @ApiParam("注册用户地址Id") @RequestParam("addressId") Long addressId) { return success(emService.temp2(getUserId(), commId, addressId)); } @ApiOperation("查询商品兑换方式") @RequestMapping(value = "/api/v1/user/commodity/commexchways", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryCommExchangeWays(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("兑换现金") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp3", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToCash(@ApiParam("商品Id") @RequestParam("commId") Long commId, @ApiParam("平台名称(例:支付宝平台)") @RequestParam("TPName") String TPName, @ApiParam("平台账号") @RequestParam("TPAccount") String TPAccount) {; @ApiOperation("兑换闪币") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp4", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToGold(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("兑换充值卡") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/temp1", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToRechargeCardTemp1(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("查看充值卡卡密") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/show/code", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToRechargeCard(@ApiParam("卡号") @RequestParam("code") String code) {; @ApiOperation("可兑换充值卡方式详情") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/show", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryExchangeToRechargeCard(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("充值卡兑换流程详情") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/info", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryExchangeToRechargeCardInfo(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("快递收货") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp2", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToExpress(@ApiParam("商品Id") @RequestParam("commId") Long commId, @ApiParam("注册用户地址Id") @RequestParam("addressId") Long addressId) {; @ApiOperation("到店领取") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp5", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToLocale(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; }
@Test public void testExchangeToExpress() throws Exception { }
CommodityExchangeController extends BaseController { @ApiOperation("到店领取") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp5", method = {RequestMethod.POST, RequestMethod.GET}) public JSONObject exchangeToLocale(@ApiParam("商品Id") @RequestParam("commId") Long commId) { return success(emService.temp5(getUserId(), commId)); } @ApiOperation("查询商品兑换方式") @RequestMapping(value = "/api/v1/user/commodity/commexchways", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryCommExchangeWays(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("兑换现金") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp3", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToCash(@ApiParam("商品Id") @RequestParam("commId") Long commId, @ApiParam("平台名称(例:支付宝平台)") @RequestParam("TPName") String TPName, @ApiParam("平台账号") @RequestParam("TPAccount") String TPAccount) {; @ApiOperation("兑换闪币") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp4", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToGold(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("兑换充值卡") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/temp1", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToRechargeCardTemp1(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("查看充值卡卡密") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/show/code", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToRechargeCard(@ApiParam("卡号") @RequestParam("code") String code) {; @ApiOperation("可兑换充值卡方式详情") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/show", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryExchangeToRechargeCard(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("充值卡兑换流程详情") @RequestMapping(value = "/api/v1/user/commodity/exchange/rcard/info", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryExchangeToRechargeCardInfo(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; @ApiOperation("快递收货") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp2", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToExpress(@ApiParam("商品Id") @RequestParam("commId") Long commId, @ApiParam("注册用户地址Id") @RequestParam("addressId") Long addressId) {; @ApiOperation("到店领取") @RequestMapping(value = "/api/v1/user/commodity/exchange/temp5", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject exchangeToLocale(@ApiParam("商品Id") @RequestParam("commId") Long commId) {; }
@Test public void testExchangeToLocale() throws Exception { }
MessageController extends BaseController { @ApiOperation(value = "queryAllMessageSize", notes = "查询所有的消息未读取消息数", responseContainer = "{object.put(\"0\", 20); " object.put(\"1\", 10); " object.put(\"2\", 0); @RequestMapping(value = "/query/count", method = {RequestMethod.POST, RequestMethod.GET}) public JSONObject queryAllMessageSize() { return success(messageService.queryAllMessageSize(getUserId())); } @ApiOperation(value = "queryAllMessageSize", notes = "查询所有的消息未读取消息数", responseContainer = "{object.put(\"0\", 20);//系统消息\n" + " object.put(\"1\", 10);//中奖消息\n" + " object.put(\"2\", 0);//发货消息}") @RequestMapping(value = "/query/count", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryAllMessageSize(); @ApiOperation(value = "消息列表查询", notes = "支持分页查询", responseContainer = "{title:标题,id:'1000',content:'内容',date:'日期'}", code = 200, produces = "application/json") @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", name = "typeid", dataType = "int", required = true), @ApiImplicitParam(paramType = "query", name = "msgid", dataType = "int", required = false) }) @RequestMapping(value = "/query/list", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryMessageByType(@RequestParam int typeid, @RequestParam(value = "msgid", required = false) String msgid); }
@Test public void testQueryAllMessageSize() throws Exception { JSONObject jsonObject = messageController.queryAllMessageSize(); System.out.println(jsonObject); }
MessageController extends BaseController { @ApiOperation(value = "消息列表查询", notes = "支持分页查询", responseContainer = "{title:标题,id:'1000',content:'内容',date:'日期'}", code = 200, produces = "application/json") @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", name = "typeid", dataType = "int", required = true), @ApiImplicitParam(paramType = "query", name = "msgid", dataType = "int", required = false) }) @RequestMapping(value = "/query/list", method = {RequestMethod.POST, RequestMethod.GET}) public JSONObject queryMessageByType(@RequestParam int typeid, @RequestParam(value = "msgid", required = false) String msgid) { JSONArray data = messageService.queryMessageByType(getUserId(), msgid, typeid); if (data == null) { return fail(-1, "请求错误"); } return success(data); } @ApiOperation(value = "queryAllMessageSize", notes = "查询所有的消息未读取消息数", responseContainer = "{object.put(\"0\", 20);//系统消息\n" + " object.put(\"1\", 10);//中奖消息\n" + " object.put(\"2\", 0);//发货消息}") @RequestMapping(value = "/query/count", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryAllMessageSize(); @ApiOperation(value = "消息列表查询", notes = "支持分页查询", responseContainer = "{title:标题,id:'1000',content:'内容',date:'日期'}", code = 200, produces = "application/json") @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", name = "typeid", dataType = "int", required = true), @ApiImplicitParam(paramType = "query", name = "msgid", dataType = "int", required = false) }) @RequestMapping(value = "/query/list", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryMessageByType(@RequestParam int typeid, @RequestParam(value = "msgid", required = false) String msgid); }
@Test public void testQueryMessageByType() throws Exception { }
UserServiceImpl implements IUserService { @Override public Map<String, Object> queryPersonalInfo(Long accountId) { User user = userMapper.selectById(accountId); Map<String, Object> map = new HashMap<>(); map.put("imgUrl", user.getHeaderUrl()); map.put("nickname", user.getNickname()); map.put("phone", user.getPhoneNumber()); map.put("qq", user.getQqNumber()); map.put("id", user.getAccountId()); map.put("codePicture", null); map.put("promId", user.getPromoterId()); map.put("promProf", 0); return map; } @Override boolean register(String phone, String password); @Override User queryUserByPhoneNum(String phone); @Override Map<String, Object> getUserInfo(Long accountId); @Override List<Map<String, Object>> selectHistoryLottery(Long accountId, Long lastCommId); Map<String, Object> selectExchange(Long commodityId); @Override List<Map<String, Object>> selectHistoryPay(Long accountId, Integer item); @Override boolean addPromoterId(Long accountId, Long promId); List<Map<String, Object>> selectToHistory(Long accountId); List<Map<String, Object>> selectToNew(Long accountId); List<String> luckUserList(Long accountId, Long commodityId); @Override User registerByOpenId(String openId, String password, String header_url, String nickname, String platform); @Override boolean checkOpenId(String token, String openId); @Override Map<String, Object> queryPersonalInfo(Long accountId); @Override List<String> selectGroupLuckCode(Long accountId, String lastCode); @Override User queryByOpenId(String openId, String platform); @Override User registerAndLoginThirdParty(ThirdPartyLoginToken token); int insertUser(User user, ThirdPartyLoginToken token); @Override int addPromoter(Long promId, Long accountId); @Override boolean addQQNumber(Long accountId, String qq); @Override List<Map<String, Object>> selectPurchaseRecords(Integer item, Long accountId, Long lastCommId); List<String> selectUserLuckCode(Long accountId, Long commId, String lastCode); @Override boolean updateUserNickname(Long accountId, String nickname); void giveRegisterRedPackets(Long accountId); }
@Test public void testQueryPersonalInfo() throws Exception { userService.queryPersonalInfo(10000L); }
UserController extends BaseController { @ResponseBody @ApiOperation("添加推广员Id") @RequestMapping(value = "/api/v1/user/promoter/add/promote", method = {RequestMethod.POST, RequestMethod.GET}) public JSONObject addPromoter(@ApiParam("推广员Id") @RequestParam("promId") Long promId) { int re = userService.addPromoter(promId, getUserId()); if (re == 1) { return success(); } else if (re == -1) { return fail("推广人id不存在"); } else { return fail("已有推广人或用户注册时间早于推广人"); } } @ResponseBody @ApiOperation("Android端用户个人中心信息接口") @RequestMapping(value = "/api/v1/user/center", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryUserCenter(); @ResponseBody @ApiOperation("Android端“我”的用户信息(头像、昵称、推广id、积分、闪币)") @RequestMapping(value = "/api/v1/user/info", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryUserInfo(); @ResponseBody @ApiOperation("获取用户中奖记录(带分页)") @RequestMapping(value = "/api/v1/user/win", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryUserWinningHistory(@ApiParam("当前页最后一item的实际id") @RequestParam("lastCommId") Long lastCommId) {; @ResponseBody @ApiOperation("获取用户夺宝记录(带分页)") @RequestMapping(value = "/api/v1/user/usercomm/show", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryUserCommRecord(@ApiParam("item(显示形式):1、进行中;2、已揭晓;其他数字显示全部") @RequestParam("item") Integer item, @ApiParam("最后一个商品Id") @RequestParam("lastCommId") Long lastCommId) {; @ResponseBody @ApiOperation("获取用户夺宝记录中的luckCode带分页") @RequestMapping(value = "/api/v1/priv/user/usercomm/code/show", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryUserLuckCode(@ApiParam("回传最后一个Code码") @RequestParam("commId") Long commId, @ApiParam("回传最后一个Code码") @RequestParam(name = "lastCode", required = false) String lastCode) {; @ResponseBody @ApiOperation("用户签到接口") @RequestMapping(value = "/api/v1/user/sign/add", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject addUserSign(); @ResponseBody @ApiOperation("用户签到信息") @RequestMapping(value = "/api/v1/user/sign/show", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryUserSign(); @ResponseBody @ApiOperation("用户上传头像(tip:接口暂时未使用也未实现功能)") @RequestMapping(value = "/api/v1/user/upload/headimg.do", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject uploadUserImg(@RequestParam("accountId") Long accountId, @RequestParam("photo") MultipartFile imgFile); @ResponseBody @ApiOperation("修改用户昵称") @RequestMapping(value = "/api/v1/user/update/nickname", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject updateUserNickName(@RequestParam("nickname") String nickname); @ResponseBody @ApiOperation("修改电话号码(tip:未实现功能)") @RequestMapping(value = "/api/v1/user/update/phone", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject updatePhone(@RequestParam("phone") String phone, @RequestParam("imgCode") String imgCode, @RequestParam("SMSCode") String SMSCode); @ResponseBody @ApiOperation("修改QQ号") @RequestMapping(value = "/api/v1/user/update/qq", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject updateQQNumber(@RequestParam("qq") String QQ); @ResponseBody @ApiOperation("推广员收益信息(带分页)") @RequestMapping(value = "/api/v1/user/promoter/profit/info", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryPromoterProfit(); @ResponseBody @ApiOperation("添加推广员Id") @RequestMapping(value = "/api/v1/user/promoter/add/promote", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject addPromoter(@ApiParam("推广员Id") @RequestParam("promId") Long promId) {; }
@Test public void testAddPromoter() throws Exception { JSONObject jsonObject = userController.addPromoter(10444L); System.out.println(jsonObject); }
UserController extends BaseController { @ResponseBody @ApiOperation("获取用户夺宝记录(带分页)") @RequestMapping(value = "/api/v1/user/usercomm/show", method = {RequestMethod.POST, RequestMethod.GET}) public JSONObject queryUserCommRecord(@ApiParam("item(显示形式):1、进行中;2、已揭晓;其他数字显示全部") @RequestParam("item") Integer item, @ApiParam("最后一个商品Id") @RequestParam("lastCommId") Long lastCommId) { List<Map<String, Object>> historyLottery = userService.selectPurchaseRecords(item, getUserId(), lastCommId); return success(historyLottery); } @ResponseBody @ApiOperation("Android端用户个人中心信息接口") @RequestMapping(value = "/api/v1/user/center", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryUserCenter(); @ResponseBody @ApiOperation("Android端“我”的用户信息(头像、昵称、推广id、积分、闪币)") @RequestMapping(value = "/api/v1/user/info", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryUserInfo(); @ResponseBody @ApiOperation("获取用户中奖记录(带分页)") @RequestMapping(value = "/api/v1/user/win", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryUserWinningHistory(@ApiParam("当前页最后一item的实际id") @RequestParam("lastCommId") Long lastCommId) {; @ResponseBody @ApiOperation("获取用户夺宝记录(带分页)") @RequestMapping(value = "/api/v1/user/usercomm/show", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryUserCommRecord(@ApiParam("item(显示形式):1、进行中;2、已揭晓;其他数字显示全部") @RequestParam("item") Integer item, @ApiParam("最后一个商品Id") @RequestParam("lastCommId") Long lastCommId) {; @ResponseBody @ApiOperation("获取用户夺宝记录中的luckCode带分页") @RequestMapping(value = "/api/v1/priv/user/usercomm/code/show", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryUserLuckCode(@ApiParam("回传最后一个Code码") @RequestParam("commId") Long commId, @ApiParam("回传最后一个Code码") @RequestParam(name = "lastCode", required = false) String lastCode) {; @ResponseBody @ApiOperation("用户签到接口") @RequestMapping(value = "/api/v1/user/sign/add", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject addUserSign(); @ResponseBody @ApiOperation("用户签到信息") @RequestMapping(value = "/api/v1/user/sign/show", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryUserSign(); @ResponseBody @ApiOperation("用户上传头像(tip:接口暂时未使用也未实现功能)") @RequestMapping(value = "/api/v1/user/upload/headimg.do", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject uploadUserImg(@RequestParam("accountId") Long accountId, @RequestParam("photo") MultipartFile imgFile); @ResponseBody @ApiOperation("修改用户昵称") @RequestMapping(value = "/api/v1/user/update/nickname", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject updateUserNickName(@RequestParam("nickname") String nickname); @ResponseBody @ApiOperation("修改电话号码(tip:未实现功能)") @RequestMapping(value = "/api/v1/user/update/phone", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject updatePhone(@RequestParam("phone") String phone, @RequestParam("imgCode") String imgCode, @RequestParam("SMSCode") String SMSCode); @ResponseBody @ApiOperation("修改QQ号") @RequestMapping(value = "/api/v1/user/update/qq", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject updateQQNumber(@RequestParam("qq") String QQ); @ResponseBody @ApiOperation("推广员收益信息(带分页)") @RequestMapping(value = "/api/v1/user/promoter/profit/info", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryPromoterProfit(); @ResponseBody @ApiOperation("添加推广员Id") @RequestMapping(value = "/api/v1/user/promoter/add/promote", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject addPromoter(@ApiParam("推广员Id") @RequestParam("promId") Long promId) {; }
@Test public void testQueryUserCommRecord() throws Exception { JSONObject jsonObject=new JSONObject(); jsonObject.put("item",1); jsonObject.put("page",1); post("/api/v1/user/usercomm/show",jsonObject.toJSONString()); }
PayController extends BaseController { @ApiOperation(value = "支付宝支付,创建订单接口") @RequestMapping(value = "/api/v1/user/order/alipay", method = RequestMethod.POST) public JSONObject createOrderByAlipay(@Valid @RequestBody OrderFormData param, BindingResult br){ if(br.hasErrors()){ LOG.debug(br.getAllErrors()); return fail(-1,"参数错误"); } try { param.getOrder().setUserAccountId(getUserId()); JSONObject result = aliPayService.createTemporaryOrder(param); return success("",result.toString()); }catch (Exception e){ return fail(-1,"订单创建失败"); } } @ApiOperation(value = "支付宝支付,创建订单接口") @RequestMapping(value = "/api/v1/user/order/alipay", method = RequestMethod.POST) JSONObject createOrderByAlipay(@Valid @RequestBody OrderFormData param, BindingResult br); @ApiOperation(value = "支付成功,支付宝异步通知接口") @RequestMapping(value = "/api/v1/pub/user/order/alipay/callback",method = RequestMethod.POST) void alipayCallback(HttpServletRequest request,HttpServletResponse response); @ResponseBody @ApiOperation(value = "接收支付宝返回的请求参数") @RequestMapping(value = "/api/v1/pub/orders/alipay/callbacks.do", produces = "text/html;charset=UTF-8", method = {RequestMethod.POST}) String callbacks(HttpServletRequest request); @RequestMapping(value = "/api/v1/user/order/alipay/query", method = RequestMethod.POST) void orderPayQuery(HttpServletRequest request, HttpServletResponse response, String tradeno, String orderno, String callback); @RequestMapping(value = "/api/v1/user/order/wxpay/notify", method = RequestMethod.POST) void orderPayNotify(HttpServletRequest request, HttpServletResponse response); @RequestMapping(value = "/api/v1/user/order/alipay/refund", method = RequestMethod.POST) void orderPayRefund(HttpServletRequest request, HttpServletResponse response, String tradeno, String orderno, String callback); @RequestMapping(value = "/api/v1/user/order/alipay/refund/query", method = RequestMethod.POST) void orderPayRefundQuery(HttpServletRequest request, HttpServletResponse response, String orderno, String tradeno, String callback); }
@Test public void testCreateOrderByAlipay() throws Exception { }
PayController extends BaseController { @ApiOperation(value = "支付成功,支付宝异步通知接口") @RequestMapping(value = "/api/v1/pub/user/order/alipay/callback",method = RequestMethod.POST) public void alipayCallback(HttpServletRequest request,HttpServletResponse response) throws Exception { Map params = request.getParameterMap(); String notify_id = (String) params.get("notify_id"); if(notify_id!="" && notify_id!=null){ String trade_status = (String) params.get("trade_status"); if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){ response.getWriter().print("success"); } else if (trade_status.equals("WAIT_BUYER_PAY")){ boolean b = aliPayService.checkAliPayOrderValidator(params); response.getWriter().print(b?"success":"fail"); } }else{ LOG.debug("订单支付失败,不是异步消息通知,notify_id等于空"); response.getWriter().print("fail"); } } @ApiOperation(value = "支付宝支付,创建订单接口") @RequestMapping(value = "/api/v1/user/order/alipay", method = RequestMethod.POST) JSONObject createOrderByAlipay(@Valid @RequestBody OrderFormData param, BindingResult br); @ApiOperation(value = "支付成功,支付宝异步通知接口") @RequestMapping(value = "/api/v1/pub/user/order/alipay/callback",method = RequestMethod.POST) void alipayCallback(HttpServletRequest request,HttpServletResponse response); @ResponseBody @ApiOperation(value = "接收支付宝返回的请求参数") @RequestMapping(value = "/api/v1/pub/orders/alipay/callbacks.do", produces = "text/html;charset=UTF-8", method = {RequestMethod.POST}) String callbacks(HttpServletRequest request); @RequestMapping(value = "/api/v1/user/order/alipay/query", method = RequestMethod.POST) void orderPayQuery(HttpServletRequest request, HttpServletResponse response, String tradeno, String orderno, String callback); @RequestMapping(value = "/api/v1/user/order/wxpay/notify", method = RequestMethod.POST) void orderPayNotify(HttpServletRequest request, HttpServletResponse response); @RequestMapping(value = "/api/v1/user/order/alipay/refund", method = RequestMethod.POST) void orderPayRefund(HttpServletRequest request, HttpServletResponse response, String tradeno, String orderno, String callback); @RequestMapping(value = "/api/v1/user/order/alipay/refund/query", method = RequestMethod.POST) void orderPayRefundQuery(HttpServletRequest request, HttpServletResponse response, String orderno, String tradeno, String callback); }
@Test public void testAlipayCallback() throws Exception { String content = "discount=0.00&payment_type=1&subject=测试&trade_no=2013082244524842&[email protected]&gmt_create=2013-08-22 14:45:23&notify_type=trade_status_sync&quantity=1&out_trade_no=082215222612710&seller_id=2088501624816263&notify_time=2013-08-22 14:45:24&body=测试测试&trade_status=TRADE_SUCCESS&is_total_fee_adjust=N&total_fee=1.00&gmt_payment=2013-08-22 14:45:24&[email protected]&price=1.00&buyer_id=2088602315385429&notify_id=64ce1b6ab92d00ede0ee56ade98fdf2f4c&use_coupon=N&sign_type=RSA&sign=1glihU9DPWee+UJ82u3+mw3Bdnr9u01at0M/xJnPsGuHh+JA5bk3zbWaoWhU6GmLab3dIM4JNdktTcEUI9/FBGhgfLO39BKX/eBCFQ3bXAmIZn4l26fiwoO613BptT44GTEtnPiQ6+tnLsGlVSrFZaLB9FVhrGfipH2SWJcnwYs="; post("/api/v1/pub/user/order/alipay/callback",content, MediaType.APPLICATION_FORM_URLENCODED); }
WebController { @RequestMapping("/commodityCalc/{id}") public String calc(@PathVariable("id") Long id, Model model) { final LotteryInfo lotteryInfo = lotteryInfoService.selectLottery(id); model.addAttribute("info", lotteryInfo == null ? new LotteryInfo() : lotteryInfo); if (null == lotteryInfo) { final Commoditys commoditys = cService.getDetails(id); if (commoditys == null) { model.addAttribute("buyTotalNumber", "未能获取到相关信息"); } else model.addAttribute("buyTotalNumber", commoditys.getBuyTotalNumber()); } return "calc"; } @RequestMapping("/commodityInfo/{id}") String commodityInfo(@PathVariable("id") Long id, Map<String, Object> model); @RequestMapping("/commodityCalc/{id}") String calc(@PathVariable("id") Long id, Model model); @RequestMapping("/activities") String getActivities(Model model); @RequestMapping("/share/view/{id}") String share(@PathVariable Long id, Model model); }
@Test public void testCalc(){ try { get("/web/commodityCalc/29",""); } catch (Exception e) { e.printStackTrace(); } }
CommoditysController extends BaseController { @ResponseBody @RequestMapping(value = "/api/v1/pub/commodity/onlottery", method = {RequestMethod.POST, RequestMethod.GET}) public JSONObject queryOnLotteryInfo(@RequestParam("page") int page) { List<Map<String, Object>> mapList = cService.selectOnLottery(page); return success(mapList); } @ResponseBody @ApiOperation("搜索商品信息(默认搜所有)参数:category 类型;commName 商品名; lastCommName 最后一个商品Id") @RequestMapping(value = "/api/v1/pub/commodity/search", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryCommoditys(@RequestParam(name = "categoryId", required = false) Integer categoryId, @RequestParam(name = "commName", required = false) String commName, @RequestParam(name = "lastCommId", required = false) Long lastCommId); @ResponseBody @RequestMapping(value = "/api/v1/pub/commodity/recommend", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryRecommend(); @ResponseBody @RequestMapping(value = "/api/v1/pub/commodity/search/category", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryCommoditys(@RequestParam("categoryId") Integer categoryId, @RequestParam("lastCommId") Long lastCommId); @ResponseBody @RequestMapping(value = "/api/v1/pub/commodity/search/name", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryCommoditys(@RequestParam("name") String name, @RequestParam("lastCommId") Long lastCommId); @ResponseBody @ApiOperation("查看单件商品详情") @RequestMapping(value = "/api/v1/pub/commodity/info", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryCommoditysInfo(@RequestParam("commid") Long commodityid); @ResponseBody @RequestMapping(value = "/api/v1/pub/commodity/onlottery", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryOnLotteryInfo(@RequestParam("page") int page); @ResponseBody @ApiOperation("查看单件正在开奖的商品") @RequestMapping(value = "/api/v1/pub/commodity/onlottery/one", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryOnLotteryInfo(@RequestParam("commId") Long commId); @ResponseBody @ApiOperation("最新揭晓") @RequestMapping(value = "/api/v1/pub/commodity/announce", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject queryNewestAnnounced(@RequestParam("lastCommId") Long lastCommId); }
@Test public void testQueryOnLotteryInfo() throws Exception { JSONObject object = new JSONObject(); object.put("page",1); post("/api/v1/pub/commodity/onlottery",object.toJSONString()); }
AppIndexController extends BaseController { @ResponseBody @RequestMapping(value = "/api/v1/index/banner", method = {RequestMethod.POST, RequestMethod.GET}) public JSONObject banner() { List<Map<String, Object>> infoList = adService.selectAdvertisement(); return success(infoList); } @ResponseBody @RequestMapping(value = "/api/v1/index/banner", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject banner(); @ResponseBody @RequestMapping(value = "/api/v1/index/quick", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject quick(); @ResponseBody @RequestMapping(value = "/api/v1/index/notice", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject notice(); @ResponseBody @RequestMapping(value = "/api/v1/index/announce", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject announceCommodityInfo(); @ResponseBody @ApiOperation("客户端首页商品板块信息(默认人气搜索)参数:type 排序类型(1、按人气,2、按最快,3、最新,4、高价,5高中奖率,14,三人夺宝,其他数字默认人气)") @RequestMapping(value = "/api/v1/index/commodity", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject orderCommodityInfo(@ApiParam("排序类型") @RequestParam(name = "type",required = false) Integer type, @ApiParam("当前页最后一个item的id") @RequestParam(name = "lastCommId",required = false) Long lastCommId) {; }
@Test public void testBanner() throws Exception { }
AppIndexController extends BaseController { @ResponseBody @RequestMapping(value = "/api/v1/index/quick", method = {RequestMethod.POST, RequestMethod.GET}) public JSONObject quick() { List<Map<String, Object>> infoList = iService.selectIcon(); return success(infoList); } @ResponseBody @RequestMapping(value = "/api/v1/index/banner", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject banner(); @ResponseBody @RequestMapping(value = "/api/v1/index/quick", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject quick(); @ResponseBody @RequestMapping(value = "/api/v1/index/notice", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject notice(); @ResponseBody @RequestMapping(value = "/api/v1/index/announce", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject announceCommodityInfo(); @ResponseBody @ApiOperation("客户端首页商品板块信息(默认人气搜索)参数:type 排序类型(1、按人气,2、按最快,3、最新,4、高价,5高中奖率,14,三人夺宝,其他数字默认人气)") @RequestMapping(value = "/api/v1/index/commodity", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject orderCommodityInfo(@ApiParam("排序类型") @RequestParam(name = "type",required = false) Integer type, @ApiParam("当前页最后一个item的id") @RequestParam(name = "lastCommId",required = false) Long lastCommId) {; }
@Test public void testQuick() throws Exception { }
AppIndexController extends BaseController { @ResponseBody @RequestMapping(value = "/api/v1/index/notice", method = {RequestMethod.POST, RequestMethod.GET}) public JSONObject notice() { return success(npService.selectUserPrizeNotify(getUserId())); } @ResponseBody @RequestMapping(value = "/api/v1/index/banner", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject banner(); @ResponseBody @RequestMapping(value = "/api/v1/index/quick", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject quick(); @ResponseBody @RequestMapping(value = "/api/v1/index/notice", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject notice(); @ResponseBody @RequestMapping(value = "/api/v1/index/announce", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject announceCommodityInfo(); @ResponseBody @ApiOperation("客户端首页商品板块信息(默认人气搜索)参数:type 排序类型(1、按人气,2、按最快,3、最新,4、高价,5高中奖率,14,三人夺宝,其他数字默认人气)") @RequestMapping(value = "/api/v1/index/commodity", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject orderCommodityInfo(@ApiParam("排序类型") @RequestParam(name = "type",required = false) Integer type, @ApiParam("当前页最后一个item的id") @RequestParam(name = "lastCommId",required = false) Long lastCommId) {; }
@Test public void testNotice() throws Exception { }
AuthorController extends BaseController { @ResponseBody @RequestMapping(value = "/api/v1/pub/auth/login", method = RequestMethod.POST) public JSONObject login(@RequestBody(required = true) CaptchaUsernamePasswordToken token) { Subject subject = SecurityUtils.getSubject(); token.setRememberMe(false); if (!subject.isAuthenticated()) { String msg = null; try { subject.login(token); return success(); } catch (UnknownAccountException e) { msg = "账号错误"; return fail(-1, msg); } catch (LockedAccountException e) { msg = "账号被禁用"; return fail(-1, msg); } catch (ExcessiveAttemptsException e) { msg = e.getMessage(); return fail(-2, msg); } catch (AuthenticationException e) { msg = "用户名或密码错误"; return fail(-1, msg); } } else { return success(); } } @RequestMapping(value = "/api/v1/pub/error/403", method = {RequestMethod.GET, RequestMethod.POST}) JSONObject error403(); @ApiOperation(value = "partyLogin", notes = "第三方登录", httpMethod = "POST") @ApiImplicitParams( { @ApiImplicitParam(name = "openid", value = "openid", paramType = "query", dataType = "string"), @ApiImplicitParam(name = "access_token", value = "access_token", paramType = "query", dataType = "string"), @ApiImplicitParam(name = "platform", value = "平台类型,1=QQ,2=微信", paramType = "query", dataType = "int"), @ApiImplicitParam(name = "nickName", value = "昵称", paramType = "query", dataType = "string"), @ApiImplicitParam(name = "headImg", value = "平台类型,1=QQ,2=微信", paramType = "query", dataType = "string") } ) @RequestMapping(value = "/api/v1/pub/party/login", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject partyLogin( @RequestParam(value = "openid", required = true) String openid, @RequestParam(value = "access_token", required = true) String accessToken, @RequestParam(value = "platform", required = true) int platform, @RequestParam(value = "nickName", required = true) String nickName, @RequestParam(value = "headImg", required = true) String headImg ); @ResponseBody @RequestMapping(value = "/api/v1/pub/auth/login", method = RequestMethod.POST) JSONObject login(@RequestBody(required = true) CaptchaUsernamePasswordToken token); @ResponseBody @RequestMapping(value = "/api/v1/pub/auth/logout", method = {RequestMethod.POST, RequestMethod.GET}) void logout(); @ResponseBody @RequestMapping(value = "/api/v1/pub/auth/register", method = RequestMethod.POST) JSONObject register( @RequestParam("phone") String phone, @RequestParam("password") String password, @RequestParam("SMSCode") String smscode); }
@Test public void testLogin() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("username", "18381690821"); jsonObject.put("password", "123456"); post("/api/v1/auth/login", jsonObject.toJSONString()); }
ShareServiceImpl implements IShareService { @Override public List<Map<String, Object>> selectByUserAccountId(Long accountId, Long lastCommId) { List<Share> shareList = shareMapper.selectByUserAccountId(accountId, lastCommId, Settings.PAGE_LOAD_SIZE_10); List<Map<String, Object>> mapList = createShareMapList(accountId, shareList); return mapList; } @Override String getUpToken(String suffix); @Override String uploadToQiniu(MultipartFile file); @Override String getUpToken(); @Override boolean isReady(); @Override Share getShare(Long shareId); @Override boolean addShare(Long accountId, Long commId, String desc, List<MultipartFile> imgs); @Override boolean deleteShare(Long shareid); @Override List<Share> selectShare(Long accountid, Long lastshareid, Integer tag); @Override boolean friendsShare(Long account); @Override List<Map<String, Object>> selectByUserAccountId(Long accountId, Long lastCommId); @Override List<Map<String, Object>> selectAll(Long lastCommId); @Override List<Map<String, Object>> selectByCommId(Long commId, Long lastCommId); List<String> imgUrl(Share s); }
@Test public void testSelectByUserAccountId() throws Exception { List<Map<String, Object>> mapList = shareService.selectByUserAccountId(10000L, 0L); System.out.println(mapList.size()); }
AuthorController extends BaseController { @ResponseBody @RequestMapping(value = "/api/v1/pub/auth/register", method = RequestMethod.POST) public JSONObject register( @RequestParam("phone") String phone, @RequestParam("password") String password, @RequestParam("SMSCode") String smscode) { boolean isOk = captchaService.validatorImageCode(phone, smscode); if (isOk) { fail(-1, "验证码无效"); } else { isOk = usersService.register(phone, password); if (!isOk) { return fail(-1, "注册失败"); } } return success(); } @RequestMapping(value = "/api/v1/pub/error/403", method = {RequestMethod.GET, RequestMethod.POST}) JSONObject error403(); @ApiOperation(value = "partyLogin", notes = "第三方登录", httpMethod = "POST") @ApiImplicitParams( { @ApiImplicitParam(name = "openid", value = "openid", paramType = "query", dataType = "string"), @ApiImplicitParam(name = "access_token", value = "access_token", paramType = "query", dataType = "string"), @ApiImplicitParam(name = "platform", value = "平台类型,1=QQ,2=微信", paramType = "query", dataType = "int"), @ApiImplicitParam(name = "nickName", value = "昵称", paramType = "query", dataType = "string"), @ApiImplicitParam(name = "headImg", value = "平台类型,1=QQ,2=微信", paramType = "query", dataType = "string") } ) @RequestMapping(value = "/api/v1/pub/party/login", method = {RequestMethod.POST, RequestMethod.GET}) JSONObject partyLogin( @RequestParam(value = "openid", required = true) String openid, @RequestParam(value = "access_token", required = true) String accessToken, @RequestParam(value = "platform", required = true) int platform, @RequestParam(value = "nickName", required = true) String nickName, @RequestParam(value = "headImg", required = true) String headImg ); @ResponseBody @RequestMapping(value = "/api/v1/pub/auth/login", method = RequestMethod.POST) JSONObject login(@RequestBody(required = true) CaptchaUsernamePasswordToken token); @ResponseBody @RequestMapping(value = "/api/v1/pub/auth/logout", method = {RequestMethod.POST, RequestMethod.GET}) void logout(); @ResponseBody @RequestMapping(value = "/api/v1/pub/auth/register", method = RequestMethod.POST) JSONObject register( @RequestParam("phone") String phone, @RequestParam("password") String password, @RequestParam("SMSCode") String smscode); }
@Test public void testRegister() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("phone", "1234567"); jsonObject.put("password", "1234567"); post("/api/v1/auth/register?phone=1234567&password=1234567", jsonObject.toJSONString()); }
ShareServiceImpl implements IShareService { @Override public List<Map<String, Object>> selectAll(Long lastCommId) { List<Share> shareList = shareMapper.selectAllWithPage(lastCommId, Settings.PAGE_LOAD_SIZE_10); List<Map<String, Object>> mapList = createShareMapList(null, shareList); return mapList; } @Override String getUpToken(String suffix); @Override String uploadToQiniu(MultipartFile file); @Override String getUpToken(); @Override boolean isReady(); @Override Share getShare(Long shareId); @Override boolean addShare(Long accountId, Long commId, String desc, List<MultipartFile> imgs); @Override boolean deleteShare(Long shareid); @Override List<Share> selectShare(Long accountid, Long lastshareid, Integer tag); @Override boolean friendsShare(Long account); @Override List<Map<String, Object>> selectByUserAccountId(Long accountId, Long lastCommId); @Override List<Map<String, Object>> selectAll(Long lastCommId); @Override List<Map<String, Object>> selectByCommId(Long commId, Long lastCommId); List<String> imgUrl(Share s); }
@Test public void testSelectAll() throws Exception { }
Adjuster implements Serializable { public Iterable<Span> adjust(final Iterable<Span> trace) { if (trace == null) throw new NullPointerException("trace was null"); return () -> new AdjustingIterator(this, trace.iterator()); } Iterable<Span> adjust(final Iterable<Span> trace); }
@Test public void unmodifiable() { thrown.expect(UnsupportedOperationException.class); Adjuster adjuster = new Adjuster() { }; Iterable<Span> adjusted = adjuster.adjust(TestObjects.TRACE); adjusted.iterator().remove(); } @Test public void defaultsToPassAllWithoutAdjusting() { Adjuster adjuster = new Adjuster() { }; assertThat(adjuster.adjust(TestObjects.TRACE)) .containsExactlyElementsOf(TestObjects.TRACE); } @Test public void canOverrideEverything() { Span clientSide = Span.builder().traceId(10L).id(10L).name("") .addAnnotation(Annotation.create((TODAY + 50) * 1000, CLIENT_SEND, WEB_ENDPOINT)) .addAnnotation(Annotation.create((TODAY + 300) * 1000, CLIENT_RECV, WEB_ENDPOINT)) .build(); Span serverSide = Span.builder().traceId(10L).id(10L).name("get") .addAnnotation(Annotation.create((TODAY + 100) * 1000, SERVER_RECV, APP_ENDPOINT)) .addAnnotation(Annotation.create((TODAY + 250) * 1000, SERVER_SEND, APP_ENDPOINT)) .build(); Adjuster adjuster = new Adjuster() { @Override public Iterable<Span> adjust(Iterable<Span> trace) { return MergeById.apply(Lists.newArrayList(trace)); } }; assertThat(adjuster.adjust(asList(clientSide, serverSide))) .containsExactlyElementsOf(MergeById.apply(asList(clientSide, serverSide))); } @Test public void adjust() { Adjuster adjuster = new Adjuster() { @Override protected Span adjust(Span span) { return ApplyTimestampAndDuration.apply(span); } }; assertThat(adjuster.adjust(TestObjects.TRACE)) .extracting(s -> s.timestamp, s -> s.duration) .doesNotContainNull(); }
ZookeeperBootstrapServers implements BootstrapServers { public static Builder newBuilder() { return new AutoValue_ZookeeperBootstrapServers.Builder() .sessionTimeout(10000); } ZookeeperBootstrapServers(); static Builder newBuilder(); @Override List<String> get(); }
@Test public void buildFailOnMissingProperties() throws Exception { thrown.expect(IllegalStateException.class); thrown.expectMessage("Missing required properties: connect"); ZookeeperBootstrapServers servers = ZookeeperBootstrapServers.newBuilder().build(); }
KafkaStreamFactory implements StreamFactory { public static Builder newBuilder() { return new AutoValue_KafkaStreamFactory.Builder() .topic("zipkin") .groupId("zipkin"); } KafkaStreamFactory(); static Builder newBuilder(); @Override JavaDStream<byte[]> create(JavaStreamingContext jsc); }
@Test public void buildFailOnMissingProperties() throws Exception { thrown.expect(IllegalStateException.class); thrown.expectMessage("Missing required properties: bootstrapServers"); KafkaStreamFactory streamFactory = KafkaStreamFactory.newBuilder().build(); }
FinagleAdjuster extends Adjuster { @Override protected Span adjust(Span span) { if (applyTimestampAndDuration()) { return ApplyTimestampAndDuration.apply(span); } return span; } FinagleAdjuster(); static Builder newBuilder(); }
@Test public void adjustsFinagleSpans() throws Exception { Iterable<Span> adjusted = adjuster.adjust(asList(serverSpan)); assertThat(adjusted).containsExactly(ApplyTimestampAndDuration.apply(serverSpan)); } @Test public void doesntAdjustNonFinagleSpans() throws Exception { Iterable<Span> adjusted = adjuster.adjust(TestObjects.TRACE); assertThat(adjusted).containsExactlyElementsOf(TestObjects.TRACE); }
FinagleIssue343Adjuster extends Adjuster { @Override protected Span adjust(Span span) { List<Annotation> annotations = new ArrayList<>(); for (Annotation a : span.annotations) { if (!a.value.equals("finagle.flush")) { annotations.add(a); } } return span.toBuilder().annotations(annotations).build(); } FinagleIssue343Adjuster(); static FinagleIssue343Adjuster create(); }
@Test public void adjustSpanWithFinagleFlush() { Iterable<Span> adjusted = adjuster.adjust(asList(serverSpanWithFinagleFlush)); assertThat(adjusted).containsExactly(serverSpan); } @Test public void hitOrMissBinaryAnnotationMissing() { Iterable<Span> adjusted = adjuster.adjust(asList(serverSpanWithFinagleFlushWithoutHitBinaryAnnotation)); assertThat(adjusted).containsExactly(serverSpanWithFinagleFlushWithoutHitBinaryAnnotation); } @Test public void doesntAdjustNonFinagleSpans() throws Exception { Iterable<Span> adjusted = adjuster.adjust(TestObjects.TRACE); assertThat(adjusted).containsExactlyElementsOf(TestObjects.TRACE); }
Adjuster implements Serializable { protected boolean shouldAdjust(Span span) { return false; } Iterable<Span> adjust(final Iterable<Span> trace); }
@Test public void shouldAdjust() { Adjuster adjuster = new Adjuster() { @Override protected boolean shouldAdjust(Span span) { for (Annotation a : span.annotations) { if (a.value.equals(Constants.SERVER_RECV) && span.parentId == null) return true; } return false; } @Override protected Span adjust(Span span) { return ApplyTimestampAndDuration.apply(span); } }; assertThat(adjuster.adjust(TestObjects.TRACE)).containsExactly( ApplyTimestampAndDuration.apply(TestObjects.TRACE.get(0)), TestObjects.TRACE.get(1), TestObjects.TRACE.get(2) ); }
StorageConsumer implements Consumer, Component { @Override public final void accept(Iterable<Span> spansSharingId) { List<Span> list = asList(spansSharingId); if (list.isEmpty()) { log().debug("Input was empty"); return; } CallbackCaptor<Void> blockingCallback = new CallbackCaptor<>(); try { get().asyncSpanConsumer().accept(list, blockingCallback); blockingCallback.get(); log().debug("Wrote {} spans", list.size()); } catch (RuntimeException e) { Throwable toLog = e.getClass().equals(RuntimeException.class) && e.getCause() != null ? e.getCause() : e; String message = "Dropped " + list.size() + " spans: " + toLog.getMessage(); if (log().isWarnEnabled()) { log().warn(message, toLog); } else { log().warn(message); } } } @Override final void accept(Iterable<Span> spansSharingId); @Override CheckResult check(); @Override final void close(); }
@Test public void logsWhenEmpty() { storageConsumer.accept(Collections.emptyList()); assertThat(logger.lines()) .extracting("level", "text") .containsExactly(tuple(LogLevel.DebugLevel, "Input was empty")); } @Test public void logsOnAcceptError() { IllegalStateException acceptException = new IllegalStateException("failed"); AsyncSpanConsumer consumer = mock(AsyncSpanConsumer.class); when(storage.asyncSpanConsumer()).thenReturn(consumer); doAnswer(answer(c -> { throw acceptException; })).when(consumer).accept(eq(TestObjects.TRACE), any(Callback.class)); storageConsumer.accept(TestObjects.TRACE); assertThat(logger.lines()).hasSize(1); assertThat(logger.lines().iterator().next().toString()) .startsWith("LogMessage(,WARN,Dropped 3 spans: failed"); } @Test public void logsOnCallbackError() { IllegalStateException callbackException = new IllegalStateException("failed"); AsyncSpanConsumer consumer = mock(AsyncSpanConsumer.class); when(storage.asyncSpanConsumer()).thenReturn(consumer); doAnswer(answer(c -> c.onError(callbackException))) .when(consumer).accept(eq(TestObjects.TRACE), any(Callback.class)); storageConsumer.accept(TestObjects.TRACE); assertThat(logger.lines()).hasSize(1); assertThat(logger.lines().iterator().next().toString()) .startsWith("LogMessage(,WARN,Dropped 3 spans: failed"); } @Test public void doesntWrapCheckedExceptionOnCallbackError() { IOException callbackException = new IOException("failed"); AsyncSpanConsumer consumer = mock(AsyncSpanConsumer.class); when(storage.asyncSpanConsumer()).thenReturn(consumer); doAnswer(answer(c -> c.onError(callbackException))) .when(consumer).accept(eq(TestObjects.TRACE), any(Callback.class)); storageConsumer.accept(TestObjects.TRACE); assertThat(logger.lines()).hasSize(1); assertThat(logger.lines().iterator().next().toString()) .startsWith("LogMessage(,WARN,Dropped 3 spans: failed"); }
StorageConsumer implements Consumer, Component { final StorageComponent get() { StorageComponent result = instance; if (result == null) { synchronized (this) { result = instance; if (result == null) { instance = result = tryCompute(); } } } return result; } @Override final void accept(Iterable<Span> spansSharingId); @Override CheckResult check(); @Override final void close(); }
@Test(timeout = 1000L) public void get_memoizes() throws InterruptedException { AtomicInteger provisionCount = new AtomicInteger(); StorageConsumer storageConsumer = new StorageConsumer() { @Override protected StorageComponent tryCompute() { provisionCount.incrementAndGet(); return new InMemoryStorage(); } }; int getCount = 1000; CountDownLatch latch = new CountDownLatch(getCount); ExecutorService exec = Executors.newFixedThreadPool(10); for (int i = 0; i < getCount; i++) { exec.execute(() -> { storageConsumer.get(); latch.countDown(); }); } latch.await(); exec.shutdown(); exec.awaitTermination(1, TimeUnit.SECONDS); assertThat(provisionCount.get()).isEqualTo(1); }
Neatle { public static UUID createUUID(int uuid) { final String base = "-0000-1000-8000-00805F9B34FB"; return UUID.fromString(String.format("%08X", uuid & 0xFFFF) + base); } private Neatle(); static CharacteristicSubscription createSubscription(@NonNull Context context, @NonNull BluetoothDevice device, @NonNull UUID serviceUUID, @NonNull UUID characteristicsUUID); static ConnectionMonitor createConnectionMonitor(@NonNull Context context, @NonNull BluetoothDevice device); static OperationBuilder createOperationBuilder(@NonNull Context context); static UUID createUUID(int uuid); static Connection getConnection(@NonNull Context context, @NonNull BluetoothDevice device); static boolean isMacValid(@NonNull String mac); static BluetoothDevice getDevice(@NonNull String mac); static ScanBuilder createScannerBuilder(); }
@Test public void testCreateUUID() { assertEquals("0000180f-0000-1000-8000-00805f9b34fb", Neatle.createUUID(0x180f).toString()); assertEquals("00000000-0000-1000-8000-00805f9b34fb", Neatle.createUUID(0).toString()); assertEquals("0000ffff-0000-1000-8000-00805f9b34fb", Neatle.createUUID(-1).toString()); }
WriteCommand extends SingleCharacteristicsCommand { @Override protected void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status != BluetoothGatt.GATT_SUCCESS) { NeatleLogger.i("Write on " + characteristic.getUuid() + " failed with status " + status); finish(CommandResult.createErrorResult(characteristicUUID, status)); return; } if (asyncMode) { synchronized (bufferReadLock) { bufferReadLock.notify(); } } else { byte[] chunk; try { chunk = buffer.nextChunk(); } catch (IOException ex) { NeatleLogger.e("Failed to get the first chunk", ex); finish(CommandResult.createErrorResult(characteristicUUID, BluetoothGatt.GATT_FAILURE)); try { buffer.close(); } catch (IOException e) { NeatleLogger.e("Failed to close input source", e); } return; } if (chunk == null) { try { buffer.close(); } catch (IOException e) { NeatleLogger.e("Failed to close input source", e); } finish(CommandResult.createEmptySuccess(characteristicUUID)); return; } nextChunkReady(chunk); } } WriteCommand(UUID serviceUUID, UUID characteristicsUUID, int writeType, InputSource buffer, CommandObserver observer); @Override String toString(); }
@Test public void testOnCharacteristicWriteFai2() throws IOException { when(gatt.getService(eq(serviceUUID))).thenReturn(gattService); when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic); when(gatt.writeCharacteristic(eq(gattCharacteristic))).thenReturn(true); InputSource inputSource = Mockito.mock(InputSource.class); when(inputSource.nextChunk()).thenReturn(new byte[]{21, 22}); writeCommand = new WriteCommand( serviceUUID, characteristicUUID, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, inputSource, commandObserver); writeCommand.execute(device, operationCommandObserver, gatt); doThrow(IOException.class).when(inputSource).nextChunk(); writeCommand.onCharacteristicWrite(gatt, gattCharacteristic, BluetoothGatt.GATT_SUCCESS); verifyCommandFail(); } @Test public void testOnCharacteristicWriteFinished() throws IOException { when(gatt.getService(eq(serviceUUID))).thenReturn(gattService); when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic); when(gatt.writeCharacteristic(eq(gattCharacteristic))).thenReturn(true); InputSource inputSource = Mockito.mock(InputSource.class); when(inputSource.nextChunk()).thenReturn(new byte[]{12, 21}); writeCommand = new WriteCommand( serviceUUID, characteristicUUID, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, inputSource, commandObserver); writeCommand.execute(device, operationCommandObserver, gatt); when(inputSource.nextChunk()).thenReturn(null); writeCommand.onCharacteristicWrite(gatt, gattCharacteristic, BluetoothGatt.GATT_SUCCESS); CommandResult result = CommandResult.createEmptySuccess(characteristicUUID); verify(commandObserver, times(1)).finished(eq(writeCommand), refEq(result, "timestamp")); verify(operationCommandObserver, times(1)).finished(eq(writeCommand), refEq(result, "timestamp")); verify(inputSource).close(); } @Test(timeout = 1000) public void testOnCharacteristicWriteFinishedAsyncSource() throws IOException { when(gatt.getService(eq(serviceUUID))).thenReturn(gattService); when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic); when(gatt.writeCharacteristic(eq(gattCharacteristic))).thenReturn(true); AsyncInputSource inputSource = Mockito.mock(AsyncInputSource.class); when(inputSource.nextChunk()).thenReturn(new byte[]{12, 21}); writeCommand = new WriteCommand( serviceUUID, characteristicUUID, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, inputSource, commandObserver); writeCommand.execute(device, operationCommandObserver, gatt); when(inputSource.nextChunk()).thenReturn(null); writeCommand.onCharacteristicWrite(gatt, gattCharacteristic, BluetoothGatt.GATT_SUCCESS); while (writeCommand.readerThread.isAlive()) { Robolectric.getForegroundThreadScheduler().advanceBy(0, TimeUnit.MILLISECONDS); Thread.yield(); } Robolectric.getForegroundThreadScheduler().advanceBy(0, TimeUnit.MILLISECONDS); CommandResult result = CommandResult.createEmptySuccess(characteristicUUID); verify(commandObserver, only()).finished(eq(writeCommand), refEq(result, "timestamp")); verify(operationCommandObserver, only()).finished(eq(writeCommand), refEq(result, "timestamp")); verify(inputSource).close(); } @Test public void testInputSourceClosesOnError() throws IOException { when(gatt.getService(eq(serviceUUID))).thenReturn(gattService); when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic); when(gatt.writeCharacteristic(eq(gattCharacteristic))).thenReturn(true); InputSource inputSource = Mockito.mock(InputSource.class); when(inputSource.nextChunk()).thenThrow(new IOException()); writeCommand = new WriteCommand( serviceUUID, characteristicUUID, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, inputSource, commandObserver); writeCommand.execute(device, operationCommandObserver, gatt); writeCommand.onCharacteristicWrite(gatt, gattCharacteristic, BluetoothGatt.GATT_SUCCESS); verify(inputSource).close(); } @Test(timeout = 1000) public void testAsyncInputSourceClosesOnError() throws IOException { when(gatt.getService(eq(serviceUUID))).thenReturn(gattService); when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic); when(gatt.writeCharacteristic(eq(gattCharacteristic))).thenReturn(true); AsyncInputSource inputSource = Mockito.mock(AsyncInputSource.class); when(inputSource.nextChunk()).thenThrow(new IOException()); writeCommand = new WriteCommand( serviceUUID, characteristicUUID, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, inputSource, commandObserver); writeCommand.execute(device, operationCommandObserver, gatt); writeCommand.onCharacteristicWrite(gatt, gattCharacteristic, BluetoothGatt.GATT_SUCCESS); while (writeCommand.readerThread.isAlive()) { Robolectric.getForegroundThreadScheduler().advanceBy(0, TimeUnit.MILLISECONDS); Thread.yield(); } Robolectric.getForegroundThreadScheduler().advanceBy(0, TimeUnit.MILLISECONDS); verify(inputSource).close(); } @Test public void testOnCharacteristicWriteNextChunk() throws IOException { when(gatt.getService(eq(serviceUUID))).thenReturn(gattService); when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic); when(gatt.writeCharacteristic(eq(gattCharacteristic))).thenReturn(true); InputSource inputSource = Mockito.mock(InputSource.class); when(inputSource.nextChunk()).thenReturn(new byte[]{12, 21}); writeCommand = new WriteCommand( serviceUUID, characteristicUUID, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, inputSource, commandObserver); writeCommand.execute(device, operationCommandObserver, gatt); writeCommand.onCharacteristicWrite(gatt, gattCharacteristic, BluetoothGatt.GATT_SUCCESS); verify(commandObserver, times(0)).finished(any(Command.class), any(CommandResult.class)); verify(operationCommandObserver, times(0)).finished(any(Command.class), any(CommandResult.class)); } @Test public void testOnCharacteristicWriteFail() throws IOException { when(gatt.getService(eq(serviceUUID))).thenReturn(gattService); when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic); when(gatt.writeCharacteristic(eq(gattCharacteristic))).thenReturn(true); InputSource inputSource = Mockito.mock(InputSource.class); when(inputSource.nextChunk()).thenReturn(new byte[]{21, 22}); writeCommand = new WriteCommand( serviceUUID, characteristicUUID, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, inputSource, commandObserver); writeCommand.execute(device, operationCommandObserver, gatt); writeCommand.onCharacteristicWrite(gatt, gattCharacteristic, BluetoothGatt.GATT_FAILURE); verifyCommandFail(); }
WriteCommand extends SingleCharacteristicsCommand { @Override protected void onError(int error) { NeatleLogger.e("Unexpected error while writing [" + error + "]"); finish(CommandResult.createErrorResult(characteristicUUID, error)); if (asyncMode && readerThread != null) { readerThread.interrupt(); } } WriteCommand(UUID serviceUUID, UUID characteristicsUUID, int writeType, InputSource buffer, CommandObserver observer); @Override String toString(); }
@Test public void testOnError() { writeCommand.execute(device, operationCommandObserver, gatt); reset(operationCommandObserver, commandObserver); writeCommand.onError(BluetoothGatt.GATT_FAILURE); verifyCommandFail(); } @Test public void testAsyncOnError() throws Exception { when(gatt.getService(eq(serviceUUID))).thenReturn(gattService); when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic); when(gatt.writeCharacteristic(eq(gattCharacteristic))).thenReturn(true); AsyncInputSource inputSource = Mockito.mock(AsyncInputSource.class); when(inputSource.nextChunk()).thenAnswer(new Answer<byte[]>() { @Override public byte[] answer(InvocationOnMock invocationOnMock) { writeCommand.onError(BluetoothGatt.GATT_FAILURE); return new byte[]{12, 21}; } }); writeCommand = new WriteCommand( serviceUUID, characteristicUUID, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, inputSource, commandObserver); writeCommand.execute(device, operationCommandObserver, gatt); while (writeCommand.readerThread.isAlive()) { Robolectric.getForegroundThreadScheduler().advanceBy(0, TimeUnit.MILLISECONDS); Thread.yield(); } Robolectric.getForegroundThreadScheduler().advanceBy(0, TimeUnit.MILLISECONDS); verifyCommandFail(); verify(inputSource).close(); }
WriteCommand extends SingleCharacteristicsCommand { @Override public String toString() { return "WriteCommand[async:" + asyncMode + " - " + characteristicUUID + "] on [" + serviceUUID + "]"; } WriteCommand(UUID serviceUUID, UUID characteristicsUUID, int writeType, InputSource buffer, CommandObserver observer); @Override String toString(); }
@Test public void testToStringBecauseWhyNot() { assertNotNull(writeCommand.toString()); }
CommandResult { public int getValueAsInt() { if (data.length > 4) { throw new IllegalStateException("Data has more than 4 bytes and cannot be converted to an integer"); } int ret = 0; switch (data.length) { case 4: ret |= (data[3] & 0xFF) << ((data.length - 4) * 8); case 3: ret |= (data[2] & 0xFF) << ((data.length - 3) * 8); case 2: ret |= (data[1] & 0xFF) << ((data.length - 2) * 8); case 1: ret |= (data[0] & 0xFF) << ((data.length - 1) * 8); } return ret; } CommandResult(UUID uuid, byte[] data, int status, long timestamp); byte[] getValue(); String getValueAsString(); int getValueAsInt(); Integer getFormattedIntValue(int formatType, int offset); UUID getUUID(); int getStatus(); long getTimestamp(); boolean wasSuccessful(); @Override String toString(); @RestrictTo(RestrictTo.Scope.LIBRARY) static CommandResult createCharacteristicRead(BluetoothGattCharacteristic characteristic, int status); @RestrictTo(RestrictTo.Scope.LIBRARY) static CommandResult createErrorResult(UUID characteristicUUID, int error); @RestrictTo(RestrictTo.Scope.LIBRARY) static CommandResult createEmptySuccess(UUID characteristicUUID); @RestrictTo(RestrictTo.Scope.LIBRARY) static CommandResult createCharacteristicChanged(BluetoothGattCharacteristic characteristic); static final int FORMAT_UINT8; static final int FORMAT_UINT16; static final int FORMAT_UINT32; static final int FORMAT_SINT8; static final int FORMAT_SINT16; static final int FORMAT_SINT32; }
@Test(expected = IllegalStateException.class) public void testIntException() { CommandResult commandResult = new CommandResult(Neatle.createUUID(1), new byte[]{22, 21, 20, 19, 18}, BluetoothGatt.GATT_SUCCESS, 1); commandResult.getValueAsInt(); }
Neatle { public static CharacteristicSubscription createSubscription(@NonNull Context context, @NonNull BluetoothDevice device, @NonNull UUID serviceUUID, @NonNull UUID characteristicsUUID) { return new CharacteristicSubscriptionImpl(context, device, serviceUUID, characteristicsUUID); } private Neatle(); static CharacteristicSubscription createSubscription(@NonNull Context context, @NonNull BluetoothDevice device, @NonNull UUID serviceUUID, @NonNull UUID characteristicsUUID); static ConnectionMonitor createConnectionMonitor(@NonNull Context context, @NonNull BluetoothDevice device); static OperationBuilder createOperationBuilder(@NonNull Context context); static UUID createUUID(int uuid); static Connection getConnection(@NonNull Context context, @NonNull BluetoothDevice device); static boolean isMacValid(@NonNull String mac); static BluetoothDevice getDevice(@NonNull String mac); static ScanBuilder createScannerBuilder(); }
@Test public void testCreateSubscription() { BluetoothDevice bluetoothDevice = Mockito.mock(BluetoothDevice.class); Mockito.when(bluetoothDevice.getAddress()).thenReturn("00:11:22:33:44:55"); assertNotNull(Neatle.createSubscription(RuntimeEnvironment.application, bluetoothDevice, Neatle.createUUID(0), Neatle.createUUID(0))); }
CommandResult { public String getValueAsString() { if (data == null) { return null; } else if (data.length == 0) { return ""; } else { return new String(data, Charset.forName("UTF8")); } } CommandResult(UUID uuid, byte[] data, int status, long timestamp); byte[] getValue(); String getValueAsString(); int getValueAsInt(); Integer getFormattedIntValue(int formatType, int offset); UUID getUUID(); int getStatus(); long getTimestamp(); boolean wasSuccessful(); @Override String toString(); @RestrictTo(RestrictTo.Scope.LIBRARY) static CommandResult createCharacteristicRead(BluetoothGattCharacteristic characteristic, int status); @RestrictTo(RestrictTo.Scope.LIBRARY) static CommandResult createErrorResult(UUID characteristicUUID, int error); @RestrictTo(RestrictTo.Scope.LIBRARY) static CommandResult createEmptySuccess(UUID characteristicUUID); @RestrictTo(RestrictTo.Scope.LIBRARY) static CommandResult createCharacteristicChanged(BluetoothGattCharacteristic characteristic); static final int FORMAT_UINT8; static final int FORMAT_UINT16; static final int FORMAT_UINT32; static final int FORMAT_SINT8; static final int FORMAT_SINT16; static final int FORMAT_SINT32; }
@Test public void testStringValues() { String dataStr = "lorem ipsum dolor sit amet"; CommandResult commandResult = new CommandResult(Neatle.createUUID(1), dataStr.getBytes(Charset.forName("UTF8")), BluetoothGatt.GATT_SUCCESS, 1); assertEquals(dataStr, commandResult.getValueAsString()); CommandResult commandResult2 = new CommandResult(Neatle.createUUID(1), null, BluetoothGatt.GATT_SUCCESS, 1); assertNull(commandResult2.getValueAsString()); CommandResult commandResult3 = new CommandResult(Neatle.createUUID(1), new byte[]{}, BluetoothGatt.GATT_SUCCESS, 1); assertEquals("", commandResult3.getValueAsString()); }
ReadCommand extends SingleCharacteristicsCommand { public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (!characteristic.getUuid().equals(characteristicUUID)) { NeatleLogger.e("Got a read request for a unknown characteristic"); return; } CommandResult result = CommandResult.createCharacteristicRead(characteristic, status); NeatleLogger.d("Read: " + result); finish(result); } ReadCommand(UUID serviceUUID, UUID characteristicUUID, CommandObserver observer); void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status); @Override String toString(); }
@Test public void testOnCharacteristicRead() { BluetoothGattCharacteristic otherCharacteristic = Mockito.mock(BluetoothGattCharacteristic.class); when(otherCharacteristic.getUuid()).thenReturn(Neatle.createUUID(123)); when(gatt.getService(eq(serviceUUID))).thenReturn(gattService); when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic); when(gatt.readCharacteristic(eq(gattCharacteristic))).thenReturn(true); when(gattCharacteristic.getValue()).thenReturn(new byte[]{21, 22}); when(gattCharacteristic.getUuid()).thenReturn(characteristicUUID); readCommand.execute(device, operationCommandObserver, gatt); readCommand.onCharacteristicRead(gatt, otherCharacteristic, BluetoothGatt.GATT_SUCCESS); verify(commandObserver, times(0)).finished(any(Command.class), any(CommandResult.class)); verify(operationCommandObserver, times(0)).finished(any(Command.class), any(CommandResult.class)); Mockito.reset(commandObserver, operationCommandObserver); readCommand.onCharacteristicRead(gatt, gattCharacteristic, BluetoothGatt.GATT_SUCCESS); CommandResult result = CommandResult.createCharacteristicRead(gattCharacteristic, BluetoothGatt.GATT_SUCCESS); verify(commandObserver, times(1)).finished(eq(readCommand), refEq(result, "timestamp")); verify(operationCommandObserver, times(1)).finished(eq(readCommand), refEq(result, "timestamp")); }
ReadCommand extends SingleCharacteristicsCommand { @Override protected void onError(int error) { NeatleLogger.e("Unexpected error while reading [" + error + "]"); finish(CommandResult.createErrorResult(characteristicUUID, error)); } ReadCommand(UUID serviceUUID, UUID characteristicUUID, CommandObserver observer); void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status); @Override String toString(); }
@Test public void testOnError() { when(gatt.getService(eq(serviceUUID))).thenReturn(gattService); when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic); when(gatt.readCharacteristic(eq(gattCharacteristic))).thenReturn(true); readCommand.execute(device, operationCommandObserver, gatt); readCommand.onError(BluetoothGatt.GATT_FAILURE); verifyCommandFail(); }
ReadCommand extends SingleCharacteristicsCommand { @Override public String toString() { return "ReadCommand[" + characteristicUUID + "] on [" + serviceUUID + "]"; } ReadCommand(UUID serviceUUID, UUID characteristicUUID, CommandObserver observer); void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status); @Override String toString(); }
@Test public void testToStringBecauseWhyNot() { ReadCommand readCommand = new ReadCommand( serviceUUID, characteristicUUID, commandObserver); assertNotNull(readCommand.toString()); }
SubscribeCommand extends SingleCharacteristicsCommand { @Override protected void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { if (status != BluetoothGatt.GATT_SUCCESS) { finish(CommandResult.createErrorResult(characteristicUUID, status)); } else { finish(CommandResult.createEmptySuccess(characteristicUUID)); } } SubscribeCommand(@Type int type, UUID serviceUUID, UUID characteristicUUID, CommandObserver observer); @Override String toString(); }
@Test public void testOnDescriptorWriteSuccess() { setupDescriptorSuccess(); subscribeCommand.execute(device, operationCommandObserver, gatt); subscribeCommand.onDescriptorWrite(gatt, gattDescriptor, BluetoothGatt.GATT_SUCCESS); CommandResult result = CommandResult.createEmptySuccess(characteristicUUID); verify(commandObserver, times(1)).finished(eq(subscribeCommand), refEq(result, "timestamp")); verify(operationCommandObserver, times(1)).finished(eq(subscribeCommand), refEq(result, "timestamp")); } @Test public void testOnDescriptorWriteFail() { setupDescriptorSuccess(); subscribeCommand.execute(device, operationCommandObserver, gatt); subscribeCommand.onDescriptorWrite(gatt, gattDescriptor, BluetoothGatt.GATT_FAILURE); verifyCommandFail(subscribeCommand, BluetoothGatt.GATT_FAILURE); }
SubscribeCommand extends SingleCharacteristicsCommand { @Override protected void onError(int error) { finish(CommandResult.createErrorResult(characteristicUUID, error)); } SubscribeCommand(@Type int type, UUID serviceUUID, UUID characteristicUUID, CommandObserver observer); @Override String toString(); }
@Test public void testOnError() { setupDescriptorSuccess(); subscribeCommand.execute(device, operationCommandObserver, gatt); subscribeCommand.onError(BluetoothGatt.GATT_FAILURE); verifyCommandFail(subscribeCommand, BluetoothGatt.GATT_FAILURE); }
SubscribeCommand extends SingleCharacteristicsCommand { @Override public String toString() { if (type == Type.UNSUBSCRIBE) { return "UnsubscribeCommand[" + characteristicUUID + "] on [" + serviceUUID + "]"; } else if (type == Type.SUBSCRIBE_INDICATION) { return "SubscribeCommand[" + characteristicUUID + "] on [" + serviceUUID + "]"; } else if (type == Type.SUBSCRIBE_NOTIFICATION) { return "SubscribeNotificationCommand[" + characteristicUUID + "] on [" + serviceUUID + "]"; } else { return super.toString(); } } SubscribeCommand(@Type int type, UUID serviceUUID, UUID characteristicUUID, CommandObserver observer); @Override String toString(); }
@Test public void testOnStringBecauseWhyNot() { SubscribeCommand subNotif = new SubscribeCommand( SubscribeCommand.Type.SUBSCRIBE_NOTIFICATION, serviceUUID, characteristicUUID, commandObserver); SubscribeCommand subIndi = new SubscribeCommand( SubscribeCommand.Type.SUBSCRIBE_INDICATION, serviceUUID, characteristicUUID, commandObserver); SubscribeCommand unsub = new SubscribeCommand( SubscribeCommand.Type.UNSUBSCRIBE, serviceUUID, characteristicUUID, commandObserver); assertNotNull(subNotif.toString()); assertNotNull(subIndi.toString()); assertNotNull(unsub.toString()); }
OperationBuilder { @CheckResult public Operation build(BluetoothDevice device) { if (device == null) { throw new IllegalArgumentException("Device cannot be null"); } return new OperationImpl(context, device, commands, retryCount, masterObserver); } @RestrictTo(RestrictTo.Scope.LIBRARY) OperationBuilder(Context context); OperationBuilder read(UUID serviceUUID, UUID characteristicsUUID); OperationBuilder read(UUID serviceUUID, UUID characteristicsUUID, CommandObserver observer); OperationBuilder write(UUID serviceUUID, UUID characteristicsUUID, InputSource source); OperationBuilder write(UUID serviceUUID, UUID characteristicsUUID, Callable<ByteBuffer> callable); OperationBuilder write(UUID serviceUUID, UUID characteristicsUUID, InputSource source, CommandObserver observer); OperationBuilder writeNoResponse(UUID serviceUUID, UUID characteristicsUUID, InputSource source); OperationBuilder writeNoResponse(UUID serviceUUID, UUID characteristicsUUID, InputSource source, CommandObserver observer); OperationBuilder executeCommand(Command cmd); OperationBuilder onFinished(OperationObserver operationObserver); OperationBuilder retryCount(int count); @CheckResult Operation build(BluetoothDevice device); }
@SuppressWarnings("CheckResult") @Test(expected = IllegalArgumentException.class) public void testBuilderException() { new OperationBuilder(RuntimeEnvironment.application).build(null); }
LolipopLEScanner extends BaseScanner { @Override @SuppressWarnings({"SpellCheckingInspection", "deprecation"}) protected void onStart(BluetoothAdapter adapter, int scanMode) { boolean ret; UUID uuids[] = scannerConfiguration.getServiceUUIDs(); if (uuids.length > 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ret = adapter.startLeScan(uuids, callback); } else { ret = adapter.startLeScan(callback); } if (ret) { NeatleLogger.d("Bluetooth LE scan started."); } else { NeatleLogger.i("Bluetooth LE scan failed to start. State = " + adapter.getState()); } } LolipopLEScanner(ScannerConfiguration settings); }
@Test @Config(sdk = Build.VERSION_CODES.LOLLIPOP) public void startScanWithUuidsOnLollipop() { BluetoothAdapter testAdapter = Mockito.mock(BluetoothAdapter.class); Mockito.when(testAdapter.startLeScan(Mockito.<UUID[]>any(), Mockito.<BluetoothAdapter.LeScanCallback>any())).thenReturn(true); LolipopLEScanner scanner = new LolipopLEScanner(TEST_CONFIGURATION); scanner.onStart(testAdapter, 0); Mockito.verify(testAdapter, Mockito.only()).startLeScan(Mockito.argThat(new ArgumentMatcher<UUID[]>() { @Override public boolean matches(UUID[] uuids) { return uuids.length == 1 && TEST_UUID.equals(uuids[0]); } }), Mockito.<BluetoothAdapter.LeScanCallback>any()); } @Test @Config(sdk = Build.VERSION_CODES.KITKAT) public void startScanWithUuidsOnKitkat() { BluetoothAdapter testAdapter = Mockito.mock(BluetoothAdapter.class); Mockito.when(testAdapter.startLeScan(Mockito.<BluetoothAdapter.LeScanCallback>any())).thenReturn(true); LolipopLEScanner scanner = new LolipopLEScanner(TEST_CONFIGURATION); scanner.onStart(testAdapter, 0); Mockito.verify(testAdapter, Mockito.only()).startLeScan(Mockito.<BluetoothAdapter.LeScanCallback>any()); } @Test @Config(sdk = Build.VERSION_CODES.KITKAT) public void filterUuidsOnKitkat() { ByteBuffer mockScanRecordBuffer = ByteBuffer.allocate(100).order(ByteOrder.LITTLE_ENDIAN) .put((byte) 17) .put((byte) 0x07) .putLong(INVALID_UUID.getLeastSignificantBits()) .putLong(INVALID_UUID.getMostSignificantBits()); byte[] mockScanRecord = Arrays.copyOf(mockScanRecordBuffer.array(), mockScanRecordBuffer.position()); Scanner.NewDeviceFoundListener listener = Mockito.mock(Scanner.NewDeviceFoundListener.class); TEST_CONFIGURATION.setNewDeviceFoundListener(listener); ArgumentCaptor<BluetoothAdapter.LeScanCallback> callbackCaptor = ArgumentCaptor.forClass(BluetoothAdapter.LeScanCallback.class); BluetoothAdapter testAdapter = Mockito.mock(BluetoothAdapter.class); LolipopLEScanner scanner = new LolipopLEScanner(TEST_CONFIGURATION); scanner.onStart(testAdapter, 0); Mockito.verify(testAdapter).startLeScan(callbackCaptor.capture()); callbackCaptor.getValue().onLeScan(Mockito.mock(BluetoothDevice.class), -10, mockScanRecord); } @Test @Config(sdk = Build.VERSION_CODES.KITKAT) public void allowProperUuidsOnKitkat() { ByteBuffer mockScanRecordBuffer = ByteBuffer.allocate(100).order(ByteOrder.LITTLE_ENDIAN) .put((byte) 17) .put((byte) 0x07) .putLong(TEST_UUID.getLeastSignificantBits()) .putLong(TEST_UUID.getMostSignificantBits()); byte[] mockScanRecord = Arrays.copyOf(mockScanRecordBuffer.array(), mockScanRecordBuffer.position()); Scanner.NewDeviceFoundListener listener = Mockito.mock(Scanner.NewDeviceFoundListener.class); ScannerConfiguration configuration = new ScannerConfiguration(); configuration.setNewDeviceFoundListener(listener); ArgumentCaptor<BluetoothAdapter.LeScanCallback> callbackCaptor = ArgumentCaptor.forClass(BluetoothAdapter.LeScanCallback.class); BluetoothAdapter testAdapter = Mockito.mock(BluetoothAdapter.class); LolipopLEScanner scanner = new LolipopLEScanner(configuration); scanner.onStart(testAdapter, 0); Mockito.verify(testAdapter).startLeScan(callbackCaptor.capture()); callbackCaptor.getValue().onLeScan(Mockito.mock(BluetoothDevice.class), -10, mockScanRecord); Mockito.verify(listener).onNewDeviceFound(Mockito.<ScanEvent>any()); } @Test @Config(sdk = Build.VERSION_CODES.KITKAT) public void doNotFilterUuidsOnKitkatWithEmptyServiceList() { ByteBuffer mockScanRecordBuffer = ByteBuffer.allocate(100).order(ByteOrder.LITTLE_ENDIAN) .put((byte) 17) .put((byte) 0x07) .putLong(INVALID_UUID.getLeastSignificantBits()) .putLong(INVALID_UUID.getMostSignificantBits()); byte[] mockScanRecord = Arrays.copyOf(mockScanRecordBuffer.array(), mockScanRecordBuffer.position()); Scanner.NewDeviceFoundListener listener = Mockito.mock(Scanner.NewDeviceFoundListener.class); ScannerConfiguration configuration = new ScannerConfiguration(); configuration.setNewDeviceFoundListener(listener); ArgumentCaptor<BluetoothAdapter.LeScanCallback> callbackCaptor = ArgumentCaptor.forClass(BluetoothAdapter.LeScanCallback.class); BluetoothAdapter testAdapter = Mockito.mock(BluetoothAdapter.class); LolipopLEScanner scanner = new LolipopLEScanner(configuration); scanner.onStart(testAdapter, 0); Mockito.verify(testAdapter).startLeScan(callbackCaptor.capture()); callbackCaptor.getValue().onLeScan(Mockito.mock(BluetoothDevice.class), -10, mockScanRecord); Mockito.verify(listener).onNewDeviceFound(Mockito.<ScanEvent>any()); }
Neatle { public static ConnectionMonitor createConnectionMonitor(@NonNull Context context, @NonNull BluetoothDevice device) { return new ConnectionMonitorImpl(context, device); } private Neatle(); static CharacteristicSubscription createSubscription(@NonNull Context context, @NonNull BluetoothDevice device, @NonNull UUID serviceUUID, @NonNull UUID characteristicsUUID); static ConnectionMonitor createConnectionMonitor(@NonNull Context context, @NonNull BluetoothDevice device); static OperationBuilder createOperationBuilder(@NonNull Context context); static UUID createUUID(int uuid); static Connection getConnection(@NonNull Context context, @NonNull BluetoothDevice device); static boolean isMacValid(@NonNull String mac); static BluetoothDevice getDevice(@NonNull String mac); static ScanBuilder createScannerBuilder(); }
@Test public void testCreateConnectionMonitor() { BluetoothDevice bluetoothDevice = Mockito.mock(BluetoothDevice.class); Mockito.when(bluetoothDevice.getAddress()).thenReturn("00:11:22:33:44:55"); assertNotNull(Neatle.createConnectionMonitor(RuntimeEnvironment.application, bluetoothDevice)); }
Neatle { public static OperationBuilder createOperationBuilder(@NonNull Context context) { return new OperationBuilder(context); } private Neatle(); static CharacteristicSubscription createSubscription(@NonNull Context context, @NonNull BluetoothDevice device, @NonNull UUID serviceUUID, @NonNull UUID characteristicsUUID); static ConnectionMonitor createConnectionMonitor(@NonNull Context context, @NonNull BluetoothDevice device); static OperationBuilder createOperationBuilder(@NonNull Context context); static UUID createUUID(int uuid); static Connection getConnection(@NonNull Context context, @NonNull BluetoothDevice device); static boolean isMacValid(@NonNull String mac); static BluetoothDevice getDevice(@NonNull String mac); static ScanBuilder createScannerBuilder(); }
@Test public void testCreateOperationBuilder() { assertNotNull(Neatle.createOperationBuilder(RuntimeEnvironment.application)); }
Neatle { public static Connection getConnection(@NonNull Context context, @NonNull BluetoothDevice device) { return DeviceManager.getInstance(context).getDevice(device); } private Neatle(); static CharacteristicSubscription createSubscription(@NonNull Context context, @NonNull BluetoothDevice device, @NonNull UUID serviceUUID, @NonNull UUID characteristicsUUID); static ConnectionMonitor createConnectionMonitor(@NonNull Context context, @NonNull BluetoothDevice device); static OperationBuilder createOperationBuilder(@NonNull Context context); static UUID createUUID(int uuid); static Connection getConnection(@NonNull Context context, @NonNull BluetoothDevice device); static boolean isMacValid(@NonNull String mac); static BluetoothDevice getDevice(@NonNull String mac); static ScanBuilder createScannerBuilder(); }
@Test public void testGetConnection() { BluetoothDevice bluetoothDevice = Mockito.mock(BluetoothDevice.class); Mockito.when(bluetoothDevice.getAddress()).thenReturn("00:11:22:33:44:55"); assertNotNull(Neatle.getConnection(RuntimeEnvironment.application, bluetoothDevice)); }
Neatle { public static BluetoothDevice getDevice(@NonNull String mac) { String upperMac = mac.toUpperCase(); if (isMacValid(upperMac)) { return BluetoothAdapter.getDefaultAdapter().getRemoteDevice(upperMac); } throw new UnsupportedOperationException("Device mac not recognized."); } private Neatle(); static CharacteristicSubscription createSubscription(@NonNull Context context, @NonNull BluetoothDevice device, @NonNull UUID serviceUUID, @NonNull UUID characteristicsUUID); static ConnectionMonitor createConnectionMonitor(@NonNull Context context, @NonNull BluetoothDevice device); static OperationBuilder createOperationBuilder(@NonNull Context context); static UUID createUUID(int uuid); static Connection getConnection(@NonNull Context context, @NonNull BluetoothDevice device); static boolean isMacValid(@NonNull String mac); static BluetoothDevice getDevice(@NonNull String mac); static ScanBuilder createScannerBuilder(); }
@Test(expected = UnsupportedOperationException.class) public void testGetDeviceException() { Neatle.getDevice("no:ta:ma:c!"); }
Neatle { public static boolean isMacValid(@NonNull String mac) { return BluetoothAdapter.checkBluetoothAddress(mac.toUpperCase()); } private Neatle(); static CharacteristicSubscription createSubscription(@NonNull Context context, @NonNull BluetoothDevice device, @NonNull UUID serviceUUID, @NonNull UUID characteristicsUUID); static ConnectionMonitor createConnectionMonitor(@NonNull Context context, @NonNull BluetoothDevice device); static OperationBuilder createOperationBuilder(@NonNull Context context); static UUID createUUID(int uuid); static Connection getConnection(@NonNull Context context, @NonNull BluetoothDevice device); static boolean isMacValid(@NonNull String mac); static BluetoothDevice getDevice(@NonNull String mac); static ScanBuilder createScannerBuilder(); }
@Test public void testIsMacValid() { assertTrue(Neatle.isMacValid("00:11:22:33:44:55")); assertTrue(Neatle.isMacValid("00:11:22:33:44:55")); assertTrue(Neatle.isMacValid("aa:bb:cc:dd:ee:ff")); assertTrue(Neatle.isMacValid("00:22:bb:cd:ef:12")); assertFalse(Neatle.isMacValid("")); assertFalse(Neatle.isMacValid("loremipsup")); assertFalse(Neatle.isMacValid("00:22:bb:cd:ef:gg")); assertFalse(Neatle.isMacValid(":::::")); }
DeviceManager { public synchronized static DeviceManager getInstance(Context context) { if (sharedInstance == null) { sharedInstance = new DeviceManager(context.getApplicationContext()); } return sharedInstance; } private DeviceManager(Context context); synchronized static DeviceManager getInstance(Context context); synchronized Device getDevice(BluetoothDevice device); @RestrictTo(RestrictTo.Scope.TESTS) void putDevice(Device device, String address); @RestrictTo(RestrictTo.Scope.TESTS) void clearDevices(); }
@Test public void instanceTest() { assertNotNull(DeviceManager.getInstance(RuntimeEnvironment.application)); }
DeviceManager { public synchronized Device getDevice(BluetoothDevice device) { NeatleLogger.d("Getting connection object for " + device.getAddress()); Device dev = devices.get(device.getAddress()); if (dev == null) { BluetoothManager mng = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); dev = new Device(context, device, mng.getAdapter()); devices.put(device.getAddress(), dev); } return dev; } private DeviceManager(Context context); synchronized static DeviceManager getInstance(Context context); synchronized Device getDevice(BluetoothDevice device); @RestrictTo(RestrictTo.Scope.TESTS) void putDevice(Device device, String address); @RestrictTo(RestrictTo.Scope.TESTS) void clearDevices(); }
@Test public void getDeviceTest() { BluetoothDevice bluetoothDevice = Mockito.mock(BluetoothDevice.class); Mockito.when(bluetoothDevice.getAddress()).thenReturn("00:11:22:33:44:55"); assertNotNull(deviceManager.getDevice(bluetoothDevice)); assertNotNull(deviceManager.getDevice(bluetoothDevice)); }
AutoCompleteUtils { public static boolean hasPrefixHandle(char handle, @Nullable CharSequence token) { return !TextUtils.isEmpty(token) && token.charAt(0) == handle; } private AutoCompleteUtils(); static boolean hasPrefixHandle(char handle, @Nullable CharSequence token); static String stripPrefixHandle(char handle, @Nullable CharSequence text); @SuppressWarnings("unused") static void selectAllText(EditText editText); }
@Test public void hasHandle() throws Exception { assertThat(AutoCompleteUtils.hasPrefixHandle('@', ""), is(false)); assertThat(AutoCompleteUtils.hasPrefixHandle('@', "no_handle"), is(false)); assertThat(AutoCompleteUtils.hasPrefixHandle('@', "no_handle@"), is(false)); assertThat(AutoCompleteUtils.hasPrefixHandle('@', "@handle"), is(true)); }
MultiAutoCompleteImpl implements MultiAutoComplete, TextWatcher, MultiAutoCompleteEditText.OnSelectionChangedListener { @Override @CallSuper public void afterTextChanged(Editable s) { for (TypeAdapterDelegate typeAdapter : typeAdapters) { typeAdapter.onTextChanged(s.toString()); } } MultiAutoCompleteImpl(@NonNull Tokenizer tokenizer, @NonNull List<TypeAdapterDelegate> typeAdapters, @Nullable Delayer delayer); @Override void onViewAttached(@NonNull MultiAutoCompleteEditText view); @Override void onViewDetached(); @Override void beforeTextChanged(CharSequence s, int start, int count, int after); @Override void onTextChanged(CharSequence s, int start, int before, int count); @Override @CallSuper void afterTextChanged(Editable s); @Override boolean onSelectionChanged(int selStart, int selEnd); }
@Test public void afterTextChanged() throws Exception { CharSequence text = "text"; autoComplete.afterTextChanged(new SpannableStringBuilder(text)); verify(typeAdapter1).onTextChanged(eq(text)); verify(typeAdapter2).onTextChanged(eq(text)); }
BaseTypeAdapterDelegate extends BaseAdapter implements TypeAdapterDelegate<M>, AutoCompleteTypeAdapter<M> { @Override public @NonNull TokenFilter<M> getFilter() { return tokenFilter; } BaseTypeAdapterDelegate(@NonNull AutoCompleteViewBinder<M> viewBinder, @NonNull TokenFilter<M> tokenFilter); @VisibleForTesting BaseTypeAdapterDelegate(@NonNull Executor computationExecutor, @NonNull Handler mainThreadHandler, @NonNull AutoCompleteViewBinder<M> viewBinder, @NonNull TokenFilter<M> tokenFilter); @Override @NonNull TokenFilter<M> getFilter(); @Override @CallSuper void setItems(@NonNull List<M> items); @Override final void setFilteredItems(@NonNull List<M> filteredItems); @Override final int getCount(); @Override final @NonNull M getItem(int position); @Override long getItemId(int position); @Override @NonNull View getView(@NonNull LayoutInflater inflater, int position, @Nullable View convertView, @NonNull ViewGroup parent, @Nullable CharSequence constraint); @Override View getView(int position, View convertView, ViewGroup parent); @Override @WorkerThread final @NonNull List<M> performFiltering(@NonNull CharSequence constraint); @Override final void setOnTokensChangedListener(@Nullable OnTokensChangedListener<M> listener); @Override final void onTextChanged(@NonNull CharSequence text); }
@Test public void testGetFilter() throws Exception { assertThat(adapterDelegate.getFilter(), notNullValue()); }
BaseTypeAdapterDelegate extends BaseAdapter implements TypeAdapterDelegate<M>, AutoCompleteTypeAdapter<M> { @Override @CallSuper public void setItems(@NonNull List<M> items) { computationExecutor.execute(() -> setItemsSync(items)); } BaseTypeAdapterDelegate(@NonNull AutoCompleteViewBinder<M> viewBinder, @NonNull TokenFilter<M> tokenFilter); @VisibleForTesting BaseTypeAdapterDelegate(@NonNull Executor computationExecutor, @NonNull Handler mainThreadHandler, @NonNull AutoCompleteViewBinder<M> viewBinder, @NonNull TokenFilter<M> tokenFilter); @Override @NonNull TokenFilter<M> getFilter(); @Override @CallSuper void setItems(@NonNull List<M> items); @Override final void setFilteredItems(@NonNull List<M> filteredItems); @Override final int getCount(); @Override final @NonNull M getItem(int position); @Override long getItemId(int position); @Override @NonNull View getView(@NonNull LayoutInflater inflater, int position, @Nullable View convertView, @NonNull ViewGroup parent, @Nullable CharSequence constraint); @Override View getView(int position, View convertView, ViewGroup parent); @Override @WorkerThread final @NonNull List<M> performFiltering(@NonNull CharSequence constraint); @Override final void setOnTokensChangedListener(@Nullable OnTokensChangedListener<M> listener); @Override final void onTextChanged(@NonNull CharSequence text); }
@Test public void testSetItems() throws Exception { adapterDelegate.setItems(dataset); assertThat(adapterDelegate.getItemsMap(), notNullValue()); assertThat(adapterDelegate.getItemsMap().size(), is(dataset.size())); assertThat(adapterDelegate.getItemsMap().values(), IsIterableContainingInOrder.contains(dataset.toArray())); assertThat(adapterDelegate.getCount(), is(0)); }
BaseTypeAdapterDelegate extends BaseAdapter implements TypeAdapterDelegate<M>, AutoCompleteTypeAdapter<M> { @Override @WorkerThread public final @NonNull List<M> performFiltering(@NonNull CharSequence constraint) { List<M> items = new ArrayList<>(); runLocked(lock.readLock(), () -> items.addAll(this.itemsMap.values())); return getFilter().performFiltering(constraint, items); } BaseTypeAdapterDelegate(@NonNull AutoCompleteViewBinder<M> viewBinder, @NonNull TokenFilter<M> tokenFilter); @VisibleForTesting BaseTypeAdapterDelegate(@NonNull Executor computationExecutor, @NonNull Handler mainThreadHandler, @NonNull AutoCompleteViewBinder<M> viewBinder, @NonNull TokenFilter<M> tokenFilter); @Override @NonNull TokenFilter<M> getFilter(); @Override @CallSuper void setItems(@NonNull List<M> items); @Override final void setFilteredItems(@NonNull List<M> filteredItems); @Override final int getCount(); @Override final @NonNull M getItem(int position); @Override long getItemId(int position); @Override @NonNull View getView(@NonNull LayoutInflater inflater, int position, @Nullable View convertView, @NonNull ViewGroup parent, @Nullable CharSequence constraint); @Override View getView(int position, View convertView, ViewGroup parent); @Override @WorkerThread final @NonNull List<M> performFiltering(@NonNull CharSequence constraint); @Override final void setOnTokensChangedListener(@Nullable OnTokensChangedListener<M> listener); @Override final void onTextChanged(@NonNull CharSequence text); }
@Test public void testPerformFiltering() throws Exception { adapterDelegate.setItems(dataset); List<String> filtered = adapterDelegate.performFiltering("it"); assertThat(filtered, hasItems("Italy", "UnitedKingdom")); }
BaseTypeAdapterDelegate extends BaseAdapter implements TypeAdapterDelegate<M>, AutoCompleteTypeAdapter<M> { @Override public final void onTextChanged(@NonNull CharSequence text) { lastText = text; computeTokenChangesAsync(text); } BaseTypeAdapterDelegate(@NonNull AutoCompleteViewBinder<M> viewBinder, @NonNull TokenFilter<M> tokenFilter); @VisibleForTesting BaseTypeAdapterDelegate(@NonNull Executor computationExecutor, @NonNull Handler mainThreadHandler, @NonNull AutoCompleteViewBinder<M> viewBinder, @NonNull TokenFilter<M> tokenFilter); @Override @NonNull TokenFilter<M> getFilter(); @Override @CallSuper void setItems(@NonNull List<M> items); @Override final void setFilteredItems(@NonNull List<M> filteredItems); @Override final int getCount(); @Override final @NonNull M getItem(int position); @Override long getItemId(int position); @Override @NonNull View getView(@NonNull LayoutInflater inflater, int position, @Nullable View convertView, @NonNull ViewGroup parent, @Nullable CharSequence constraint); @Override View getView(int position, View convertView, ViewGroup parent); @Override @WorkerThread final @NonNull List<M> performFiltering(@NonNull CharSequence constraint); @Override final void setOnTokensChangedListener(@Nullable OnTokensChangedListener<M> listener); @Override final void onTextChanged(@NonNull CharSequence text); }
@Test @SuppressWarnings("unchecked") public void testOnTextChanged() throws Exception { adapterDelegate.setItems(dataset); OnTokensChangedListener mockListener = mock(OnTokensChangedListener.class); adapterDelegate.setOnTokensChangedListener(mockListener); adapterDelegate.onTextChanged(" Spain"); ShadowLooper.runUiThreadTasks(); verify(mockListener).onTokenAdded(eq("Spain"), eq("Spain")); adapterDelegate.onTextChanged(" Spai"); ShadowLooper.runUiThreadTasks(); verify(mockListener).onTokenRemoved(eq("Spain"), eq("Spain")); }
BaseTypeAdapterDelegate extends BaseAdapter implements TypeAdapterDelegate<M>, AutoCompleteTypeAdapter<M> { @VisibleForTesting static Collection<CharSequence> getAddedTokens(Set<CharSequence> existingSet, Set<CharSequence> newSet) { Set<CharSequence> added = new HashSet<>(newSet); added.removeAll(existingSet); return added; } BaseTypeAdapterDelegate(@NonNull AutoCompleteViewBinder<M> viewBinder, @NonNull TokenFilter<M> tokenFilter); @VisibleForTesting BaseTypeAdapterDelegate(@NonNull Executor computationExecutor, @NonNull Handler mainThreadHandler, @NonNull AutoCompleteViewBinder<M> viewBinder, @NonNull TokenFilter<M> tokenFilter); @Override @NonNull TokenFilter<M> getFilter(); @Override @CallSuper void setItems(@NonNull List<M> items); @Override final void setFilteredItems(@NonNull List<M> filteredItems); @Override final int getCount(); @Override final @NonNull M getItem(int position); @Override long getItemId(int position); @Override @NonNull View getView(@NonNull LayoutInflater inflater, int position, @Nullable View convertView, @NonNull ViewGroup parent, @Nullable CharSequence constraint); @Override View getView(int position, View convertView, ViewGroup parent); @Override @WorkerThread final @NonNull List<M> performFiltering(@NonNull CharSequence constraint); @Override final void setOnTokensChangedListener(@Nullable OnTokensChangedListener<M> listener); @Override final void onTextChanged(@NonNull CharSequence text); }
@Test public void testGetAddedTokens() throws Exception { Collection<CharSequence> diff = getAddedTokens(Collections.emptySet(), Collections.emptySet()); assertThat(diff.size(), is(0)); diff = getAddedTokens(Collections.singleton("test"), (Collections.singleton("test"))); assertThat(diff.size(), is(0)); diff = getAddedTokens(Collections.singleton("test1"), Collections.singleton("test2")); assertThat(diff.size(), is(1)); assertThat(diff, hasItem("test2")); Set<CharSequence> diff1 = new HashSet<>(Arrays.asList("existing1", "existing2", "existing3")); Set<CharSequence> diff2 = new HashSet<>(Arrays.asList("new1", "new2", "existing2")); diff = getAddedTokens(diff1, diff2); assertThat(diff, hasItems("new1", "new2")); }
BaseTypeAdapterDelegate extends BaseAdapter implements TypeAdapterDelegate<M>, AutoCompleteTypeAdapter<M> { @VisibleForTesting static Collection<CharSequence> getRemovedTokens(Set<CharSequence> existingSet, Set<CharSequence> newSet) { Set<CharSequence> removed = new HashSet<>(existingSet); removed.removeAll(newSet); return removed; } BaseTypeAdapterDelegate(@NonNull AutoCompleteViewBinder<M> viewBinder, @NonNull TokenFilter<M> tokenFilter); @VisibleForTesting BaseTypeAdapterDelegate(@NonNull Executor computationExecutor, @NonNull Handler mainThreadHandler, @NonNull AutoCompleteViewBinder<M> viewBinder, @NonNull TokenFilter<M> tokenFilter); @Override @NonNull TokenFilter<M> getFilter(); @Override @CallSuper void setItems(@NonNull List<M> items); @Override final void setFilteredItems(@NonNull List<M> filteredItems); @Override final int getCount(); @Override final @NonNull M getItem(int position); @Override long getItemId(int position); @Override @NonNull View getView(@NonNull LayoutInflater inflater, int position, @Nullable View convertView, @NonNull ViewGroup parent, @Nullable CharSequence constraint); @Override View getView(int position, View convertView, ViewGroup parent); @Override @WorkerThread final @NonNull List<M> performFiltering(@NonNull CharSequence constraint); @Override final void setOnTokensChangedListener(@Nullable OnTokensChangedListener<M> listener); @Override final void onTextChanged(@NonNull CharSequence text); }
@Test public void testGetRemovedTokens() throws Exception { Collection<CharSequence> diff = getRemovedTokens(Collections.emptySet(), Collections.emptySet()); assertThat(diff.size(), is(0)); diff = getRemovedTokens(Collections.singleton("test"), Collections.singleton("test")); assertThat(diff.size(), is(0)); diff = getRemovedTokens(Collections.singleton("test1"), Collections.singleton("test2")); assertThat(diff.size(), is(1)); assertThat(diff, hasItem("test1")); Set<CharSequence> diff1 = new HashSet<>(Arrays.asList("existing1", "existing2", "existing3")); Set<CharSequence> diff2 = new HashSet<>(Arrays.asList("new1", "new2", "existing2")); diff = getRemovedTokens(diff1, diff2); assertThat(diff, hasItems("existing1", "existing3")); }
PrefixTokenizer implements MultiAutoCompleteTextView.Tokenizer { @Override public int findTokenStart(CharSequence text, int cursor) { if (text.length() == 0) { return 0; } char separator = getDefaultSeparator(); for (int i = cursor - 1; i >= 0; i--) { if (matchesPrefix(text, i)) { char charAt; if (i == 0 || (charAt = text.charAt(i - 1)) == separator || charAt == NEW_LINE) { return i; } } } return cursor; } PrefixTokenizer(char prefix); PrefixTokenizer(char... prefixes); @Override int findTokenStart(CharSequence text, int cursor); @Override int findTokenEnd(CharSequence text, int cursor); @Override CharSequence terminateToken(CharSequence text); }
@Test public void findTokenStart() throws Exception { assertThat(tokenizer.findTokenStart("", 0), is(0)); assertThat(tokenizer.findTokenStart("@", 1), is(0)); assertThat(tokenizer.findTokenStart(" @", 1), is(1)); assertThat(tokenizer.findTokenStart(" @te", 3), is(1)); assertThat(tokenizer.findTokenStart(" @te @tests", 5), is(1)); assertThat(tokenizer.findTokenStart(" @te @tests", 11), is(5)); assertThat(tokenizer.findTokenStart(" @te@tests", 10), is(1)); assertThat(tokenizer.findTokenStart("\n@te@tests", 10), is(1)); assertThat(tokenizer.findTokenStart(" ", 1), is(1)); assertThat(tokenizer.findTokenStart(" @", 0), is(0)); assertThat(tokenizer.findTokenStart("tests:", 6), is(6)); assertThat(tokenizer.findTokenStart("test@s:", 6), is(6)); assertThat(tokenizer.findTokenStart("test@\ns:", 7), is(7)); } @Test public void findTokenStart_multiple() throws Exception { assertThat(tokenizer.findTokenStart(" @:", 3), is(1)); assertThat(tokenizer.findTokenStart(" :@", 3), is(1)); assertThat(tokenizer.findTokenStart(" :test1@test2", 3), is(1)); assertThat(tokenizer.findTokenStart(" :test1 @test2", 9), is(8)); }
PrefixTokenizer implements MultiAutoCompleteTextView.Tokenizer { @Override public int findTokenEnd(CharSequence text, int cursor) { int length = text.length(); if (length == 0) { return 0; } char separator = getDefaultSeparator(); for (int i = cursor; i < length; i++) { char charAt = text.charAt(i); if (charAt == separator || charAt == NEW_LINE) { return i == 0 ? 0 : i - 1; } } return length; } PrefixTokenizer(char prefix); PrefixTokenizer(char... prefixes); @Override int findTokenStart(CharSequence text, int cursor); @Override int findTokenEnd(CharSequence text, int cursor); @Override CharSequence terminateToken(CharSequence text); }
@Test public void findTokenEnd() throws Exception { assertThat(tokenizer.findTokenEnd("", 0), is(0)); assertThat(tokenizer.findTokenEnd("@", 0), is(1)); assertThat(tokenizer.findTokenEnd("@ ", 0), is(0)); assertThat(tokenizer.findTokenEnd("@te ", 0), is(2)); assertThat(tokenizer.findTokenEnd("@te @tests", 0), is(2)); assertThat(tokenizer.findTokenEnd("@te @tests ", 4), is(9)); assertThat(tokenizer.findTokenEnd("@te@tests ", 0), is(8)); assertThat(tokenizer.findTokenEnd("\n@tetests\n", 1), is(8)); assertThat(tokenizer.findTokenEnd(" ", 0), is(0)); assertThat(tokenizer.findTokenEnd("@ ", 2), is(2)); assertThat(tokenizer.findTokenEnd("tests:", 0), is(6)); assertThat(tokenizer.findTokenEnd("test@s:", 0), is(7)); assertThat(tokenizer.findTokenEnd("test@\ns:", 0), is(4)); }
AutoCompleteUtils { public static String stripPrefixHandle(char handle, @Nullable CharSequence text) { if (TextUtils.isEmpty(text)) { return ""; } return text.charAt(0) == handle ? text.toString().substring(1) : text.toString(); } private AutoCompleteUtils(); static boolean hasPrefixHandle(char handle, @Nullable CharSequence token); static String stripPrefixHandle(char handle, @Nullable CharSequence text); @SuppressWarnings("unused") static void selectAllText(EditText editText); }
@Test public void stripHandle() throws Exception { assertThat(AutoCompleteUtils.stripPrefixHandle('@', ""), is("")); assertThat(AutoCompleteUtils.stripPrefixHandle('@', "no_handle"), is("no_handle")); assertThat(AutoCompleteUtils.stripPrefixHandle('@', "no_handle@"), is("no_handle@")); assertThat(AutoCompleteUtils.stripPrefixHandle('@', "@handle"), is("handle")); }
PrefixTokenizer implements MultiAutoCompleteTextView.Tokenizer { @Override public CharSequence terminateToken(CharSequence text) { int i = text.length(); char separator = getDefaultSeparator(); if (i == 0 || (i > 0 && text.charAt(i - 1) == separator)) { return text; } if (text instanceof Spanned) { SpannableString sp = new SpannableString(text + String.valueOf(separator)); TextUtils.copySpansFrom((Spanned) text, 0, text.length(), Object.class, sp, 0); return sp; } else { return text + String.valueOf(separator); } } PrefixTokenizer(char prefix); PrefixTokenizer(char... prefixes); @Override int findTokenStart(CharSequence text, int cursor); @Override int findTokenEnd(CharSequence text, int cursor); @Override CharSequence terminateToken(CharSequence text); }
@Test public void terminateToken() throws Exception { MatcherAssert.assertThat(tokenizer.terminateToken(""), is("")); MatcherAssert.assertThat(tokenizer.terminateToken(" "), is(" ")); MatcherAssert.assertThat(tokenizer.terminateToken("test "), is("test ")); MatcherAssert.assertThat(tokenizer.terminateToken("test"), is("test ")); }
AutoCompleteAdapter extends BaseAdapter implements Filterable { @Override public int getCount() { return currentTypeAdapter.getCount(); } AutoCompleteAdapter(@NonNull Context context, @NonNull List<TypeAdapterDelegate> typeAdapters, @Nullable MultiAutoComplete.Delayer delayer); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override boolean hasStableIds(); @Override int getViewTypeCount(); @Override int getItemViewType(int position); @Override @NonNull View getView(int position, View convertView, @NonNull ViewGroup parent); @Override @NonNull Filter getFilter(); }
@Test public void getCount() throws Exception { assertThat(autoCompleteAdapter.getCount(), is(0)); Filter filter = autoCompleteAdapter.getFilter(); performFiltering(filter, "it"); assertThat(autoCompleteAdapter.getCount(), is(2)); }
AutoCompleteAdapter extends BaseAdapter implements Filterable { @Override public Object getItem(int position) { return currentTypeAdapter.getItem(position); } AutoCompleteAdapter(@NonNull Context context, @NonNull List<TypeAdapterDelegate> typeAdapters, @Nullable MultiAutoComplete.Delayer delayer); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override boolean hasStableIds(); @Override int getViewTypeCount(); @Override int getItemViewType(int position); @Override @NonNull View getView(int position, View convertView, @NonNull ViewGroup parent); @Override @NonNull Filter getFilter(); }
@Test public void getItem() throws Exception { Filter filter = autoCompleteAdapter.getFilter(); performFiltering(filter, "it"); assertThat(autoCompleteAdapter.getItem(0), is("Italy")); assertThat(autoCompleteAdapter.getItem(1), is("United Kingdom")); }
AutoCompleteAdapter extends BaseAdapter implements Filterable { @Override public long getItemId(int position) { return currentTypeAdapter.getItemId(position); } AutoCompleteAdapter(@NonNull Context context, @NonNull List<TypeAdapterDelegate> typeAdapters, @Nullable MultiAutoComplete.Delayer delayer); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override boolean hasStableIds(); @Override int getViewTypeCount(); @Override int getItemViewType(int position); @Override @NonNull View getView(int position, View convertView, @NonNull ViewGroup parent); @Override @NonNull Filter getFilter(); }
@Test public void getItemId() throws Exception { Filter filter = autoCompleteAdapter.getFilter(); performFiltering(filter, ""); assertThat(autoCompleteAdapter.getItemId(0), is((long) "Ireland".hashCode())); assertThat(autoCompleteAdapter.getItemId(3), is((long) "Spain".hashCode())); }
AutoCompleteAdapter extends BaseAdapter implements Filterable { @Override public int getViewTypeCount() { return typeAdapters.size() + 1; } AutoCompleteAdapter(@NonNull Context context, @NonNull List<TypeAdapterDelegate> typeAdapters, @Nullable MultiAutoComplete.Delayer delayer); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override boolean hasStableIds(); @Override int getViewTypeCount(); @Override int getItemViewType(int position); @Override @NonNull View getView(int position, View convertView, @NonNull ViewGroup parent); @Override @NonNull Filter getFilter(); }
@Test public void getViewTypeCount() throws Exception { assertThat(autoCompleteAdapter.getViewTypeCount(), is(2)); Filter filter = autoCompleteAdapter.getFilter(); performFiltering(filter, "it"); assertThat(autoCompleteAdapter.getViewTypeCount(), is(2)); }
AutoCompleteAdapter extends BaseAdapter implements Filterable { @Override public int getItemViewType(int position) { if (currentTypeAdapter instanceof NullTypeAdapterDelegate) { return typeAdapters.size(); } return typeAdapters.indexOf(currentTypeAdapter); } AutoCompleteAdapter(@NonNull Context context, @NonNull List<TypeAdapterDelegate> typeAdapters, @Nullable MultiAutoComplete.Delayer delayer); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override boolean hasStableIds(); @Override int getViewTypeCount(); @Override int getItemViewType(int position); @Override @NonNull View getView(int position, View convertView, @NonNull ViewGroup parent); @Override @NonNull Filter getFilter(); }
@Test public void getItemViewType() throws Exception { assertThat(autoCompleteAdapter.getItemViewType(0), is(1)); Filter filter = autoCompleteAdapter.getFilter(); performFiltering(filter, ""); assertThat(autoCompleteAdapter.getItemViewType(0), is(0)); }
AutoCompleteAdapter extends BaseAdapter implements Filterable { @Override public @NonNull Filter getFilter() { if (filter == null) { filter = new AutoCompleteFilter(); if (delayer != null) { injectDelayer(filter, delayer); } } return filter; } AutoCompleteAdapter(@NonNull Context context, @NonNull List<TypeAdapterDelegate> typeAdapters, @Nullable MultiAutoComplete.Delayer delayer); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override boolean hasStableIds(); @Override int getViewTypeCount(); @Override int getItemViewType(int position); @Override @NonNull View getView(int position, View convertView, @NonNull ViewGroup parent); @Override @NonNull Filter getFilter(); }
@Test public void testFilter_performFiltering() throws Exception { Filter filter = autoCompleteAdapter.getFilter(); assertThat(filter, notNullValue()); performFiltering(filter, "it"); verify(((TypeAdapterDelegate) typeAdapter).getFilter()).stripHandle(eq("it")); verify(((TypeAdapterDelegate) typeAdapter).getFilter()).supportsToken("it"); verify(((TypeAdapterDelegate) typeAdapter).getFilter()).performFiltering("it", dataset); }
MultiAutoCompleteImpl implements MultiAutoComplete, TextWatcher, MultiAutoCompleteEditText.OnSelectionChangedListener { @Override public void onViewAttached(@NonNull MultiAutoCompleteEditText view) { editText = view; adapter = new AutoCompleteAdapter(view.getContext(), typeAdapters, delayer); editText.setAdapter(adapter); editText.setTokenizer(tokenizer); editText.addTextChangedListener(this); editText.setOnSelectionChangedListener(this); adapter.registerDataSetObserver(dataSetObserver); for (TypeAdapterDelegate adapter : typeAdapters) { adapter.registerDataSetObserver(delegateDataSetObserver); } } MultiAutoCompleteImpl(@NonNull Tokenizer tokenizer, @NonNull List<TypeAdapterDelegate> typeAdapters, @Nullable Delayer delayer); @Override void onViewAttached(@NonNull MultiAutoCompleteEditText view); @Override void onViewDetached(); @Override void beforeTextChanged(CharSequence s, int start, int count, int after); @Override void onTextChanged(CharSequence s, int start, int before, int count); @Override @CallSuper void afterTextChanged(Editable s); @Override boolean onSelectionChanged(int selStart, int selEnd); }
@Test public void onViewAttached() throws Exception { autoComplete.onViewAttached(editText); assertThat(autoComplete.getAdapter(), notNullValue()); assertThat(autoComplete.getEditText(), notNullValue()); }
MultiAutoCompleteImpl implements MultiAutoComplete, TextWatcher, MultiAutoCompleteEditText.OnSelectionChangedListener { @Override public void onViewDetached() { for (TypeAdapterDelegate adapter : typeAdapters) { adapter.unregisterDataSetObserver(delegateDataSetObserver); } if (adapter != null) { adapter.unregisterDataSetObserver(dataSetObserver); adapter.notifyDataSetInvalidated(); adapter = null; } if (editText != null) { editText.setAdapter(null); editText = null; } } MultiAutoCompleteImpl(@NonNull Tokenizer tokenizer, @NonNull List<TypeAdapterDelegate> typeAdapters, @Nullable Delayer delayer); @Override void onViewAttached(@NonNull MultiAutoCompleteEditText view); @Override void onViewDetached(); @Override void beforeTextChanged(CharSequence s, int start, int count, int after); @Override void onTextChanged(CharSequence s, int start, int before, int count); @Override @CallSuper void afterTextChanged(Editable s); @Override boolean onSelectionChanged(int selStart, int selEnd); }
@Test public void onViewDetached() throws Exception { autoComplete.onViewAttached(editText); autoComplete.onViewDetached(); assertThat(autoComplete.getAdapter(), nullValue()); assertThat(autoComplete.getEditText(), nullValue()); }
OpenSSLKey implements Serializable { public void encrypt(String password) throws GeneralSecurityException { encrypt(password.getBytes()); } OpenSSLKey(InputStream is); OpenSSLKey(String file); OpenSSLKey(PrivateKey key); OpenSSLKey(String algorithm, byte[] data); boolean isEncrypted(); void decrypt(String password); void decrypt(byte[] password); void encrypt(String password); void encrypt(byte[] password); void setEncryptionAlgorithm(String alg); PrivateKey getPrivateKey(); void writeTo(OutputStream output); void writeTo(Writer w); void writeTo(String file); @Override boolean equals(Object other); @Override int hashCode(); }
@Test public void testEqualsForKeysDifferingByEncrypted() throws Exception { OpenSSLKey key1 = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); OpenSSLKey key2 = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); key2.encrypt("too many secrets"); assertThat(key2, not(equalTo(key1))); } @Test public void testSerializableEncrypted() throws Exception { OpenSSLKey key = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); key.encrypt("too many secrets"); OpenSSLKey copy = serialiseAndDeserialise(key); assertThat(copy, equalTo(key)); }
SigningPolicyParser { public static Pattern getPattern(String patternStr) { if (patternStr == null) { throw new IllegalArgumentException(); } int startIndex = 0; int endIndex = patternStr.length(); StringBuffer buffer = new StringBuffer(""); while (startIndex < endIndex) { int star = patternStr.indexOf(WILDCARD, startIndex); if (star == -1) { star = endIndex; String preStr = patternStr.substring(startIndex, star); buffer = buffer.append(preStr); } else { String preStr = patternStr.substring(startIndex, star); buffer = buffer.append(preStr).append(WILDCARD_PATTERN); } startIndex = star + 1; } String tmpPatternStr = buffer.toString(); startIndex = 0; endIndex = tmpPatternStr.length(); buffer = new StringBuffer(""); while (startIndex < endIndex) { int qMark = tmpPatternStr.indexOf(SINGLE_CHAR, startIndex); if (qMark == -1) { qMark = endIndex; String preStr = tmpPatternStr.substring(startIndex, qMark); buffer = buffer.append(preStr); } else { String preStr = tmpPatternStr.substring(startIndex, qMark); buffer = buffer.append(preStr).append(SINGLE_PATTERN); } startIndex = qMark + 1; } tmpPatternStr = buffer.toString(); LogFactory.getLog(SigningPolicyParser.class.getCanonicalName()).debug("String with replaced pattern is " + tmpPatternStr); return Pattern.compile(tmpPatternStr, Pattern.CASE_INSENSITIVE); } Map<X500Principal, SigningPolicy> parse(String fileName); Map<X500Principal, SigningPolicy> parse(Reader reader); static Pattern getPattern(String patternStr); static final String ACCESS_ID_PREFIX; static final String ACCESS_ID_CA; static final String DEF_AUTH_X509; static final String DEF_AUTH_GLOBUS; static final String POS_RIGHTS; static final String NEG_RIGHTS; static final String CONDITION_PREFIX; static final String CONDITION_SUBJECT; static final String VALUE_CA_SIGN; static final String SINGLE_CHAR; static final String WILDCARD; static final String SINGLE_PATTERN; static final String WILDCARD_PATTERN; }
@Test public void testPatternMatching() throws Exception { String patternStr = "CN=abcdefgh"; String patternR = (SigningPolicyParser.getPattern(patternStr)) .pattern(); assertTrue("CN=abcdefgh".equals(patternR)); String pattern1Str = "CN=*def?gh?"; Pattern pattern1 = SigningPolicyParser.getPattern(pattern1Str); String pattern1R = pattern1.pattern(); assertTrue(("CN=" + SigningPolicyParser.WILDCARD_PATTERN + "def" + SigningPolicyParser.SINGLE_PATTERN + "gh" + SigningPolicyParser.SINGLE_PATTERN).equals(pattern1R)); String pattern2Str = "/CN=abc*def*gh"; Pattern pattern2 = SigningPolicyParser.getPattern(pattern2Str); String pattern2R = pattern2.pattern(); assertTrue( ("/CN=abc" + SigningPolicyParser.WILDCARD_PATTERN + "def" + SigningPolicyParser.WILDCARD_PATTERN + "gh").equals( pattern2R)); Vector<Pattern> allowed = new Vector(); allowed.add(pattern2); X500Principal fooPrincipal = new X500Principal("CN=foo"); SigningPolicy policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject21 = new X500Principal("CN=abc12DEF34defdef56gh"); assertTrue(policy.isValidSubject(subject21)); X500Principal subject22 = new X500Principal("CN=123abc12def34defdef56gh"); assertFalse(policy.isValidSubject(subject22)); X500Principal subject23 = new X500Principal("CN=abc12def34defdef56gh123"); assertFalse(policy.isValidSubject(subject23)); String pattern3Str = "*abc*def*gh*"; Pattern pattern3 = SigningPolicyParser.getPattern(pattern3Str); allowed.clear(); allowed.add(pattern3); policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject31 = new X500Principal("CN=ABC12def34defdef56gh"); assertTrue(policy.isValidSubject(subject31)); X500Principal subject32 = new X500Principal("CN=123abc12def34defdef56gh555"); assertTrue(policy.isValidSubject(subject32)); String pattern4Str = "/C=US/O=GlobusCN=user-??"; Pattern pattern6 = SigningPolicyParser.getPattern(pattern6Str); allowed.clear(); allowed.add(pattern6); policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject61 = new X500Principal("CN=user-12,CN=foo,O=Globus,C=US"); assertFalse(policy.isValidSubject(subject61)); X500Principal subject62 = new X500Principal("CN=user-12,CN=foo,O=Global,C=US"); assertTrue(policy.isValidSubject(subject62)); X500Principal subject63 = new X500Principal("CN=user-12,CN=bar 1,CN=foo ,O=global,C=US"); assertTrue(policy.isValidSubject(subject63)); String pattern7Str = "/C=US/O=Globus/CN=*/CN=user-??"; Pattern pattern7 = SigningPolicyParser.getPattern(pattern7Str); allowed.add(pattern7); policy = new SigningPolicy(fooPrincipal, allowed); X500Principal subject71 = new X500Principal("CN=user-12, CN=bar 1, CN=foo , O=Globus,C=US"); assertTrue(policy.isValidSubject(subject71)); assertTrue(policy.isValidSubject(subject63)); }
SigningPolicyParser { public Map<X500Principal, SigningPolicy> parse(String fileName) throws FileNotFoundException, SigningPolicyException { if ((fileName == null) || (fileName.trim().isEmpty())) { throw new IllegalArgumentException(); } logger.debug("Signing policy file name " + fileName); FileReader fileReader = null; try { fileReader = new FileReader(fileName); return parse(fileReader); } catch (Exception e) { throw new SigningPolicyException(e); } finally { if (fileReader != null) { try { fileReader.close(); } catch (Exception exp) { logger.debug("Error closing file reader", exp); } } } } Map<X500Principal, SigningPolicy> parse(String fileName); Map<X500Principal, SigningPolicy> parse(Reader reader); static Pattern getPattern(String patternStr); static final String ACCESS_ID_PREFIX; static final String ACCESS_ID_CA; static final String DEF_AUTH_X509; static final String DEF_AUTH_GLOBUS; static final String POS_RIGHTS; static final String NEG_RIGHTS; static final String CONDITION_PREFIX; static final String CONDITION_SUBJECT; static final String VALUE_CA_SIGN; static final String SINGLE_CHAR; static final String WILDCARD; static final String SINGLE_PATTERN; static final String WILDCARD_PATTERN; }
@Test(expected = SigningPolicyException.class) public void testFileFailure() throws Exception { SigningPolicyParser parser = new SigningPolicyParser(); parser.parse("Foo"); }
SimpleMemoryCertStore extends CertStoreSpi { @Override public Collection<? extends CRL> engineGetCRLs(CRLSelector selector) throws CertStoreException { List<X509CRL> l = new LinkedList<X509CRL>(); for (X509CRL crl : crlStore) { if (selector.match(crl)) { l.add(crl); } } return l; } SimpleMemoryCertStore(CertStoreParameters params); @Override Collection<? extends CRL> engineGetCRLs(CRLSelector selector); @Override Collection<? extends Certificate> engineGetCertificates(CertSelector selector); }
@Test public void testEngineGetCRLsCRLSelector() throws Exception { SimpleMemoryCertStoreParams params = new SimpleMemoryCertStoreParams(null, null); store = new SimpleMemoryCertStore(params); assertEquals(0, store.engineGetCRLs(new X509CRLSelector()).size()); params = new SimpleMemoryCertStoreParams(new X509Certificate[] {cert}, new X509CRL[] {crl}); store = new SimpleMemoryCertStore(params); assertEquals(1, store.engineGetCRLs(new X509CRLSelector()).size()); X509CRLSelector crlSelector = new X509CRLSelector(); crlSelector.addIssuerName("CN=non-existent"); assertEquals(0, store.engineGetCRLs(crlSelector).size()); }
SimpleMemoryCertStore extends CertStoreSpi { @Override public Collection<? extends Certificate> engineGetCertificates(CertSelector selector) throws CertStoreException { List<X509Certificate> l = new LinkedList<X509Certificate>(); X509CertSelector select = (X509CertSelector) selector; for (X509Certificate cert : certStore) { if (selector.match(cert)) { l.add(cert); } } return l; } SimpleMemoryCertStore(CertStoreParameters params); @Override Collection<? extends CRL> engineGetCRLs(CRLSelector selector); @Override Collection<? extends Certificate> engineGetCertificates(CertSelector selector); }
@Test public void testEngineGetCertificatesCertSelector() throws Exception { SimpleMemoryCertStoreParams params = new SimpleMemoryCertStoreParams(null, null); store = new SimpleMemoryCertStore(params); assertEquals(0, store.engineGetCertificates(new X509CertSelector()).size()); params = new SimpleMemoryCertStoreParams(new X509Certificate[] {cert}, new X509CRL[] {crl}); store = new SimpleMemoryCertStore(params); assertEquals(1, store.engineGetCertificates(new X509CertSelector()).size()); params = new SimpleMemoryCertStoreParams(new X509Certificate[] {cert}, new X509CRL[] {crl}); store = new SimpleMemoryCertStore(params); X509CertSelector selector = new X509CertSelector(); selector.setSubject(cert.getSubjectX500Principal()); assertEquals(1, store.engineGetCertificates(selector).size()); X509CertSelector certSelector = new X509CertSelector(); certSelector.setSubject("CN=non-existent"); assertEquals(0, store.engineGetCertificates(certSelector).size()); }
SimpleMemoryKeyStore extends KeyStoreSpi { @Override public int engineSize() { return this.certMap.size(); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }
@Test public void testEngineSize() throws Exception { assertEquals(0, store.engineSize()); store.engineSetCertificateEntry(cert.getSubjectDN().getName(), cert); assertEquals(1, store.engineSize()); }
SimpleMemoryKeyStore extends KeyStoreSpi { @Override public Enumeration<String> engineAliases() { return Collections.enumeration(this.certMap.keySet()); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }
@Test public void testEngineAliases() throws Exception { assertFalse(store.engineAliases().hasMoreElements()); store.engineSetCertificateEntry(cert.getSubjectDN().getName(), cert); Enumeration e = store.engineAliases(); assertEquals(cert.getSubjectDN().getName(), e.nextElement()); assertFalse(e.hasMoreElements()); }
SimpleMemoryKeyStore extends KeyStoreSpi { @Override public void engineStore(OutputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { throw new UnsupportedOperationException(); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }
@Test(expected = UnsupportedOperationException.class) public void testEngineStoreOutputStreamCharArray() throws Exception { store.engineStore(null); }
SimpleMemoryKeyStore extends KeyStoreSpi { @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) throws KeyStoreException { throw new UnsupportedOperationException(); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }
@Test(expected = UnsupportedOperationException.class) public void testEngineSetKeyEntryStringByteArrayCertificateArray() throws Exception { store.engineSetKeyEntry(null,null,null); } @Test(expected = UnsupportedOperationException.class) public void testEngineSetKeyEntryStringKeyCharArrayCertificateArray() throws Exception { store.engineSetKeyEntry(null, null, null); }
SimpleMemoryKeyStore extends KeyStoreSpi { @Override public void engineLoad(LoadStoreParameter params) throws IOException, NoSuchAlgorithmException, CertificateException { logger.debug("creating cert store."); if (params == null) { throw new IllegalArgumentException("parameter null"); } else if (!(params instanceof SimpleMemoryKeyStoreLoadStoreParameter)) { throw new IllegalArgumentException("Wrong parameter type"); } X509Certificate[] certs = ((SimpleMemoryKeyStoreLoadStoreParameter) params).getCerts(); this.certMap = new ConcurrentHashMap<String,X509Certificate>(); if (certs != null) { for (X509Certificate cert : certs) { if (cert != null) { logger.debug("adding cert " + cert.getSubjectDN().getName()); certMap.put(cert.getSubjectDN().getName(), cert); } } } } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }
@Test(expected = UnsupportedOperationException.class) public void testEngineLoadInputStreamCharArray() throws Exception { store.engineLoad(null,new char[3]); }
SimpleMemoryKeyStore extends KeyStoreSpi { @Override public String engineGetCertificateAlias(Certificate cert) { throw new UnsupportedOperationException(); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }
@Test(expected = UnsupportedOperationException.class) public void testEngineGetCertificateAliasCertificate() throws Exception { store.engineGetCertificateAlias(cert); }
SimpleMemoryKeyStore extends KeyStoreSpi { @Override public Certificate[] engineGetCertificateChain(String alias) { throw new UnsupportedOperationException(); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }
@Test(expected = UnsupportedOperationException.class) public void testEngineGetCertificateChainString() throws Exception { store.engineGetCertificateChain("test"); }
SimpleMemoryKeyStore extends KeyStoreSpi { @Override public Date engineGetCreationDate(String alias) { throw new UnsupportedOperationException(); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }
@Test(expected = UnsupportedOperationException.class) public void testEngineGetCreationDateString() throws Exception { store.engineGetCreationDate("test"); }
SimpleMemoryKeyStore extends KeyStoreSpi { @Override public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException { throw new UnsupportedOperationException(); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }
@Test(expected = UnsupportedOperationException.class) public void testEngineGetKeyStringCharArray() throws Exception { store.engineGetKey("test", new char[] {'t'}); }
SimpleMemorySigningPolicyStore implements SigningPolicyStore { public SigningPolicy getSigningPolicy(X500Principal caPrincipal) throws SigningPolicyStoreException { SigningPolicy policy = store.get(caPrincipal.getName(X500Principal.RFC2253)); if (policy == null) { X509Name name = new X509Name(false, caPrincipal.getName(X500Principal.RFC2253)); logger.debug("Getting from policy store: " + X509NameHelper.toString(name)); policy = store.get(X509NameHelper.toString(name)); } return policy; } SimpleMemorySigningPolicyStore(SigningPolicy[] policies); SigningPolicy getSigningPolicy(X500Principal caPrincipal); }
@Test public void testGetSigningPolicy() throws Exception { SigningPolicyParser parser = new SigningPolicyParser(); Map<X500Principal, SigningPolicy> policies; policies = parser.parse(new InputStreamReader(new GlobusPathMatchingResourcePatternResolver().getResource("classpath:/org/globus/gsi/test/49f18420.signing_policy").getInputStream())); assertNotNull(policies); assertFalse(policies.isEmpty()); SimpleMemorySigningPolicyStore store = new SimpleMemorySigningPolicyStore(policies.values().toArray(new SigningPolicy[1])); for (X500Principal p : policies.keySet()) { assertNotNull(store.getSigningPolicy(p)); } }
CertificateUtil { public static String toGlobusID(String dn) { return toGlobusID(dn, true); } private CertificateUtil(); static void init(); static void setProvider(String providerName); static void installSecureRandomProvider(); static int getCAPathConstraint(TBSCertificateStructure crt); static KeyPair generateKeyPair(String algorithm, int bits); static GSIConstants.CertificateType getCertificateType( TBSCertificateStructure crt); static BasicConstraints getBasicConstraints(X509Extension ext); static ASN1Primitive toASN1Primitive(byte[] data); static TBSCertificateStructure getTBSCertificateStructure( X509Certificate cert); static EnumSet<KeyUsage> getKeyUsage(TBSCertificateStructure crt); static EnumSet<KeyUsage> getKeyUsage(X509Extension ext); static ASN1Primitive getExtensionObject(X509Extension ext); static String toGlobusID(String dn); static String toGlobusID(String dn, boolean noreverse); static String toGlobusID(Principal name); static String toGlobusID(X500Principal principal); static X500Principal toPrincipal(String globusID); static CertPath getCertPath(X509Certificate[] certs); }
@Test public void testToGlobusIdForString() { String dn = CertificateUtil.toGlobusID("DC=org, DC=DOEGrids, OU=Certificate Authorities, CN=DOEGrids CA 1", true); assertThat(dn, is("/DC=org/DC=DOEGrids/OU=Certificate Authorities/CN=DOEGrids CA 1")); } @Test public void testToGlobusIdForReverseString() { String dn = CertificateUtil.toGlobusID("CN=DOEGrids CA 1, OU=Certificate Authorities, DC=DOEGrids, DC=org", false); assertThat(dn, is("/DC=org/DC=DOEGrids/OU=Certificate Authorities/CN=DOEGrids CA 1")); } @Test public void testToGlobusIdForX500Principal() { String dn = CertificateUtil.toGlobusID( new X500Principal("CN=DOEGrids CA 1, OU=Certificate Authorities, DC=DOEGrids, DC=org")); assertThat(dn, is("/DC=org/DC=DOEGrids/OU=Certificate Authorities/CN=DOEGrids CA 1")); }
CertificateUtil { public static X500Principal toPrincipal(String globusID) { if (globusID == null) { return null; } String id = globusID.trim(); StringBuilder buf = new StringBuilder(id.length()); if (!id.isEmpty()) { final int IDLE = 0; final int VALUE = 1; final int KEY = 2; int state = IDLE; int cEnd = 0; char[] asChars = id.toCharArray(); for (int i = asChars.length - 1; i >= 0; i--) { char c = asChars[i]; switch (state) { case KEY: if (c == '/' || c == ' ') { String s = id.substring(i + 1, cEnd + 1); int commaIndex = s.indexOf(','); if (commaIndex != -1) { s = s.substring(0, commaIndex) + "\\" + s.substring(commaIndex); } buf.append(s).append(','); state = IDLE; } break; case VALUE: if (c == '=') { state = KEY; } break; case IDLE: default: if (c == '/' || c == ' ') { continue; } else { cEnd = i; state = VALUE; } } } buf.deleteCharAt(buf.length() - 1); } String dn = buf.toString(); return new X500Principal(dn, KEYWORD_MAP); } private CertificateUtil(); static void init(); static void setProvider(String providerName); static void installSecureRandomProvider(); static int getCAPathConstraint(TBSCertificateStructure crt); static KeyPair generateKeyPair(String algorithm, int bits); static GSIConstants.CertificateType getCertificateType( TBSCertificateStructure crt); static BasicConstraints getBasicConstraints(X509Extension ext); static ASN1Primitive toASN1Primitive(byte[] data); static TBSCertificateStructure getTBSCertificateStructure( X509Certificate cert); static EnumSet<KeyUsage> getKeyUsage(TBSCertificateStructure crt); static EnumSet<KeyUsage> getKeyUsage(X509Extension ext); static ASN1Primitive getExtensionObject(X509Extension ext); static String toGlobusID(String dn); static String toGlobusID(String dn, boolean noreverse); static String toGlobusID(Principal name); static String toGlobusID(X500Principal principal); static X500Principal toPrincipal(String globusID); static CertPath getCertPath(X509Certificate[] certs); }
@Test public void testToPrincipal() { X500Principal principal = CertificateUtil.toPrincipal("/DC=org/DC=DOEGrids/OU=Certificate Authorities/CN=DOEGrids CA 1"); assertThat(principal, is(new X500Principal( "CN=DOEGrids CA 1, OU=Certificate Authorities, DC=DOEGrids, DC=org"))); } @Test public void testToPrincipalWithSlashInAttribute() { X500Principal principal = CertificateUtil.toPrincipal("/DC=org/DC=DOEGrids/OU=Certificate / Authorities/CN=DOEGrids CA 1"); assertThat(principal, is(new X500Principal( "CN=DOEGrids CA 1, OU=Certificate / Authorities, DC=DOEGrids, DC=org"))); } @Test public void testToPrincipalWithEmptyAttribute() { X500Principal principal = CertificateUtil.toPrincipal("/DC=org/DC=DOEGrids assertThat(principal, is(new X500Principal( "CN=DOEGrids CA 1, DC=DOEGrids, DC=org"))); } @Test public void testToPrincipalWithEmptyString() { X500Principal principal = CertificateUtil.toPrincipal(""); assertThat(principal, is(new X500Principal(""))); } @Test public void testToPrincipalWithWhiteSpace() { X500Principal principal = CertificateUtil.toPrincipal(" /DC=org/ DC=DOEGrids/OU=Certificate Authorities / CN=DOEGrids CA 1 "); assertThat(principal, is(new X500Principal( "CN=DOEGrids CA 1, OU=Certificate Authorities, DC=DOEGrids, DC=org"))); }
StringUtils { @SuppressWarnings({"SameParameterValue", "SameParameterValue"}) public static String align(String s, int width, int alignment) { return align(s, width, ' ', alignment); } @SuppressWarnings({"SameParameterValue", "SameParameterValue"}) static String align(String s, int width, int alignment); static String align(String s, int width, char paddingChar, int alignment); static void align(PrintWriter output, String s, int width, int alignment); static void align(PrintWriter output, String s, int width, char paddingChar, int alignment); static String multiply(char c, int count); static String multiply(String s, int count); static void multiply(PrintWriter output, char c, int count); @SuppressWarnings({"SameParameterValue"}) static void multiply(PrintWriter output, String s, int count); @SuppressWarnings({"SameParameterValue"}) static String prependEachLine(String s, String prependWith); static void prependEachLine(PrintWriter output, String s, String prependWith); static final int ALIGN_LEFT; static final int ALIGN_CENTER; static final int ALIGN_RIGHT; }
@Test public void testAlignLeft() throws Exception { Assert.assertEquals("foo ", StringUtils.align("foo", 9, StringUtils.ALIGN_LEFT)); Assert.assertEquals("fu+++++++", StringUtils.align("fu", 9, '+', StringUtils.ALIGN_LEFT)); } @Test public void testAlignCenter() throws Exception { Assert.assertEquals(" foo ", StringUtils.align("foo", 9, StringUtils.ALIGN_CENTER)); Assert.assertEquals("+++fu++++", StringUtils.align("fu", 9, '+', StringUtils.ALIGN_CENTER)); } @Test public void testAlignRight() throws Exception { Assert.assertEquals(" foo", StringUtils.align("foo", 9, StringUtils.ALIGN_RIGHT)); Assert.assertEquals("+++++++fu", StringUtils.align("fu", 9, '+', StringUtils.ALIGN_RIGHT)); } @Test public void testAlignWithWriterLeft() throws Exception { StringUtils.align(getWriter(), "foo", 9, StringUtils.ALIGN_LEFT); assertWriter("foo "); StringUtils.align(getWriter(), "fu", 9, '+', StringUtils.ALIGN_LEFT); assertWriter("fu+++++++"); } @Test public void testAlignWithWriterCenter() throws Exception { StringUtils.align(getWriter(), "foo", 9, StringUtils.ALIGN_CENTER); assertWriter(" foo "); StringUtils.align(getWriter(), "fu", 9, '+', StringUtils.ALIGN_CENTER); assertWriter("+++fu++++"); } @Test public void testAlignWithWriterRight() throws Exception { StringUtils.align(getWriter(), "foo", 9, StringUtils.ALIGN_RIGHT); assertWriter(" foo"); StringUtils.align(getWriter(), "fu", 9, '+', StringUtils.ALIGN_RIGHT); assertWriter("+++++++fu"); }
StringUtils { @SuppressWarnings({"SameParameterValue"}) public static String prependEachLine(String s, String prependWith) { StringWriter sw = new StringWriter(s.length()+(prependWith.length()*20)); prependEachLine(new PrintWriter(sw), s, prependWith); return sw.toString(); } @SuppressWarnings({"SameParameterValue", "SameParameterValue"}) static String align(String s, int width, int alignment); static String align(String s, int width, char paddingChar, int alignment); static void align(PrintWriter output, String s, int width, int alignment); static void align(PrintWriter output, String s, int width, char paddingChar, int alignment); static String multiply(char c, int count); static String multiply(String s, int count); static void multiply(PrintWriter output, char c, int count); @SuppressWarnings({"SameParameterValue"}) static void multiply(PrintWriter output, String s, int count); @SuppressWarnings({"SameParameterValue"}) static String prependEachLine(String s, String prependWith); static void prependEachLine(PrintWriter output, String s, String prependWith); static final int ALIGN_LEFT; static final int ALIGN_CENTER; static final int ALIGN_RIGHT; }
@Test public void testPrependEachLine() throws Exception { Assert.assertEquals(" 1\n 2\n 3", StringUtils.prependEachLine("1\n2\n3", " ")); } @Test public void testPrependEachLineWithWriter() throws Exception { StringUtils.prependEachLine(getWriter(), "1\n2\n3", " "); assertWriter(" 1\n 2\n 3"); }
MarkdownTable { public int getNumberOfColumns() { int columns = 0; for(List<MarkdownTableCell> row : this.header) { columns = Math.max(columns, getNumberOfColumnsInRow(row)); } for(List<MarkdownTableCell> row : this.body) { columns = Math.max(columns, getNumberOfColumnsInRow(row)); } return columns; } MarkdownTable(); List<MarkdownTableCell> addHeaderRow(); List<MarkdownTableCell> addBodyRow(); void renderTable(PrintWriter output, boolean allowColspan, boolean renderAsCode); int getNumberOfColumns(); }
@Test public void testGetNumberOfColumns() throws Exception { MarkdownTable mt = new MarkdownTable(); for(int i=0; i<10; i++) { List<MarkdownTableCell> row = mt.addBodyRow(); for(int j=0; j <= i%5; j++) { row.add(new MarkdownTableCell("cell "+j)); } } Assert.assertEquals(5, mt.getNumberOfColumns()); }
DocumentConverter { String cleanLinkId(String url, String linkId, boolean image) { String ret = linkId.replace('\n', ' '); ret = LINK_MULTIPLE_SPACES.matcher(ret).replaceAll(" "); ret = LINK_SAFE_CHARS.matcher(ret).replaceAll(LINK_REPLACEMENT); ret = LINK_MULTIPLE_REPLACE.matcher(ret).replaceAll(LINK_REPLACEMENT); ret = LINK_EDGE_REPLACE.matcher(ret).replaceAll(""); ret = ret.trim(); if(ret.length() == 0 || ret.equals(LINK_REPLACEMENT)) { if(image) { if(url != null) { Matcher m = LINK_FILENAME.matcher(url); if(m.find()) { ret = cleanLinkId(null, m.group(1), true); } else { genericImageUrlCounter++; ret = "Image " + genericImageUrlCounter; } } else { genericImageUrlCounter++; ret = "Image " + genericImageUrlCounter; } } else { genericLinkUrlCounter++; ret = "Link " + genericLinkUrlCounter; } } return ret; } DocumentConverter(Options options); @SuppressWarnings({"UnusedDeclaration"}) Options getOptions(); @SuppressWarnings({"UnusedDeclaration"}) TextCleaner getCleaner(); @SuppressWarnings({"UnusedDeclaration"}) Map<String, NodeHandler> getBlockNodes(); @SuppressWarnings({"UnusedDeclaration"}) Map<String, NodeHandler> getInlineNodes(); @SuppressWarnings({"UnusedDeclaration"}) BlockWriter getOutput(); @SuppressWarnings({"UnusedDeclaration"}) void setOutput(BlockWriter output); @SuppressWarnings({"WeakerAccess"}) void addInlineNode(NodeHandler handler, String tagnames); @SuppressWarnings({"WeakerAccess"}) void addBlockNode(NodeHandler handler, String tagnames); void convert(Document doc, Writer out); void convert(Document doc, OutputStream out); String convert(Document doc); void walkNodes(NodeHandler currentNode, Element el); void walkNodes(NodeHandler currentNodeHandler, Element el, Map<String, NodeHandler> nodeList); String getInlineContent(NodeHandler currentNode, Element el); String getInlineContent(NodeHandler currentNode, Element el, boolean undoLeadingEscapes); String addLink(String url, String recommendedName, boolean image); }
@Test public void testSimpleLink() throws Exception { Assert.assertEquals("test", dc.cleanLinkId(LINK_URL, "test", false)); Assert.assertEquals("test-test", dc.cleanLinkId(LINK_URL, "test-test", false)); Assert.assertEquals("test test", dc.cleanLinkId(LINK_URL, "test\ntest", false)); } @Test public void testReplacementLinks() throws Exception { Assert.assertEquals("test_test", dc.cleanLinkId(LINK_URL, "test*&^$#˜∂test", false)); Assert.assertEquals("test", dc.cleanLinkId(LINK_URL, "&(^test", false)); Assert.assertEquals("test", dc.cleanLinkId(LINK_URL, "test^%$", false)); } @Test public void testGenericLinks() throws Exception { Assert.assertEquals("Link 1", dc.cleanLinkId(LINK_URL, "*(&(*&(", false)); Assert.assertEquals("Link 2", dc.cleanLinkId(LINK_URL, "_!!\n!!_", false)); } @Test public void testGenericImages() throws Exception { Assert.assertEquals("Image 1", dc.cleanLinkId(IMAGE_NOFILE_URL, "*(&(*&(", true)); Assert.assertEquals("Image 2", dc.cleanLinkId(IMAGE_NOFILE_URL, "_!!\n!!_", true)); Assert.assertEquals("image.jpg", dc.cleanLinkId(IMAGE_URL, "!", true)); Assert.assertEquals("Image 3", dc.cleanLinkId(IMAGE_INVALID_URL, "!", true)); }
TextCleaner { public String clean(Object input) { return clean(input, true); } TextCleaner(Options options); String clean(Object input); String cleanCode(Object input); String cleanInlineCode(Object input); String unescapeLeadingCharacters(String input); String cleanUrl(String input); }
@Test public void testCleanBasic() throws Exception { assertEqualsAndPrint(loadOut("cleanBasic"), BASIC.clean(loadBasicIn())); } @Test public void testCleanFull() throws Exception { assertEqualsAndPrint(loadOut("cleanFull"), FULL.clean(loadFullIn())); }
TextCleaner { public String cleanCode(Object input) { return clean(input, false); } TextCleaner(Options options); String clean(Object input); String cleanCode(Object input); String cleanInlineCode(Object input); String unescapeLeadingCharacters(String input); String cleanUrl(String input); }
@Test public void testCleanCodeBasic() throws Exception { assertEqualsAndPrint(loadOut("cleanCodeBasic"), BASIC.cleanCode(loadBasicIn())); } @Test public void testCleanCodeFull() throws Exception { assertEqualsAndPrint(loadOut("cleanCodeFull"), FULL.cleanCode(loadFullIn())); }
TextCleaner { public String cleanInlineCode(Object input) { String output = clean(input, false).replace('\n', ' '); if(output.indexOf('`') != -1) { String prepend = ""; if(output.charAt(0) == '`') { prepend = " "; } String append = ""; if(output.charAt(output.length()-1) == '`') { append = " "; } String delim = getDelimiter(output); output = String.format("%s%s%s%s%s", delim, prepend, output, append, delim); } else { output = String.format("`%s`", output); } return output; } TextCleaner(Options options); String clean(Object input); String cleanCode(Object input); String cleanInlineCode(Object input); String unescapeLeadingCharacters(String input); String cleanUrl(String input); }
@Test public void testCleanInlineCodeSimple() throws Exception { Assert.assertEquals("`hello & > world`", BASIC.cleanInlineCode("hello &amp; \n&gt; world")); } @Test public void testCleanInlineCodeLeadingTick() throws Exception { Assert.assertEquals("`` `tick``", BASIC.cleanInlineCode("`tick")); } @Test public void testCleanInlineCodeTrailingTick() throws Exception { Assert.assertEquals("``tick` ``", BASIC.cleanInlineCode("tick`")); } @Test public void testCleanInlineCodeInlineTick() throws Exception { Assert.assertEquals("``ti`ck``", BASIC.cleanInlineCode("ti`ck")); } @Test public void testCleanInlineCodeLotsOfTicks() throws Exception { Assert.assertEquals("```` ``t```i`ck` ````", BASIC.cleanInlineCode("``t`&#96;`i`ck`")); }
Strings { public static String replaceLast(String text, String regex, String replacement) { return text.replaceFirst("(?s)(.*)" + regex, "$1" + replacement); } private Strings(); static String replaceLast(String text, String regex, String replacement); static SpannableStringBuilder colorizeBackground(@NonNull String text, @NonNull String matchText, @ColorInt int color, boolean ignoreCase); static String EMPTY; static String NEW_LINE; }
@Test public void replaceLast() throws Exception { Assertions.assertThat("2017-02-14T13:54:04+0900") .isEqualTo(Strings.replaceLast("2017-02-14T13:54:04+09:00", ":", "")); }
Api implements DataSource { @Override public Observable<Feed> getFeed(@NonNull final String category) { return getFeed(category, false); } @VisibleForTesting Api(@NonNull AwesomeBlogsLocalSource localSource, @NonNull AwesomeBlogsRemoteSource remoteSource); Api(@NonNull Context context, @NonNull Supplier<String> userAgentSupplier, @NonNull Supplier<String> deviceIdSupplier, @NonNull Supplier<String> fcmTokenSupplier, @NonNull Supplier<String> accessTokenSupplier, boolean loggable); @Override Observable<Feed> getFeed(@NonNull final String category); Observable<Feed> getFeed(@NonNull final String category, final boolean forceRefresh); Observable<Pair<String, List<Entry>>> getFreshEntries(); Observable<Pair<String, Boolean>> getSilentRefresh(); Observable<Entry> getEntry(@NonNull String link); Observable<List<Entry>> getEntries(@NonNull String author); Observable<RealmResults<Read>> getHistory(); Observable<RealmResults<Entry>> search(@NonNull String keyword); Observable<Boolean> isRead(@NonNull String link); void markAsRead(@NonNull Entry entry, long readAt); Observable<RealmResults<Favorite>> getFavorites(); Observable<Boolean> isFavorite(@NonNull String link); void markAsFavorite(@NonNull Entry entry, long favoriteAt); void unMarkAsFavorite(@NonNull Entry entry); Observable<Date> getExpiryDate(@NonNull String category); void clearExpiryDate(@NonNull String category); }
@Test public void getFeed_empty() throws Exception { doReturn(Observable.<Feed>empty()).when(localSource).getFeed(anyString()); doReturn(Observable.just(new Feed())).when(remoteSource).getFeed(anyString()); api.getFeed("dev") .test() .awaitTerminalEvent() .assertValueCount(1); verify(localSource, times(1)).getFeed(anyString()); verify(remoteSource, times(1)).getFeed(anyString()); } @Test public void getFeed_one_more() throws Exception { doReturn(Observable.just(new Feed())).when(localSource).getFeed(anyString()); doReturn(Observable.just(new Feed())).when(remoteSource).getFeed(anyString()); api.getFeed("dev") .test() .awaitTerminalEvent() .assertValueCount(1); verify(localSource, times(1)).getFeed(anyString()); verify(remoteSource, times(1)).getFeed(anyString()); }
StringUtils { public static String multiply(char c, int count) { return multiply(String.valueOf(c), count); } @SuppressWarnings({"SameParameterValue", "SameParameterValue"}) static String align(String s, int width, int alignment); static String align(String s, int width, char paddingChar, int alignment); static void align(PrintWriter output, String s, int width, int alignment); static void align(PrintWriter output, String s, int width, char paddingChar, int alignment); static String multiply(char c, int count); static String multiply(String s, int count); static void multiply(PrintWriter output, char c, int count); @SuppressWarnings({"SameParameterValue"}) static void multiply(PrintWriter output, String s, int count); @SuppressWarnings({"SameParameterValue"}) static String prependEachLine(String s, String prependWith); static void prependEachLine(PrintWriter output, String s, String prependWith); static final int ALIGN_LEFT; static final int ALIGN_CENTER; static final int ALIGN_RIGHT; }
@Test public void testMultiplyCharacter() throws Exception { Assert.assertEquals("", StringUtils.multiply('c', 0)); Assert.assertEquals("ccc", StringUtils.multiply('c', 3)); } @Test public void testMultiplyString() throws Exception { Assert.assertEquals("", StringUtils.multiply("str", 0)); Assert.assertEquals("strstrstrstr", StringUtils.multiply("str", 4)); } @Test public void testMultiplyCharacterWithWriter() throws Exception { StringUtils.multiply(getWriter(), 'c', 0); assertWriter(""); StringUtils.multiply(getWriter(), 'c', 3); assertWriter("ccc"); } @Test public void testMultiplyStringWithWriter() throws Exception { StringUtils.multiply(getWriter(), "str", 0); assertWriter(""); StringUtils.multiply(getWriter(), "str", 4); assertWriter("strstrstrstr"); }
TorqueDecoder implements Decoder<T> { public void update(T next) { counterBasedDecoder.update(next); } TorqueDecoder(FilteredBroadcastMessenger<TaggedTelemetryEvent> updateHub); void reset(); void update(T next); void invalidate(); }
@Test public void matchesKnownGood() { FilteredBroadcastMessenger<TaggedTelemetryEvent> bus = new FilteredBroadcastMessenger<TaggedTelemetryEvent>(); class PowerListener implements BroadcastListener<TaggedTelemetryEvent> { BigDecimal power; public void receiveMessage(TaggedTelemetryEvent telemetryEvent) { if (telemetryEvent instanceof TorquePowerUpdate) { TorquePowerUpdate up = (TorquePowerUpdate) telemetryEvent; power = up.getPower(); } } }; PowerListener powerListener = new PowerListener(); bus.addListener(TaggedTelemetryEvent.class, powerListener); BigDecimal speed = new BigDecimal(10.0); BigDecimal period = WHEEL_CIRCUM.multiply(new BigDecimal(Math.pow(10, -3))).divide(speed, 20, BigDecimal.ROUND_HALF_UP); int power = 200; int rotationsDelta = 10; int eventsDelta = 1; final byte[] data1 = new byte[8]; final byte[] data2 = new byte[8]; new TorqueData.TorqueDataPayload() .encode(data1); new TorqueData.TorqueDataPayload() .setEvents(eventsDelta) .updateTorqueSumFromPower(power, period) .setRotations(rotationsDelta) .encode(data2); TorqueData p1 = new TorqueData(data1); TorqueData p2 = new TorqueData(data2); TorqueDecoder<TorqueDecodable> dec = new TorqueDecoder<>(bus); dec.update(p1); dec.update(p2); assertEquals(new BigDecimal(power).setScale(0, RoundingMode.HALF_UP), powerListener.power.setScale(0, RoundingMode.HALF_UP)); }
SpeedDecoder implements Decoder<T> { @Override public void update(T newPage) { decoder.update(newPage); } SpeedDecoder(FilteredBroadcastMessenger<TaggedTelemetryEvent> updateHub, BigDecimal wheelCircumference); void reset(); @Override void update(T newPage); @Override void invalidate(); }
@Test public void matchesKnownGood() { FilteredBroadcastMessenger<TaggedTelemetryEvent> bus = new FilteredBroadcastMessenger<TaggedTelemetryEvent>(); class FreqListener implements BroadcastListener<TaggedTelemetryEvent> { private BigDecimal freq; private BigDecimal speedKmh; public void receiveMessage(TaggedTelemetryEvent telemetryEvent) { if (telemetryEvent instanceof WheelFreqUpdate) { WheelFreqUpdate up = (WheelFreqUpdate) telemetryEvent; freq = up.getRotationalFrequency(); } if (telemetryEvent instanceof SpeedUpdate) { speedKmh = ((SpeedUpdate) telemetryEvent).getSpeed(); } } }; FreqListener freqListener = new FreqListener(); bus.addListener(TaggedTelemetryEvent.class, freqListener); BigDecimal speed = new BigDecimal(10.0); BigDecimal period = WHEEL_CIRCUM.divide(speed, 20, BigDecimal.ROUND_HALF_UP); int power = 200; int rotationsDelta = 10; int eventsDelta = 1; final byte[] data1 = new byte[8]; final byte[] data2 = new byte[8]; new TorqueData.TorqueDataPayload() .encode(data1); new TorqueData.TorqueDataPayload() .setEvents(eventsDelta) .updateTorqueSumFromPower(power, period) .setRotations(rotationsDelta) .encode(data2); TorqueData p1 = new TorqueData(data1); TorqueData p2 = new TorqueData(data2); SpeedDecoder<SpeedDecodable> dec = new SpeedDecoder<>(bus, WHEEL_CIRCUM); dec.update(p1); dec.update(p2); BigDecimal calcSpeed = WHEEL_CIRCUM.multiply(freqListener.freq); assertEquals( speed.setScale(1, RoundingMode.HALF_UP), calcSpeed.setScale(1, RoundingMode.HALF_UP) ); assertEquals( speed.multiply(new BigDecimal(3.6)).setScale(0, RoundingMode.HALF_UP), freqListener.speedKmh.setScale(0, RoundingMode.HALF_UP) ); }