src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
SpringContextHolder implements ApplicationContextAware { public static ApplicationContext getApplicationContext() { checkApplicationContext(); return context; } @Override void setApplicationContext(ApplicationContext applicationContext); static ApplicationContext getApplicationContext(); static T getBean(String name); static T getBean(Class<T> clazz); }
@Test public void testGetApplicationContext() { ApplicationContext context = SpringContextHolder.getApplicationContext(); PersonMapper personMapper = SpringContextHolder.getBean(PersonMapper.class); personMapper.findAll(); personMapper.findAll(); logger.info(personMapper.getClass().getName()); }
GatewayApiController { @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) public Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isEmpty(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } try { List<ApiDefinitionEntity> apis = sentinelApiClient.fetchApis(app, ip, port).get(); repository.saveAll(apis); return Result.ofSuccess(apis); } catch (Throwable throwable) { logger.error("queryApis error:", throwable); return Result.ofThrowable(-1, throwable); } } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteApi(Long id); }
@Test public void testQueryApis() throws Exception { String path = "/gateway/api/list.json"; List<ApiDefinitionEntity> entities = new ArrayList<>(); ApiDefinitionEntity entity = new ApiDefinitionEntity(); entity.setId(1L); entity.setApp(TEST_APP); entity.setIp(TEST_IP); entity.setPort(TEST_PORT); entity.setApiName("foo"); Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); Set<ApiPredicateItemEntity> itemEntities = new LinkedHashSet<>(); entity.setPredicateItems(itemEntities); ApiPredicateItemEntity itemEntity = new ApiPredicateItemEntity(); itemEntity.setPattern("/aaa"); itemEntity.setMatchStrategy(URL_MATCH_STRATEGY_EXACT); itemEntities.add(itemEntity); entities.add(entity); ApiDefinitionEntity entity2 = new ApiDefinitionEntity(); entity2.setId(2L); entity2.setApp(TEST_APP); entity2.setIp(TEST_IP); entity2.setPort(TEST_PORT); entity2.setApiName("biz"); entity.setGmtCreate(date); entity.setGmtModified(date); Set<ApiPredicateItemEntity> itemEntities2 = new LinkedHashSet<>(); entity2.setPredicateItems(itemEntities2); ApiPredicateItemEntity itemEntity2 = new ApiPredicateItemEntity(); itemEntity2.setPattern("/bbb"); itemEntity2.setMatchStrategy(URL_MATCH_STRATEGY_PREFIX); itemEntities2.add(itemEntity2); entities.add(entity2); CompletableFuture<List<ApiDefinitionEntity>> completableFuture = mock(CompletableFuture.class); given(completableFuture.get()).willReturn(entities); given(sentinelApiClient.fetchApis(TEST_APP, TEST_IP, TEST_PORT)).willReturn(completableFuture); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(path); requestBuilder.param("app", TEST_APP); requestBuilder.param("ip", TEST_IP); requestBuilder.param("port", String.valueOf(TEST_PORT)); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).fetchApis(TEST_APP, TEST_IP, TEST_PORT); Result<List<ApiDefinitionEntity>> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<List<ApiDefinitionEntity>>>(){}); assertTrue(result.isSuccess()); List<ApiDefinitionEntity> data = result.getData(); assertEquals(2, data.size()); assertEquals(entities, data); List<ApiDefinitionEntity> entitiesInMem = repository.findAllByApp(TEST_APP); assertEquals(2, entitiesInMem.size()); assertEquals(entities, entitiesInMem); }
GatewayApiController { @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } ApiDefinitionEntity entity = new ApiDefinitionEntity(); entity.setApp(app.trim()); String ip = reqVo.getIp(); if (StringUtil.isBlank(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } entity.setIp(ip.trim()); Integer port = reqVo.getPort(); if (port == null) { return Result.ofFail(-1, "port can't be null"); } entity.setPort(port); String apiName = reqVo.getApiName(); if (StringUtil.isBlank(apiName)) { return Result.ofFail(-1, "apiName can't be null or empty"); } entity.setApiName(apiName.trim()); List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems(); if (CollectionUtils.isEmpty(predicateItems)) { return Result.ofFail(-1, "predicateItems can't empty"); } List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>(); for (ApiPredicateItemVo predicateItem : predicateItems) { ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); Integer matchStrategy = predicateItem.getMatchStrategy(); if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } predicateItemEntity.setMatchStrategy(matchStrategy); String pattern = predicateItem.getPattern(); if (StringUtil.isBlank(pattern)) { return Result.ofFail(-1, "pattern can't be null or empty"); } predicateItemEntity.setPattern(pattern); predicateItemEntities.add(predicateItemEntity); } entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); List<ApiDefinitionEntity> allApis = repository.findAllByMachine(MachineInfo.of(app.trim(), ip.trim(), port)); if (allApis.stream().map(o -> o.getApiName()).anyMatch(o -> o.equals(apiName.trim()))) { return Result.ofFail(-1, "apiName exists: " + apiName); } Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("add gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(app, ip, port)) { logger.warn("publish gateway apis fail after add"); } return Result.ofSuccess(entity); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteApi(Long id); }
@Test public void testAddApi() throws Exception { String path = "/gateway/api/new.json"; AddApiReqVo reqVo = new AddApiReqVo(); reqVo.setApp(TEST_APP); reqVo.setIp(TEST_IP); reqVo.setPort(TEST_PORT); reqVo.setApiName("customized_api"); List<ApiPredicateItemVo> itemVos = new ArrayList<>(); ApiPredicateItemVo itemVo = new ApiPredicateItemVo(); itemVo.setMatchStrategy(URL_MATCH_STRATEGY_EXACT); itemVo.setPattern("/product"); itemVos.add(itemVo); reqVo.setPredicateItems(itemVos); given(sentinelApiClient.modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path); requestBuilder.content(JSON.toJSONString(reqVo)).contentType(MediaType.APPLICATION_JSON); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any()); Result<ApiDefinitionEntity> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<ApiDefinitionEntity>>() {}); assertTrue(result.isSuccess()); ApiDefinitionEntity entity = result.getData(); assertNotNull(entity); assertEquals(TEST_APP, entity.getApp()); assertEquals(TEST_IP, entity.getIp()); assertEquals(TEST_PORT, entity.getPort()); assertEquals("customized_api", entity.getApiName()); assertNotNull(entity.getId()); assertNotNull(entity.getGmtCreate()); assertNotNull(entity.getGmtModified()); Set<ApiPredicateItemEntity> predicateItemEntities = entity.getPredicateItems(); assertEquals(1, predicateItemEntities.size()); ApiPredicateItemEntity predicateItemEntity = predicateItemEntities.iterator().next(); assertEquals(URL_MATCH_STRATEGY_EXACT, predicateItemEntity.getMatchStrategy().intValue()); assertEquals("/product", predicateItemEntity.getPattern()); List<ApiDefinitionEntity> entitiesInMem = repository.findAllByApp(TEST_APP); assertEquals(1, entitiesInMem.size()); assertEquals(entity, entitiesInMem.get(0)); }
GatewayApiController { @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } Long id = reqVo.getId(); if (id == null) { return Result.ofFail(-1, "id can't be null"); } ApiDefinitionEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "api does not exist, id=" + id); } List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems(); if (CollectionUtils.isEmpty(predicateItems)) { return Result.ofFail(-1, "predicateItems can't empty"); } List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>(); for (ApiPredicateItemVo predicateItem : predicateItems) { ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); int matchStrategy = predicateItem.getMatchStrategy(); if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "Invalid matchStrategy: " + matchStrategy); } predicateItemEntity.setMatchStrategy(matchStrategy); String pattern = predicateItem.getPattern(); if (StringUtil.isBlank(pattern)) { return Result.ofFail(-1, "pattern can't be null or empty"); } predicateItemEntity.setPattern(pattern); predicateItemEntities.add(predicateItemEntity); } entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("update gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(app, entity.getIp(), entity.getPort())) { logger.warn("publish gateway apis fail after update"); } return Result.ofSuccess(entity); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteApi(Long id); }
@Test public void testUpdateApi() throws Exception { String path = "/gateway/api/save.json"; ApiDefinitionEntity addEntity = new ApiDefinitionEntity(); addEntity.setApp(TEST_APP); addEntity.setIp(TEST_IP); addEntity.setPort(TEST_PORT); addEntity.setApiName("bbb"); Date date = new Date(); date = DateUtils.addSeconds(date, -1); addEntity.setGmtCreate(date); addEntity.setGmtModified(date); Set<ApiPredicateItemEntity> addRedicateItemEntities = new HashSet<>(); addEntity.setPredicateItems(addRedicateItemEntities); ApiPredicateItemEntity addPredicateItemEntity = new ApiPredicateItemEntity(); addPredicateItemEntity.setMatchStrategy(URL_MATCH_STRATEGY_EXACT); addPredicateItemEntity.setPattern("/order"); addEntity = repository.save(addEntity); UpdateApiReqVo reqVo = new UpdateApiReqVo(); reqVo.setId(addEntity.getId()); reqVo.setApp(TEST_APP); List<ApiPredicateItemVo> itemVos = new ArrayList<>(); ApiPredicateItemVo itemVo = new ApiPredicateItemVo(); itemVo.setMatchStrategy(URL_MATCH_STRATEGY_PREFIX); itemVo.setPattern("/my_order"); itemVos.add(itemVo); reqVo.setPredicateItems(itemVos); given(sentinelApiClient.modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path); requestBuilder.content(JSON.toJSONString(reqVo)).contentType(MediaType.APPLICATION_JSON); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any()); Result<ApiDefinitionEntity> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<ApiDefinitionEntity>>() {}); assertTrue(result.isSuccess()); ApiDefinitionEntity entity = result.getData(); assertNotNull(entity); assertEquals("bbb", entity.getApiName()); assertEquals(date, entity.getGmtCreate()); assertNotNull(entity.getGmtModified()); assertNotEquals(entity.getGmtCreate(), entity.getGmtModified()); Set<ApiPredicateItemEntity> predicateItemEntities = entity.getPredicateItems(); assertEquals(1, predicateItemEntities.size()); ApiPredicateItemEntity predicateItemEntity = predicateItemEntities.iterator().next(); assertEquals(URL_MATCH_STRATEGY_PREFIX, predicateItemEntity.getMatchStrategy().intValue()); assertEquals("/my_order", predicateItemEntity.getPattern()); List<ApiDefinitionEntity> entitiesInMem = repository.findAllByApp(TEST_APP); assertEquals(1, entitiesInMem.size()); assertEquals(entity, entitiesInMem.get(0)); }
GatewayApiController { @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteApi(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } ApiDefinitionEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Throwable throwable) { logger.error("delete gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { logger.warn("publish gateway apis fail after delete"); } return Result.ofSuccess(id); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteApi(Long id); }
@Test public void testDeleteApi() throws Exception { String path = "/gateway/api/delete.json"; ApiDefinitionEntity addEntity = new ApiDefinitionEntity(); addEntity.setApp(TEST_APP); addEntity.setIp(TEST_IP); addEntity.setPort(TEST_PORT); addEntity.setApiName("ccc"); Date date = new Date(); addEntity.setGmtCreate(date); addEntity.setGmtModified(date); Set<ApiPredicateItemEntity> addRedicateItemEntities = new HashSet<>(); addEntity.setPredicateItems(addRedicateItemEntities); ApiPredicateItemEntity addPredicateItemEntity = new ApiPredicateItemEntity(); addPredicateItemEntity.setMatchStrategy(URL_MATCH_STRATEGY_EXACT); addPredicateItemEntity.setPattern("/user/add"); addEntity = repository.save(addEntity); given(sentinelApiClient.modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path); requestBuilder.param("id", String.valueOf(addEntity.getId())); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any()); Result<Long> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<Long>>() {}); assertTrue(result.isSuccess()); assertEquals(addEntity.getId(), result.getData()); List<ApiDefinitionEntity> entitiesInMem = repository.findAllByApp(TEST_APP); assertEquals(0, entitiesInMem.size()); }
GatewayFlowRuleController { @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) public Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isEmpty(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } try { List<GatewayFlowRuleEntity> rules = sentinelApiClient.fetchGatewayFlowRules(app, ip, port).get(); repository.saveAll(rules); return Result.ofSuccess(rules); } catch (Throwable throwable) { logger.error("query gateway flow rules error:", throwable); return Result.ofThrowable(-1, throwable); } } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteFlowRule(Long id); }
@Test public void testQueryFlowRules() throws Exception { String path = "/gateway/flow/list.json"; List<GatewayFlowRuleEntity> entities = new ArrayList<>(); GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity(); entity.setId(1L); entity.setApp(TEST_APP); entity.setIp(TEST_IP); entity.setPort(TEST_PORT); entity.setResource("httpbin_route"); entity.setResourceMode(RESOURCE_MODE_ROUTE_ID); entity.setGrade(FLOW_GRADE_QPS); entity.setCount(5D); entity.setInterval(30L); entity.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_SECOND); entity.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT); entity.setBurst(0); entity.setMaxQueueingTimeoutMs(0); GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); itemEntity.setParseStrategy(PARAM_PARSE_STRATEGY_CLIENT_IP); entities.add(entity); GatewayFlowRuleEntity entity2 = new GatewayFlowRuleEntity(); entity2.setId(2L); entity2.setApp(TEST_APP); entity2.setIp(TEST_IP); entity2.setPort(TEST_PORT); entity2.setResource("some_customized_api"); entity2.setResourceMode(RESOURCE_MODE_CUSTOM_API_NAME); entity2.setCount(30D); entity2.setInterval(2L); entity2.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_MINUTE); entity2.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT); entity2.setBurst(0); entity2.setMaxQueueingTimeoutMs(0); GatewayParamFlowItemEntity itemEntity2 = new GatewayParamFlowItemEntity(); entity2.setParamItem(itemEntity2); itemEntity2.setParseStrategy(PARAM_PARSE_STRATEGY_CLIENT_IP); entities.add(entity2); CompletableFuture<List<GatewayFlowRuleEntity>> completableFuture = mock(CompletableFuture.class); given(completableFuture.get()).willReturn(entities); given(sentinelApiClient.fetchGatewayFlowRules(TEST_APP, TEST_IP, TEST_PORT)).willReturn(completableFuture); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(path); requestBuilder.param("app", TEST_APP); requestBuilder.param("ip", TEST_IP); requestBuilder.param("port", String.valueOf(TEST_PORT)); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).fetchGatewayFlowRules(TEST_APP, TEST_IP, TEST_PORT); Result<List<GatewayFlowRuleEntity>> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<List<GatewayFlowRuleEntity>>>(){}); assertTrue(result.isSuccess()); List<GatewayFlowRuleEntity> data = result.getData(); assertEquals(2, data.size()); assertEquals(entities, data); List<GatewayFlowRuleEntity> entitiesInMem = repository.findAllByApp(TEST_APP); assertEquals(2, entitiesInMem.size()); assertEquals(entities, entitiesInMem); }
GatewayFlowRuleController { @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity(); entity.setApp(app.trim()); String ip = reqVo.getIp(); if (StringUtil.isBlank(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } entity.setIp(ip.trim()); Integer port = reqVo.getPort(); if (port == null) { return Result.ofFail(-1, "port can't be null"); } entity.setPort(port); Integer resourceMode = reqVo.getResourceMode(); if (resourceMode == null) { return Result.ofFail(-1, "resourceMode can't be null"); } if (!Arrays.asList(RESOURCE_MODE_ROUTE_ID, RESOURCE_MODE_CUSTOM_API_NAME).contains(resourceMode)) { return Result.ofFail(-1, "invalid resourceMode: " + resourceMode); } entity.setResourceMode(resourceMode); String resource = reqVo.getResource(); if (StringUtil.isBlank(resource)) { return Result.ofFail(-1, "resource can't be null or empty"); } entity.setResource(resource.trim()); GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); if (paramItem != null) { GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); Integer parseStrategy = paramItem.getParseStrategy(); if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); } itemEntity.setParseStrategy(paramItem.getParseStrategy()); if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { String fieldName = paramItem.getFieldName(); if (StringUtil.isBlank(fieldName)) { return Result.ofFail(-1, "fieldName can't be null or empty"); } itemEntity.setFieldName(paramItem.getFieldName()); } String pattern = paramItem.getPattern(); if (StringUtil.isNotEmpty(pattern)) { itemEntity.setPattern(pattern); Integer matchStrategy = paramItem.getMatchStrategy(); if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } itemEntity.setMatchStrategy(matchStrategy); } } Integer grade = reqVo.getGrade(); if (grade == null) { return Result.ofFail(-1, "grade can't be null"); } if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { return Result.ofFail(-1, "invalid grade: " + grade); } entity.setGrade(grade); Double count = reqVo.getCount(); if (count == null) { return Result.ofFail(-1, "count can't be null"); } if (count < 0) { return Result.ofFail(-1, "count should be at lease zero"); } entity.setCount(count); Long interval = reqVo.getInterval(); if (interval == null) { return Result.ofFail(-1, "interval can't be null"); } if (interval <= 0) { return Result.ofFail(-1, "interval should be greater than zero"); } entity.setInterval(interval); Integer intervalUnit = reqVo.getIntervalUnit(); if (intervalUnit == null) { return Result.ofFail(-1, "intervalUnit can't be null"); } if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); } entity.setIntervalUnit(intervalUnit); Integer controlBehavior = reqVo.getControlBehavior(); if (controlBehavior == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); } entity.setControlBehavior(controlBehavior); if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { Integer burst = reqVo.getBurst(); if (burst == null) { return Result.ofFail(-1, "burst can't be null"); } if (burst < 0) { return Result.ofFail(-1, "invalid burst: " + burst); } entity.setBurst(burst); } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); if (maxQueueingTimeoutMs == null) { return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); } if (maxQueueingTimeoutMs < 0) { return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); } entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); } Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("add gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(app, ip, port)) { logger.warn("publish gateway flow rules fail after add"); } return Result.ofSuccess(entity); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteFlowRule(Long id); }
@Test public void testAddFlowRule() throws Exception { String path = "/gateway/flow/new.json"; AddFlowRuleReqVo reqVo = new AddFlowRuleReqVo(); reqVo.setApp(TEST_APP); reqVo.setIp(TEST_IP); reqVo.setPort(TEST_PORT); reqVo.setResourceMode(RESOURCE_MODE_ROUTE_ID); reqVo.setResource("httpbin_route"); reqVo.setGrade(FLOW_GRADE_QPS); reqVo.setCount(5D); reqVo.setInterval(30L); reqVo.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_SECOND); reqVo.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT); reqVo.setBurst(0); reqVo.setMaxQueueingTimeoutMs(0); given(sentinelApiClient.modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path); requestBuilder.content(JSON.toJSONString(reqVo)).contentType(MediaType.APPLICATION_JSON); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any()); Result<GatewayFlowRuleEntity> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<GatewayFlowRuleEntity>>() {}); assertTrue(result.isSuccess()); GatewayFlowRuleEntity entity = result.getData(); assertNotNull(entity); assertEquals(TEST_APP, entity.getApp()); assertEquals(TEST_IP, entity.getIp()); assertEquals(TEST_PORT, entity.getPort()); assertEquals(RESOURCE_MODE_ROUTE_ID, entity.getResourceMode().intValue()); assertEquals("httpbin_route", entity.getResource()); assertNotNull(entity.getId()); assertNotNull(entity.getGmtCreate()); assertNotNull(entity.getGmtModified()); List<GatewayFlowRuleEntity> entitiesInMem = repository.findAllByApp(TEST_APP); assertEquals(1, entitiesInMem.size()); assertEquals(entity, entitiesInMem.get(0)); }
GatewayFlowRuleController { @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } Long id = reqVo.getId(); if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "gateway flow rule does not exist, id=" + id); } GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); if (paramItem != null) { GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); Integer parseStrategy = paramItem.getParseStrategy(); if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); } itemEntity.setParseStrategy(paramItem.getParseStrategy()); if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { String fieldName = paramItem.getFieldName(); if (StringUtil.isBlank(fieldName)) { return Result.ofFail(-1, "fieldName can't be null or empty"); } itemEntity.setFieldName(paramItem.getFieldName()); } String pattern = paramItem.getPattern(); if (StringUtil.isNotEmpty(pattern)) { itemEntity.setPattern(pattern); Integer matchStrategy = paramItem.getMatchStrategy(); if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } itemEntity.setMatchStrategy(matchStrategy); } } else { entity.setParamItem(null); } Integer grade = reqVo.getGrade(); if (grade == null) { return Result.ofFail(-1, "grade can't be null"); } if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { return Result.ofFail(-1, "invalid grade: " + grade); } entity.setGrade(grade); Double count = reqVo.getCount(); if (count == null) { return Result.ofFail(-1, "count can't be null"); } if (count < 0) { return Result.ofFail(-1, "count should be at lease zero"); } entity.setCount(count); Long interval = reqVo.getInterval(); if (interval == null) { return Result.ofFail(-1, "interval can't be null"); } if (interval <= 0) { return Result.ofFail(-1, "interval should be greater than zero"); } entity.setInterval(interval); Integer intervalUnit = reqVo.getIntervalUnit(); if (intervalUnit == null) { return Result.ofFail(-1, "intervalUnit can't be null"); } if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); } entity.setIntervalUnit(intervalUnit); Integer controlBehavior = reqVo.getControlBehavior(); if (controlBehavior == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); } entity.setControlBehavior(controlBehavior); if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { Integer burst = reqVo.getBurst(); if (burst == null) { return Result.ofFail(-1, "burst can't be null"); } if (burst < 0) { return Result.ofFail(-1, "invalid burst: " + burst); } entity.setBurst(burst); } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); if (maxQueueingTimeoutMs == null) { return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); } if (maxQueueingTimeoutMs < 0) { return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); } entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); } Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("update gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(app, entity.getIp(), entity.getPort())) { logger.warn("publish gateway flow rules fail after update"); } return Result.ofSuccess(entity); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteFlowRule(Long id); }
@Test public void testUpdateFlowRule() throws Exception { String path = "/gateway/flow/save.json"; GatewayFlowRuleEntity addEntity = new GatewayFlowRuleEntity(); addEntity.setId(1L); addEntity.setApp(TEST_APP); addEntity.setIp(TEST_IP); addEntity.setPort(TEST_PORT); addEntity.setResource("httpbin_route"); addEntity.setResourceMode(RESOURCE_MODE_ROUTE_ID); addEntity.setGrade(FLOW_GRADE_QPS); addEntity.setCount(5D); addEntity.setInterval(30L); addEntity.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_SECOND); addEntity.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT); addEntity.setBurst(0); addEntity.setMaxQueueingTimeoutMs(0); Date date = new Date(); date = DateUtils.addSeconds(date, -1); addEntity.setGmtCreate(date); addEntity.setGmtModified(date); GatewayParamFlowItemEntity addItemEntity = new GatewayParamFlowItemEntity(); addEntity.setParamItem(addItemEntity); addItemEntity.setParseStrategy(PARAM_PARSE_STRATEGY_CLIENT_IP); repository.save(addEntity); UpdateFlowRuleReqVo reqVo = new UpdateFlowRuleReqVo(); reqVo.setId(addEntity.getId()); reqVo.setApp(TEST_APP); reqVo.setGrade(FLOW_GRADE_QPS); reqVo.setCount(6D); reqVo.setInterval(2L); reqVo.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_MINUTE); reqVo.setControlBehavior(CONTROL_BEHAVIOR_RATE_LIMITER); reqVo.setMaxQueueingTimeoutMs(500); GatewayParamFlowItemVo itemVo = new GatewayParamFlowItemVo(); reqVo.setParamItem(itemVo); itemVo.setParseStrategy(PARAM_PARSE_STRATEGY_URL_PARAM); itemVo.setFieldName("pa"); given(sentinelApiClient.modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path); requestBuilder.content(JSON.toJSONString(reqVo)).contentType(MediaType.APPLICATION_JSON); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any()); Result<GatewayFlowRuleEntity> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<GatewayFlowRuleEntity>>() { }); assertTrue(result.isSuccess()); GatewayFlowRuleEntity entity = result.getData(); assertNotNull(entity); assertEquals(RESOURCE_MODE_ROUTE_ID, entity.getResourceMode().intValue()); assertEquals("httpbin_route", entity.getResource()); assertEquals(6D, entity.getCount().doubleValue(), 0); assertEquals(2L, entity.getInterval().longValue()); assertEquals(GatewayFlowRuleEntity.INTERVAL_UNIT_MINUTE, entity.getIntervalUnit().intValue()); assertEquals(CONTROL_BEHAVIOR_RATE_LIMITER, entity.getControlBehavior().intValue()); assertEquals(0, entity.getBurst().intValue()); assertEquals(500, entity.getMaxQueueingTimeoutMs().intValue()); assertEquals(date, entity.getGmtCreate()); assertNotNull(entity.getGmtModified()); assertNotEquals(entity.getGmtCreate(), entity.getGmtModified()); GatewayParamFlowItemEntity itemEntity = entity.getParamItem(); assertEquals(PARAM_PARSE_STRATEGY_URL_PARAM, itemEntity.getParseStrategy().intValue()); assertEquals("pa", itemEntity.getFieldName()); }
GatewayFlowRuleController { @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteFlowRule(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Throwable throwable) { logger.error("delete gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { logger.warn("publish gateway flow rules fail after delete"); } return Result.ofSuccess(id); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteFlowRule(Long id); }
@Test public void testDeleteFlowRule() throws Exception { String path = "/gateway/flow/delete.json"; GatewayFlowRuleEntity addEntity = new GatewayFlowRuleEntity(); addEntity.setId(1L); addEntity.setApp(TEST_APP); addEntity.setIp(TEST_IP); addEntity.setPort(TEST_PORT); addEntity.setResource("httpbin_route"); addEntity.setResourceMode(RESOURCE_MODE_ROUTE_ID); addEntity.setGrade(FLOW_GRADE_QPS); addEntity.setCount(5D); addEntity.setInterval(30L); addEntity.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_SECOND); addEntity.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT); addEntity.setBurst(0); addEntity.setMaxQueueingTimeoutMs(0); Date date = new Date(); date = DateUtils.addSeconds(date, -1); addEntity.setGmtCreate(date); addEntity.setGmtModified(date); GatewayParamFlowItemEntity addItemEntity = new GatewayParamFlowItemEntity(); addEntity.setParamItem(addItemEntity); addItemEntity.setParseStrategy(PARAM_PARSE_STRATEGY_CLIENT_IP); repository.save(addEntity); given(sentinelApiClient.modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path); requestBuilder.param("id", String.valueOf(addEntity.getId())); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any()); Result<Long> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<Long>>() {}); assertTrue(result.isSuccess()); assertEquals(addEntity.getId(), result.getData()); List<GatewayFlowRuleEntity> entitiesInMem = repository.findAllByApp(TEST_APP); assertEquals(0, entitiesInMem.size()); }
DashboardConfig { protected static String getConfigStr(String name) { if (cacheMap.containsKey(name)) { return (String) cacheMap.get(name); } String val = getConfig(name); if (StringUtils.isBlank(val)) { return null; } cacheMap.put(name, val); return val; } static String getAuthUsername(); static String getAuthPassword(); static int getHideAppNoMachineMillis(); static int getRemoveAppNoMachineMillis(); static int getAutoRemoveMachineMillis(); static int getUnhealthyMachineMillis(); static void clearCache(); static final int DEFAULT_MACHINE_HEALTHY_TIMEOUT_MS; static final String CONFIG_AUTH_USERNAME; static final String CONFIG_AUTH_PASSWORD; static final String CONFIG_HIDE_APP_NO_MACHINE_MILLIS; static final String CONFIG_REMOVE_APP_NO_MACHINE_MILLIS; static final String CONFIG_UNHEALTHY_MACHINE_MILLIS; static final String CONFIG_AUTO_REMOVE_MACHINE_MILLIS; }
@Test public void testGetConfigStr() { DashboardConfig.clearCache(); assertEquals(null, DashboardConfig.getConfigStr("a")); System.setProperty("a", "111"); assertEquals("111", DashboardConfig.getConfigStr("a")); environmentVariables.set("a", "222"); assertEquals("111", DashboardConfig.getConfigStr("a")); DashboardConfig.clearCache(); assertEquals("222", DashboardConfig.getConfigStr("a")); }
ImageConversion { @Benchmark public BufferedImage RGB_to_3ByteBGR() { DataBuffer buffer = new DataBufferByte(RGB_SRC, RGB_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 3, WIDTH * 3, new int[]{0, 1, 2}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_3BYTE_BGR); Raster raster = Raster.createRaster(sampleModel, buffer, null); image.setData(raster); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }
@Test public void RGB_to_3ByteBGR() { new ImageConversion().RGB_to_3ByteBGR(); }
ImageConversion { @Benchmark public BufferedImage RGBA_to_4ByteABGR() { DataBuffer buffer = new DataBufferByte(RGBA_SRC, RGBA_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 4, WIDTH * 4, new int[]{0, 1, 2, 3}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR); Raster raster = Raster.createRaster(sampleModel, buffer, null); image.setData(raster); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }
@Test public void RGBA_to_4ByteABGR() { new ImageConversion().RGBA_to_4ByteABGR(); }
ImageConversion { @Benchmark public BufferedImage ABGR_to_4ByteABGR_arraycopy() { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR); DataBufferByte buffer = (DataBufferByte)(image.getRaster().getDataBuffer()); byte[] data = buffer.getData(); System.arraycopy(ABGR_SRC, 0, data, 0, ABGR_SRC.length); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }
@Test public void ABGR_to_4ByteABGR() { new ImageConversion().ABGR_to_4ByteABGR_arraycopy(); }
ImageConversion { @Benchmark public BufferedImage ABGR_to_4ByteABGR_instantiate() { ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel colorModel; WritableRaster raster; int[] nBits = {8, 8, 8, 8}; int[] bOffs = {3, 2, 1, 0}; colorModel = new ComponentColorModel(cs, nBits, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); DataBufferByte buffer = new DataBufferByte(ABGR_SRC, ABGR_SRC.length); raster = Raster.createInterleavedRaster(buffer, WIDTH, HEIGHT, WIDTH*4, 4, bOffs, null); BufferedImage image = new BufferedImage(colorModel, raster, false, null); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }
@Test public void ABGR_to_4ByteABGR_instantiate() { new ImageConversion().ABGR_to_4ByteABGR_instantiate(); }
TextDisplay { public void displayText(String text) throws IOException { BufferedImage image = new BufferedImage(8, 8, BufferedImage.TYPE_USHORT_565_RGB); Graphics2D graphics = image.createGraphics(); if (big) { text = text.toUpperCase(); } Font sansSerif = new Font("SansSerif", Font.PLAIN, big ? 10 : 8); graphics.setFont(sansSerif); int i = graphics.getFontMetrics().stringWidth(text) - 8; if (i <= 0) { i = 1; } long durationInMillis = duration.toMillis(); for (int j = 0; j <= i; j++) { long start = System.currentTimeMillis(); graphics.setColor(background); graphics.setPaint(background); graphics.fillRect(0, 0, 8, 8); graphics.setColor(foreground); graphics.setPaint(foreground); graphics.drawString(text, -j, big ? 8 : 7); senseHat.fadeTo(image, duration.dividedBy(2)); long timeToSleep = durationInMillis - (System.currentTimeMillis() - start); if(timeToSleep > 0) { try { Thread.sleep(timeToSleep); } catch (InterruptedException e) { log.error(e.getLocalizedMessage(), e); } } } graphics.dispose(); } void displayText(String text); void setForeground(SenseHatColor foreground); void setBackground(SenseHatColor background); }
@Test public void displayText() throws Exception { new TextDisplay(senseHat).displayText("Hallo Welt!"); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testInt_red() { assertThat(SenseHatColor.fromRGB(0xFF, 0x00, 0x00).getSenseHatColor()).isEqualTo(0xF800); } @Test public void testDouble_red() { assertThat(SenseHatColor.fromRGB(1f ,0f, 0f).getSenseHatColor()).isEqualTo(0xF800); } @Test public void testInt_blue() { assertThat(SenseHatColor.fromRGB(0x00, 0x00, 0xFF).getSenseHatColor()).isEqualTo(0x001F); } @Test public void testDouble_blue() { assertThat(SenseHatColor.fromRGB(0f ,0f, 1f).getSenseHatColor()).isEqualTo(0x001F); } @Test public void testInt_white() { assertThat(SenseHatColor.fromRGB(0xFF, 0xFF, 0xFF).getSenseHatColor()).isEqualTo(0xFFFF); } @Test public void testDouble_white() { assertThat(SenseHatColor.fromRGB(1f ,1f, 1f).getSenseHatColor()).isEqualTo(0xFFFF); } @Test public void testInt_black() { assertThat(SenseHatColor.fromRGB(0x00, 0x00, 0x00).getSenseHatColor()).isEqualTo(0x0000); } @Test public void testDouble_black() { assertThat(SenseHatColor.fromRGB(0f ,0f, 0f).getSenseHatColor()).isEqualTo(0x0000); }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testString_red() { assertThat(SenseHatColor.fromString("red").getSenseHatColor()).isEqualTo(0xF800); assertThat(SenseHatColor.fromString("F00").getSenseHatColor()).isEqualTo(0xF800); assertThat(SenseHatColor.fromString("#F00").getSenseHatColor()).isEqualTo(0xF800); assertThat(SenseHatColor.fromString("FF0000").getSenseHatColor()).isEqualTo(0xF800); assertThat(SenseHatColor.fromString("#FF0000").getSenseHatColor()).isEqualTo(0xF800); } @Test public void testString_blue() { assertThat(SenseHatColor.fromString("blue").getSenseHatColor()).isEqualTo(0x001F); assertThat(SenseHatColor.fromString("00F").getSenseHatColor()).isEqualTo(0x001F); assertThat(SenseHatColor.fromString("#00F").getSenseHatColor()).isEqualTo(0x001F); assertThat(SenseHatColor.fromString("0000FF").getSenseHatColor()).isEqualTo(0x001F); assertThat(SenseHatColor.fromString("#0000FF").getSenseHatColor()).isEqualTo(0x001F); } @Test public void testString_white() { assertThat(SenseHatColor.fromString("white").getSenseHatColor()).isEqualTo(0xFFFF); assertThat(SenseHatColor.fromString("FFF").getSenseHatColor()).isEqualTo(0xFFFF); assertThat(SenseHatColor.fromString("fff").getSenseHatColor()).isEqualTo(0xFFFF); assertThat(SenseHatColor.fromString("#FFF").getSenseHatColor()).isEqualTo(0xFFFF); assertThat(SenseHatColor.fromString("#FFFFFF").getSenseHatColor()).isEqualTo(0xFFFF); } @Test public void testString_black() { assertThat(SenseHatColor.fromString("black").getSenseHatColor()).isEqualTo(0x0000); assertThat(SenseHatColor.fromString("000").getSenseHatColor()).isEqualTo(0x0000); assertThat(SenseHatColor.fromString("#000").getSenseHatColor()).isEqualTo(0x0000); assertThat(SenseHatColor.fromString("000000").getSenseHatColor()).isEqualTo(0x0000); assertThat(SenseHatColor.fromString("#000000").getSenseHatColor()).isEqualTo(0x0000); }
SenseHatColor { public SenseHatColor plus(SenseHatColor other) { int newRed = getRedRaw() + other.getRedRaw(); int newGreen = getGreenRaw() + other.getGreenRaw(); int newBlue = getBlueRaw() + other.getBlueRaw(); if (newRed > 31) { newRed = 31; } if (newGreen > 63) { newGreen = 63; } if (newBlue > 31) { newBlue = 31; } return new SenseHatColor(newRed, newGreen, newBlue); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testPlus() { SenseHatColor white = SenseHatColor.fromString("FFF"); SenseHatColor black = SenseHatColor.fromString("000"); assertThat(white.plus(black)).isEqualTo(white); assertThat(white.plus(white)).isEqualTo(white); assertThat(black.plus(black)).isEqualTo(black); assertThat(SenseHatColor.fromString("F00").plus(SenseHatColor.fromString("00F"))) .isEqualTo(SenseHatColor.fromString("F0F")); }
SenseHatColor { public SenseHatColor mix(SenseHatColor other) { if (this.equals(other)) { return this; } float newRed = (getRed() + other.getRed()) / 2f; float newGreen = (getGreen() + other.getGreen()) / 2f; float newBlue = (getBlue() + other.getBlue()) / 2f; return fromRGB(newRed, newGreen, newBlue); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testMix() { SenseHatColor white = SenseHatColor.fromString("FFF"); SenseHatColor black = SenseHatColor.fromString("000"); assertThat(white.mix(black)).isEqualTo(white.divide(2)); assertThat(white.mix(white)).isEqualTo(white); assertThat(black.mix(black)).isEqualTo(black); assertThat(SenseHatColor.fromString("F00").mix(SenseHatColor.fromString("00F"))) .isEqualTo(SenseHatColor.fromRGB(0.5f, 0f, 0.5f)); }
SenseHatColor { public float getRed() { return getRedRaw() / 31f; } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testGetRed() throws Exception { assertThat(new SenseHatColor(0xFFFF).getRed()).isEqualTo(1); assertThat(new SenseHatColor(0xF800).getRed()).isEqualTo(1); assertThat(new SenseHatColor(0x0000).getRed()).isEqualTo(0); }
SenseHatColor { public float getGreen() { return getGreenRaw() / 63f; } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void getGreen() throws Exception { assertThat(new SenseHatColor(0xFFFF).getGreen()).isEqualTo(1); assertThat(new SenseHatColor(0x07E0).getGreen()).isEqualTo(1); assertThat(new SenseHatColor(0x0000).getGreen()).isEqualTo(0); }
SenseHatColor { public float getBlue() { return getBlueRaw() / 31f; } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void getBlue() throws Exception { assertThat(new SenseHatColor(0xFFFF).getBlue()).isEqualTo(1); assertThat(new SenseHatColor(0x003F).getBlue()).isEqualTo(1); assertThat(new SenseHatColor(0x0000).getBlue()).isEqualTo(0); }
ConditionRouter implements Router, Comparable<Router> { public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException { if (invokers == null || invokers.size() == 0) { return invokers; } try { if (!matchWhen(url)) { return invokers; } List<Invoker<T>> result = new ArrayList<Invoker<T>>(); if (thenCondition == null) { logger.warn("The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey()); return result; } for (Invoker<T> invoker : invokers) { if (matchThen(invoker.getUrl(), url)) { result.add(invoker); } } if (result.size() > 0) { return result; } else if (force) { logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(Constants.RULE_KEY)); return result; } } catch (Throwable t) { logger.error("Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: " + t.getMessage(), t); } return invokers; } ConditionRouter(URL url); List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation); URL getUrl(); int compareTo(Router o); boolean matchWhen(URL url); boolean matchThen(URL url, URL param); }
@Test public void testRoute_ReturnFalse() { Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => false")); List<Invoker<String>> invokers = new ArrayList<Invoker<String>>(); invokers.add(new MockInvoker<String>()); invokers.add(new MockInvoker<String>()); invokers.add(new MockInvoker<String>()); List<Invoker<String>> fileredInvokers = router.route(invokers, URL.valueOf("consumer: Assert.assertEquals(0, fileredInvokers.size()); } @Test public void testRoute_ReturnEmpty() { Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => ")); List<Invoker<String>> invokers = new ArrayList<Invoker<String>>(); invokers.add(new MockInvoker<String>()); invokers.add(new MockInvoker<String>()); invokers.add(new MockInvoker<String>()); List<Invoker<String>> fileredInvokers = router.route(invokers, URL.valueOf("consumer: Assert.assertEquals(0, fileredInvokers.size()); } @Test public void testRoute_ReturnAll() { Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => " + " host = " + NetUtils.getLocalHost())); List<Invoker<String>> invokers = new ArrayList<Invoker<String>>(); invokers.add(new MockInvoker<String>()); invokers.add(new MockInvoker<String>()); invokers.add(new MockInvoker<String>()); List<Invoker<String>> fileredInvokers = router.route(invokers, URL.valueOf("consumer: Assert.assertEquals(invokers, fileredInvokers); } @Test public void testRoute_HostFilter() { Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => " + " host = " + NetUtils.getLocalHost())); List<Invoker<String>> invokers = new ArrayList<Invoker<String>>(); Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo: Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo: Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo: invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); List<Invoker<String>> fileredInvokers = router.route(invokers, URL.valueOf("consumer: Assert.assertEquals(2, fileredInvokers.size()); Assert.assertEquals(invoker2, fileredInvokers.get(0)); Assert.assertEquals(invoker3, fileredInvokers.get(1)); } @Test public void testRoute_Empty_HostFilter() { Router router = new ConditionRouterFactory().getRouter(getRouteUrl(" => " + " host = " + NetUtils.getLocalHost())); List<Invoker<String>> invokers = new ArrayList<Invoker<String>>(); Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo: Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo: Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo: invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); List<Invoker<String>> fileredInvokers = router.route(invokers, URL.valueOf("consumer: Assert.assertEquals(2, fileredInvokers.size()); Assert.assertEquals(invoker2, fileredInvokers.get(0)); Assert.assertEquals(invoker3, fileredInvokers.get(1)); } @Test public void testRoute_False_HostFilter() { Router router = new ConditionRouterFactory().getRouter(getRouteUrl("true => " + " host = " + NetUtils.getLocalHost())); List<Invoker<String>> invokers = new ArrayList<Invoker<String>>(); Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo: Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo: Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo: invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); List<Invoker<String>> fileredInvokers = router.route(invokers, URL.valueOf("consumer: Assert.assertEquals(2, fileredInvokers.size()); Assert.assertEquals(invoker2, fileredInvokers.get(0)); Assert.assertEquals(invoker3, fileredInvokers.get(1)); } @Test public void testRoute_Placeholder() { Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => " + " host = $host")); List<Invoker<String>> invokers = new ArrayList<Invoker<String>>(); Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo: Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo: Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo: invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); List<Invoker<String>> fileredInvokers = router.route(invokers, URL.valueOf("consumer: Assert.assertEquals(2, fileredInvokers.size()); Assert.assertEquals(invoker2, fileredInvokers.get(0)); Assert.assertEquals(invoker3, fileredInvokers.get(1)); } @Test public void testRoute_NoForce() { Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => " + " host = 1.2.3.4")); List<Invoker<String>> invokers = new ArrayList<Invoker<String>>(); Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo: Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo: Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo: invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); List<Invoker<String>> fileredInvokers = router.route(invokers, URL.valueOf("consumer: Assert.assertEquals(invokers, fileredInvokers); } @Test public void testRoute_Force() { Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => " + " host = 1.2.3.4").addParameter(Constants.FORCE_KEY, String.valueOf(true))); List<Invoker<String>> invokers = new ArrayList<Invoker<String>>(); Invoker<String> invoker1 = new MockInvoker<String>(URL.valueOf("dubbo: Invoker<String> invoker2 = new MockInvoker<String>(URL.valueOf("dubbo: Invoker<String> invoker3 = new MockInvoker<String>(URL.valueOf("dubbo: invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); List<Invoker<String>> fileredInvokers = router.route(invokers, URL.valueOf("consumer: Assert.assertEquals(0, fileredInvokers.size()); }
FailbackRegistry extends AbstractRegistry { @Override public void register(URL url) { super.register(url); failedRegistered.remove(url); failedUnregistered.remove(url); try { doRegister(url); } catch (Exception e) { Throwable t = e; boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true) && !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(), t); } failedRegistered.add(url); } } FailbackRegistry(URL url); Future<?> getRetryFuture(); Set<URL> getFailedRegistered(); Set<URL> getFailedUnregistered(); Map<URL, Set<NotifyListener>> getFailedSubscribed(); Map<URL, Set<NotifyListener>> getFailedUnsubscribed(); Map<URL, Map<NotifyListener, List<URL>>> getFailedNotified(); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); }
@Test public void testDoRetry_subscribe() throws Exception { final CountDownLatch latch = new CountDownLatch(1); registry = new MockRegistry(registryUrl, latch); registry.setBad(true); registry.register(serviceUrl); registry.setBad(false); for (int i = 0; i < trytimes; i++) { System.out.println("failback registry retry ,times:" + i); if (latch.getCount() == 0) break; Thread.sleep(sleeptime); } assertEquals(0, latch.getCount()); }
FailbackRegistry extends AbstractRegistry { @Override public void subscribe(URL url, NotifyListener listener) { super.subscribe(url, listener); removeFailedSubscribed(url, listener); try { doSubscribe(url, listener); } catch (Exception e) { Throwable t = e; List<URL> urls = getCacheUrls(url); if (urls != null && urls.size() > 0) { notify(url, listener, urls); logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); } else { boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); } } addFailedSubscribed(url, listener); } } FailbackRegistry(URL url); Future<?> getRetryFuture(); Set<URL> getFailedRegistered(); Set<URL> getFailedUnregistered(); Map<URL, Set<NotifyListener>> getFailedSubscribed(); Map<URL, Set<NotifyListener>> getFailedUnsubscribed(); Map<URL, Map<NotifyListener, List<URL>>> getFailedNotified(); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); }
@Test public void testDoRetry_register() throws Exception { final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); final CountDownLatch latch = new CountDownLatch(1); NotifyListener listner = new NotifyListener() { public void notify(List<URL> urls) { notified.set(Boolean.TRUE); } }; registry = new MockRegistry(registryUrl, latch); registry.setBad(true); registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner); assertEquals(false, notified.get()); assertEquals(1, latch.getCount()); registry.setBad(false); for (int i = 0; i < trytimes; i++) { System.out.println("failback registry retry ,times:" + i); if (latch.getCount() == 0) break; Thread.sleep(sleeptime); } assertEquals(0, latch.getCount()); assertEquals(true, notified.get()); } @Test public void testDoRetry_nofify() throws Exception { final AtomicInteger count = new AtomicInteger(0); NotifyListener listner = new NotifyListener() { public void notify(List<URL> urls) { count.incrementAndGet(); if (count.get() == 1l) { throw new RuntimeException("test exception please ignore"); } } }; registry = new MockRegistry(registryUrl, new CountDownLatch(0)); registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner); assertEquals(1, count.get()); for (int i = 0; i < trytimes; i++) { System.out.println("failback notify retry ,times:" + i); if (count.get() == 2) break; Thread.sleep(sleeptime); } assertEquals(2, count.get()); }
Wrapper { public static Wrapper getWrapper(Class<?> c) { while (ClassGenerator.isDynamicClass(c)) c = c.getSuperclass(); if (c == Object.class) return OBJECT_WRAPPER; Wrapper ret = WRAPPER_MAP.get(c); if (ret == null) { ret = makeWrapper(c); WRAPPER_MAP.put(c, ret); } return ret; } static Wrapper getWrapper(Class<?> c); abstract String[] getPropertyNames(); abstract Class<?> getPropertyType(String pn); abstract boolean hasProperty(String name); abstract Object getPropertyValue(Object instance, String pn); abstract void setPropertyValue(Object instance, String pn, Object pv); Object[] getPropertyValues(Object instance, String[] pns); void setPropertyValues(Object instance, String[] pns, Object[] pvs); abstract String[] getMethodNames(); abstract String[] getDeclaredMethodNames(); boolean hasMethod(String name); abstract Object invokeMethod(Object instance, String mn, Class<?>[] types, Object[] args); }
@Test public void test_makeEmptyClass() throws Exception { Wrapper.getWrapper(EmptyServiceImpl.class); }
URL implements Serializable { public static URL valueOf(String url) { if (url == null || (url = url.trim()).length() == 0) { throw new IllegalArgumentException("url == null"); } String protocol = null; String username = null; String password = null; String host = null; int port = 0; String path = null; Map<String, String> parameters = null; int i = url.indexOf("?"); if (i >= 0) { String[] parts = url.substring(i + 1).split("\\&"); parameters = new HashMap<String, String>(); for (String part : parts) { part = part.trim(); if (part.length() > 0) { int j = part.indexOf('='); if (j >= 0) { parameters.put(part.substring(0, j), part.substring(j + 1)); } else { parameters.put(part, part); } } } url = url.substring(0, i); } i = url.indexOf(": if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 3); } else { i = url.indexOf(":/"); if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 1); } } i = url.indexOf("/"); if (i >= 0) { path = url.substring(i + 1); url = url.substring(0, i); } i = url.indexOf("@"); if (i >= 0) { username = url.substring(0, i); int j = username.indexOf(":"); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } url = url.substring(i + 1); } i = url.indexOf(":"); if (i >= 0 && i < url.length() - 1) { port = Integer.parseInt(url.substring(i + 1)); url = url.substring(0, i); } if (url.length() > 0) host = url; return new URL(protocol, username, password, host, port, path, parameters); } protected URL(); URL(String protocol, String host, int port); URL(String protocol, String host, int port, String[] pairs); URL(String protocol, String host, int port, Map<String, String> parameters); URL(String protocol, String host, int port, String path); URL(String protocol, String host, int port, String path, String... pairs); URL(String protocol, String host, int port, String path, Map<String, String> parameters); URL(String protocol, String username, String password, String host, int port, String path); URL(String protocol, String username, String password, String host, int port, String path, String... pairs); URL(String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters); static URL valueOf(String url); String getProtocol(); String getUsername(); String getPassword(); String getAuthority(); String getHost(); String getIp(); int getPort(); int getPort(int defaultPort); String getAddress(); String getBackupAddress(); String getBackupAddress(int defaultPort); List<URL> getBackupUrls(); String getPath(); String getAbsolutePath(); URL setProtocol(String protocol); URL setUsername(String username); URL setPassword(String password); URL setAddress(String address); URL setHost(String host); URL setPort(int port); URL setPath(String path); Map<String, String> getParameters(); String getParameterAndDecoded(String key); String getParameterAndDecoded(String key, String defaultValue); String getParameter(String key); String getParameter(String key, String defaultValue); String[] getParameter(String key, String[] defaultValue); URL getUrlParameter(String key); double getParameter(String key, double defaultValue); float getParameter(String key, float defaultValue); long getParameter(String key, long defaultValue); int getParameter(String key, int defaultValue); short getParameter(String key, short defaultValue); byte getParameter(String key, byte defaultValue); float getPositiveParameter(String key, float defaultValue); double getPositiveParameter(String key, double defaultValue); long getPositiveParameter(String key, long defaultValue); int getPositiveParameter(String key, int defaultValue); short getPositiveParameter(String key, short defaultValue); byte getPositiveParameter(String key, byte defaultValue); char getParameter(String key, char defaultValue); boolean getParameter(String key, boolean defaultValue); boolean hasParameter(String key); String getMethodParameterAndDecoded(String method, String key); String getMethodParameterAndDecoded(String method, String key, String defaultValue); String getMethodParameter(String method, String key); String getMethodParameter(String method, String key, String defaultValue); double getMethodParameter(String method, String key, double defaultValue); float getMethodParameter(String method, String key, float defaultValue); long getMethodParameter(String method, String key, long defaultValue); int getMethodParameter(String method, String key, int defaultValue); short getMethodParameter(String method, String key, short defaultValue); byte getMethodParameter(String method, String key, byte defaultValue); double getMethodPositiveParameter(String method, String key, double defaultValue); float getMethodPositiveParameter(String method, String key, float defaultValue); long getMethodPositiveParameter(String method, String key, long defaultValue); int getMethodPositiveParameter(String method, String key, int defaultValue); short getMethodPositiveParameter(String method, String key, short defaultValue); byte getMethodPositiveParameter(String method, String key, byte defaultValue); char getMethodParameter(String method, String key, char defaultValue); boolean getMethodParameter(String method, String key, boolean defaultValue); boolean hasMethodParameter(String method, String key); boolean isLocalHost(); boolean isAnyHost(); URL addParameterAndEncoded(String key, String value); URL addParameter(String key, boolean value); URL addParameter(String key, char value); URL addParameter(String key, byte value); URL addParameter(String key, short value); URL addParameter(String key, int value); URL addParameter(String key, long value); URL addParameter(String key, float value); URL addParameter(String key, double value); URL addParameter(String key, Enum<?> value); URL addParameter(String key, Number value); URL addParameter(String key, CharSequence value); URL addParameter(String key, String value); URL addParameterIfAbsent(String key, String value); URL addParameters(Map<String, String> parameters); URL addParametersIfAbsent(Map<String, String> parameters); URL addParameters(String... pairs); URL addParameterString(String query); URL removeParameter(String key); URL removeParameters(Collection<String> keys); URL removeParameters(String... keys); URL clearParameters(); String getRawParameter(String key); Map<String, String> toMap(); String toString(); String toString(String... parameters); String toIdentityString(); String toIdentityString(String... parameters); String toFullString(); String toFullString(String... parameters); String toParameterString(); String toParameterString(String... parameters); java.net.URL toJavaURL(); InetSocketAddress toInetSocketAddress(); String getServiceKey(); String toServiceString(); @Deprecated String getServiceName(); String getServiceInterface(); URL setServiceInterface(String service); @Deprecated int getIntParameter(String key); @Deprecated int getIntParameter(String key, int defaultValue); @Deprecated int getPositiveIntParameter(String key, int defaultValue); @Deprecated boolean getBooleanParameter(String key); @Deprecated boolean getBooleanParameter(String key, boolean defaultValue); @Deprecated int getMethodIntParameter(String method, String key); @Deprecated int getMethodIntParameter(String method, String key, int defaultValue); @Deprecated int getMethodPositiveIntParameter(String method, String key, int defaultValue); @Deprecated boolean getMethodBooleanParameter(String method, String key); @Deprecated boolean getMethodBooleanParameter(String method, String key, boolean defaultValue); static String encode(String value); static String decode(String value); @Override int hashCode(); @Override boolean equals(Object obj); }
@Test public void test_valueOf_Exception_noProtocol() throws Exception { try { URL.valueOf(": fail(); } catch (IllegalStateException expected) { assertEquals("url missing protocol: \": } } @Test public void test_equals() throws Exception { URL url1 = URL.valueOf("dubbo: Map<String, String> params = new HashMap<String, String>(); params.put("version", "1.0.0"); params.put("application", "morgan"); URL url2 = new URL("dubbo", "admin", "hello1234", "10.20.130.230", 20880, "context/path", params); assertEquals(url1, url2); }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
@Test public void testMergeValues() { List<String> merged = ConfigUtils.mergeValues(Serialization.class, "aaa,bbb,default.cunstom", toArray("dubbo", "default.hessian2", "json")); Assert.assertEquals(toArray("dubbo", "json", "aaa", "bbb", "default.cunstom"), merged); } @Test public void testMergeValues_addDefault() { List<String> merged = ConfigUtils.mergeValues(Serialization.class, "aaa,bbb,default,zzz", toArray("dubbo", "default.hessian2", "json")); Assert.assertEquals(toArray("aaa", "bbb", "dubbo", "json", "zzz"), merged); } @Test public void testMergeValuesDeleteDefault() { List<String> merged = ConfigUtils.mergeValues(Serialization.class, "-default", toArray("dubbo", "default.hessian2", "json")); Assert.assertEquals(toArray(), merged); } @Test public void testMergeValuesDeleteDefault_2() { List<String> merged = ConfigUtils.mergeValues(Serialization.class, "-default,aaa", toArray("dubbo", "default.hessian2", "json")); Assert.assertEquals(toArray("aaa"), merged); } @Test public void testMergeValuesDelete() { List<String> merged = ConfigUtils.mergeValues(Serialization.class, "-dubbo,aaa", toArray("dubbo", "default.hessian2", "json")); Assert.assertEquals(toArray("json", "aaa"), merged); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
@Test public void test_loadProperties_noFile() throws Exception { Properties p = ConfigUtils.loadProperties("notExisted", true); Properties expected = new Properties(); Assert.assertEquals(expected, p); p = ConfigUtils.loadProperties("notExisted", false); Assert.assertEquals(expected, p); } @Test public void test_loadProperties_oneFile() throws Exception { Properties p = ConfigUtils.loadProperties("properties.load", false); Properties expected = new Properties(); expected.put("a", "12"); expected.put("b", "34"); expected.put("c", "56"); Assert.assertEquals(expected, p); } @Test public void test_loadProperties_oneFile_allowMulti() throws Exception { Properties p = ConfigUtils.loadProperties("properties.load", true); Properties expected = new Properties(); expected.put("a", "12"); expected.put("b", "34"); expected.put("c", "56"); Assert.assertEquals(expected, p); } @Test public void test_loadProperties_oneFile_notRootPath() throws Exception { Properties p = ConfigUtils.loadProperties("META-INF/dubbo/internal/com.alibaba.dubbo.common.threadpool.ThreadPool", false); Properties expected = new Properties(); expected.put("fixed", "com.alibaba.dubbo.common.threadpool.support.fixed.FixedThreadPool"); expected.put("cached", "com.alibaba.dubbo.common.threadpool.support.cached.CachedThreadPool"); expected.put("limited", "com.alibaba.dubbo.common.threadpool.support.limited.LimitedThreadPool"); Assert.assertEquals(expected, p); } @Ignore("see http: @Test public void test_loadProperties_multiFile_notRootPath_Exception() throws Exception { try { ConfigUtils.loadProperties("META-INF/services/com.alibaba.dubbo.common.status.StatusChecker", false); Assert.fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString("only 1 META-INF/services/com.alibaba.dubbo.common.status.StatusChecker file is expected, but 2 dubbo.properties files found on class path:")); } } @Test public void test_loadProperties_multiFile_notRootPath() throws Exception { Properties p = ConfigUtils.loadProperties("META-INF/dubbo/internal/com.alibaba.dubbo.common.status.StatusChecker", true); Properties expected = new Properties(); expected.put("memory", "com.alibaba.dubbo.common.status.support.MemoryStatusChecker"); expected.put("load", "com.alibaba.dubbo.common.status.support.LoadStatusChecker"); expected.put("aa", "12"); Assert.assertEquals(expected, p); }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } AbstractClusterInvoker(Directory<T> directory); AbstractClusterInvoker(Directory<T> directory, URL url); Class<T> getInterface(); URL getUrl(); boolean isAvailable(); void destroy(); Result invoke(final Invocation invocation); @Override String toString(); }
@Test public void testSelect_Invokersize0() throws Exception { { Invoker invoker = cluster.select(null, null, null, null); Assert.assertEquals(null, invoker); } { invokers.clear(); selectedInvokers.clear(); Invoker invoker = cluster.select(null, null, invokers, null); Assert.assertEquals(null, invoker); } } @Test public void testSelect_Invokersize1() throws Exception { invokers.clear(); invokers.add(invoker1); Invoker invoker = cluster.select(null, null, invokers, null); Assert.assertEquals(invoker1, invoker); } @Test public void testSelect_Invokersize2AndselectNotNull() throws Exception { invokers.clear(); invokers.add(invoker1); invokers.add(invoker2); { selectedInvokers.clear(); selectedInvokers.add(invoker1); Invoker invoker = cluster.select(null, null, invokers, selectedInvokers); Assert.assertEquals(invoker2, invoker); } { selectedInvokers.clear(); selectedInvokers.add(invoker2); Invoker invoker = cluster.select(null, null, invokers, selectedInvokers); Assert.assertEquals(invoker1, invoker); } } @Test public void testDonotSelectAgainAndNoCheckAvailable() { LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RoundRobinLoadBalance.NAME); initlistsize5(); { selectedInvokers.clear(); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assert.assertSame(invoker1, sinvoker); } { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker3); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assert.assertSame(invoker2, sinvoker); } { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assert.assertSame(invoker3, sinvoker); } { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); selectedInvokers.add(invoker4); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assert.assertSame(invoker5, sinvoker); } { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assert.assertTrue(invokers.contains(sinvoker)); } } @Test public void testSelectAgainAndCheckAvailable() { LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RoundRobinLoadBalance.NAME); initlistsize5(); { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); selectedInvokers.add(invoker5); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assert.assertTrue(sinvoker == invoker4); } { selectedInvokers.clear(); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assert.assertTrue(sinvoker == invoker2 || sinvoker == invoker4); } { for (int i = 0; i < 100; i++) { selectedInvokers.clear(); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assert.assertTrue(sinvoker == invoker2 || sinvoker == invoker4); } } { for (int i = 0; i < 100; i++) { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker3); selectedInvokers.add(invoker5); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assert.assertTrue(sinvoker == invoker2 || sinvoker == invoker4); } } { for (int i = 0; i < 100; i++) { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker3); selectedInvokers.add(invoker2); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); Assert.assertTrue(sinvoker == invoker2 || sinvoker == invoker4); } } }
PojoUtils { public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } static Object[] generalize(Object[] objs); static Object[] realize(Object[] objs, Class<?>[] types); static Object[] realize(Object[] objs, Class<?>[] types, Type[] gtypes); static Object generalize(Object pojo); static Object realize(Object pojo, Class<?> type); static Object realize(Object pojo, Class<?> type, Type genericType); static boolean isPojo(Class<?> cls); }
@Test public void test_realize_LongPararmter_IllegalArgumentException() throws Exception { Method method = PojoUtilsTest.class.getMethod("setLong", long.class); assertNotNull(method); Object value = PojoUtils.realize("563439743927993", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]); method.invoke(new PojoUtilsTest(), value); } @Test public void test_realize_IntPararmter_IllegalArgumentException() throws Exception { Method method = PojoUtilsTest.class.getMethod("setInt", int.class); assertNotNull(method); Object value = PojoUtils.realize("123", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]); method.invoke(new PojoUtilsTest(), value); } @Test public void testRealize() throws Exception { Map<String, String> inputMap = new LinkedHashMap<String, String>(); inputMap.put("key", "value"); Object obj = PojoUtils.generalize(inputMap); Assert.assertTrue(obj instanceof LinkedHashMap); Object outputObject = PojoUtils.realize(inputMap, LinkedHashMap.class); System.out.println(outputObject.getClass().getName()); Assert.assertTrue(outputObject instanceof LinkedHashMap); }
CompatibleTypeUtils { @SuppressWarnings({"unchecked", "rawtypes"}) public static Object compatibleTypeConvert(Object value, Class<?> type) { if (value == null || type == null || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } else if (type.isEnum()) { return Enum.valueOf((Class<Enum>) type, string); } else if (type == BigInteger.class) { return new BigInteger(string); } else if (type == BigDecimal.class) { return new BigDecimal(string); } else if (type == Short.class || type == short.class) { return new Short(string); } else if (type == Integer.class || type == int.class) { return new Integer(string); } else if (type == Long.class || type == long.class) { return new Long(string); } else if (type == Double.class || type == double.class) { return new Double(string); } else if (type == Float.class || type == float.class) { return new Float(string); } else if (type == Byte.class || type == byte.class) { return new Byte(string); } else if (type == Boolean.class || type == boolean.class) { return new Boolean(string); } else if (type == Date.class) { try { return new SimpleDateFormat(DATE_FORMAT).parse((String) value); } catch (ParseException e) { throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + e.getMessage(), e); } } else if (type == Class.class) { try { return ReflectUtils.name2class((String) value); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } } } else if (value instanceof Number) { Number number = (Number) value; if (type == byte.class || type == Byte.class) { return number.byteValue(); } else if (type == short.class || type == Short.class) { return number.shortValue(); } else if (type == int.class || type == Integer.class) { return number.intValue(); } else if (type == long.class || type == Long.class) { return number.longValue(); } else if (type == float.class || type == Float.class) { return number.floatValue(); } else if (type == double.class || type == Double.class) { return number.doubleValue(); } else if (type == BigInteger.class) { return BigInteger.valueOf(number.longValue()); } else if (type == BigDecimal.class) { return BigDecimal.valueOf(number.doubleValue()); } else if (type == Date.class) { return new Date(number.longValue()); } } else if (value instanceof Collection) { Collection collection = (Collection) value; if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } else if (!type.isInterface()) { try { Collection result = (Collection) type.newInstance(); result.addAll(collection); return result; } catch (Throwable e) { } } else if (type == List.class) { return new ArrayList<Object>(collection); } else if (type == Set.class) { return new HashSet<Object>(collection); } } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { Collection collection; if (!type.isInterface()) { try { collection = (Collection) type.newInstance(); } catch (Throwable e) { collection = new ArrayList<Object>(); } } else if (type == Set.class) { collection = new HashSet<Object>(); } else { collection = new ArrayList<Object>(); } int length = Array.getLength(value); for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; } private CompatibleTypeUtils(); @SuppressWarnings({"unchecked", "rawtypes"}) static Object compatibleTypeConvert(Object value, Class<?> type); }
@SuppressWarnings("unchecked") @Test public void testCompatibleTypeConvert() throws Exception { Object result; { Object input = new Object(); result = CompatibleTypeUtils.compatibleTypeConvert(input, Date.class); assertSame(input, result); result = CompatibleTypeUtils.compatibleTypeConvert(input, null); assertSame(input, result); result = CompatibleTypeUtils.compatibleTypeConvert(null, Date.class); assertNull(result); } { result = CompatibleTypeUtils.compatibleTypeConvert("a", char.class); assertEquals(Character.valueOf('a'), (Character) result); result = CompatibleTypeUtils.compatibleTypeConvert("A", MyEnum.class); assertEquals(MyEnum.A, (MyEnum) result); result = CompatibleTypeUtils.compatibleTypeConvert("3", BigInteger.class); assertEquals(new BigInteger("3"), (BigInteger) result); result = CompatibleTypeUtils.compatibleTypeConvert("3", BigDecimal.class); assertEquals(new BigDecimal("3"), (BigDecimal) result); result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", Date.class); assertEquals(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2011-12-11 12:24:12"), (Date) result); } { result = CompatibleTypeUtils.compatibleTypeConvert(3, byte.class); assertEquals(Byte.valueOf((byte) 3), (Byte) result); result = CompatibleTypeUtils.compatibleTypeConvert((byte) 3, int.class); assertEquals(Integer.valueOf(3), (Integer) result); result = CompatibleTypeUtils.compatibleTypeConvert(3, short.class); assertEquals(Short.valueOf((short) 3), (Short) result); result = CompatibleTypeUtils.compatibleTypeConvert((short) 3, int.class); assertEquals(Integer.valueOf(3), (Integer) result); result = CompatibleTypeUtils.compatibleTypeConvert(3, int.class); assertEquals(Integer.valueOf(3), (Integer) result); result = CompatibleTypeUtils.compatibleTypeConvert(3, long.class); assertEquals(Long.valueOf(3), (Long) result); result = CompatibleTypeUtils.compatibleTypeConvert(3L, int.class); assertEquals(Integer.valueOf(3), (Integer) result); result = CompatibleTypeUtils.compatibleTypeConvert(3L, BigInteger.class); assertEquals(BigInteger.valueOf(3L), (BigInteger) result); result = CompatibleTypeUtils.compatibleTypeConvert(BigInteger.valueOf(3L), int.class); assertEquals(Integer.valueOf(3), (Integer) result); } { result = CompatibleTypeUtils.compatibleTypeConvert(3D, float.class); assertEquals(Float.valueOf(3), (Float) result); result = CompatibleTypeUtils.compatibleTypeConvert(3F, double.class); assertEquals(Double.valueOf(3), (Double) result); result = CompatibleTypeUtils.compatibleTypeConvert(3D, double.class); assertEquals(Double.valueOf(3), (Double) result); result = CompatibleTypeUtils.compatibleTypeConvert(3D, BigDecimal.class); assertEquals(BigDecimal.valueOf(3D), (BigDecimal) result); result = CompatibleTypeUtils.compatibleTypeConvert(BigDecimal.valueOf(3D), double.class); assertEquals(Double.valueOf(3), (Double) result); } { List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); Set<String> set = new HashSet<String>(); set.add("a"); set.add("b"); String[] array = new String[]{"a", "b"}; result = CompatibleTypeUtils.compatibleTypeConvert(array, List.class); assertEquals(ArrayList.class, result.getClass()); assertEquals(2, ((List<String>) result).size()); assertTrue(((List<String>) result).contains("a")); assertTrue(((List<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(set, List.class); assertEquals(ArrayList.class, result.getClass()); assertEquals(2, ((List<String>) result).size()); assertTrue(((List<String>) result).contains("a")); assertTrue(((List<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(array, CopyOnWriteArrayList.class); assertEquals(CopyOnWriteArrayList.class, result.getClass()); assertEquals(2, ((List<String>) result).size()); assertTrue(((List<String>) result).contains("a")); assertTrue(((List<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(set, CopyOnWriteArrayList.class); assertEquals(CopyOnWriteArrayList.class, result.getClass()); assertEquals(2, ((List<String>) result).size()); assertTrue(((List<String>) result).contains("a")); assertTrue(((List<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(set, String[].class); assertEquals(String[].class, result.getClass()); assertEquals(2, ((String[]) result).length); assertTrue(((String[]) result)[0].equals("a") || ((String[]) result)[0].equals("b")); assertTrue(((String[]) result)[1].equals("a") || ((String[]) result)[1].equals("b")); result = CompatibleTypeUtils.compatibleTypeConvert(array, Set.class); assertEquals(HashSet.class, result.getClass()); assertEquals(2, ((Set<String>) result).size()); assertTrue(((Set<String>) result).contains("a")); assertTrue(((Set<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(list, Set.class); assertEquals(HashSet.class, result.getClass()); assertEquals(2, ((Set<String>) result).size()); assertTrue(((Set<String>) result).contains("a")); assertTrue(((Set<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(array, ConcurrentHashSet.class); assertEquals(ConcurrentHashSet.class, result.getClass()); assertEquals(2, ((Set<String>) result).size()); assertTrue(((Set<String>) result).contains("a")); assertTrue(((Set<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(list, ConcurrentHashSet.class); assertEquals(ConcurrentHashSet.class, result.getClass()); assertEquals(2, ((Set<String>) result).size()); assertTrue(((Set<String>) result).contains("a")); assertTrue(((Set<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(list, String[].class); assertEquals(String[].class, result.getClass()); assertEquals(2, ((String[]) result).length); assertTrue(((String[]) result)[0].equals("a")); assertTrue(((String[]) result)[1].equals("b")); } }
ReflectUtils { public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { String signature = methodName; if (parameterTypes != null && parameterTypes.length > 0) { signature = methodName + StringUtils.join(parameterTypes); } Method method = Signature_METHODS_CACHE.get(signature); if (method != null) { return method; } if (parameterTypes == null) { List<Method> finded = new ArrayList<Method>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); } Signature_METHODS_CACHE.put(signature, method); return method; } private ReflectUtils(); static boolean isPrimitives(Class<?> cls); static boolean isPrimitive(Class<?> cls); static Class<?> getBoxedClass(Class<?> c); static boolean isCompatible(Class<?> c, Object o); static boolean isCompatible(Class<?>[] cs, Object[] os); static String getCodeBase(Class<?> cls); static String getName(Class<?> c); static Class<?> getGenericClass(Class<?> cls); static Class<?> getGenericClass(Class<?> cls, int i); static String getName(final Method m); static String getSignature(String methodName, Class<?>[] parameterTypes); static String getName(final Constructor<?> c); static String getDesc(Class<?> c); static String getDesc(final Class<?>[] cs); static String getDesc(final Method m); static String getDesc(final Constructor<?> c); static String getDescWithoutMethodName(Method m); static String getDesc(final CtClass c); static String getDesc(final CtMethod m); static String getDesc(final CtConstructor c); static String getDescWithoutMethodName(final CtMethod m); static String name2desc(String name); static String desc2name(String desc); static Class<?> forName(String name); static Class<?> name2class(String name); static Class<?> desc2class(String desc); static Class<?>[] desc2classArray(String desc); static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes); static Method findMethodByMethodName(Class<?> clazz, String methodName); static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType); static boolean isInstance(Object obj, String interfaceClazzName); static Object getEmptyObject(Class<?> returnType); static boolean isBeanPropertyReadMethod(Method method); static String getPropertyNameFromBeanReadMethod(Method method); static boolean isBeanPropertyWriteMethod(Method method); static String getPropertyNameFromBeanWriteMethod(Method method); static boolean isPublicInstanceField(Field field); static final char JVM_VOID; static final char JVM_BOOLEAN; static final char JVM_BYTE; static final char JVM_CHAR; static final char JVM_DOUBLE; static final char JVM_FLOAT; static final char JVM_INT; static final char JVM_LONG; static final char JVM_SHORT; static final Class<?>[] EMPTY_CLASS_ARRAY; static final String JAVA_IDENT_REGEX; static final String JAVA_NAME_REGEX; static final String CLASS_DESC; static final String ARRAY_DESC; static final String DESC_REGEX; static final Pattern DESC_PATTERN; static final String METHOD_DESC_REGEX; static final Pattern METHOD_DESC_PATTERN; static final Pattern GETTER_METHOD_DESC_PATTERN; static final Pattern SETTER_METHOD_DESC_PATTERN; static final Pattern IS_HAS_CAN_METHOD_DESC_PATTERN; }
@Test public void test_findMethodByMethodSignature_override_Morethan1() throws Exception { try { ReflectUtils.findMethodByMethodSignature(TestedClass.class, "overrideMethod", null); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString( "Not unique method for method name(")); } } @Test public void test_findMethodByMethodSignature_notFound() throws Exception { try { ReflectUtils.findMethodByMethodSignature(TestedClass.class, "notExsited", null); fail(); } catch (NoSuchMethodException expected) { assertThat(expected.getMessage(), containsString("No such method ")); assertThat(expected.getMessage(), containsString("in class")); } }
ReflectUtils { public static Object getEmptyObject(Class<?> returnType) { return getEmptyObject(returnType, new HashMap<Class<?>, Object>(), 0); } private ReflectUtils(); static boolean isPrimitives(Class<?> cls); static boolean isPrimitive(Class<?> cls); static Class<?> getBoxedClass(Class<?> c); static boolean isCompatible(Class<?> c, Object o); static boolean isCompatible(Class<?>[] cs, Object[] os); static String getCodeBase(Class<?> cls); static String getName(Class<?> c); static Class<?> getGenericClass(Class<?> cls); static Class<?> getGenericClass(Class<?> cls, int i); static String getName(final Method m); static String getSignature(String methodName, Class<?>[] parameterTypes); static String getName(final Constructor<?> c); static String getDesc(Class<?> c); static String getDesc(final Class<?>[] cs); static String getDesc(final Method m); static String getDesc(final Constructor<?> c); static String getDescWithoutMethodName(Method m); static String getDesc(final CtClass c); static String getDesc(final CtMethod m); static String getDesc(final CtConstructor c); static String getDescWithoutMethodName(final CtMethod m); static String name2desc(String name); static String desc2name(String desc); static Class<?> forName(String name); static Class<?> name2class(String name); static Class<?> desc2class(String desc); static Class<?>[] desc2classArray(String desc); static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes); static Method findMethodByMethodName(Class<?> clazz, String methodName); static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType); static boolean isInstance(Object obj, String interfaceClazzName); static Object getEmptyObject(Class<?> returnType); static boolean isBeanPropertyReadMethod(Method method); static String getPropertyNameFromBeanReadMethod(Method method); static boolean isBeanPropertyWriteMethod(Method method); static String getPropertyNameFromBeanWriteMethod(Method method); static boolean isPublicInstanceField(Field field); static final char JVM_VOID; static final char JVM_BOOLEAN; static final char JVM_BYTE; static final char JVM_CHAR; static final char JVM_DOUBLE; static final char JVM_FLOAT; static final char JVM_INT; static final char JVM_LONG; static final char JVM_SHORT; static final Class<?>[] EMPTY_CLASS_ARRAY; static final String JAVA_IDENT_REGEX; static final String JAVA_NAME_REGEX; static final String CLASS_DESC; static final String ARRAY_DESC; static final String DESC_REGEX; static final Pattern DESC_PATTERN; static final String METHOD_DESC_REGEX; static final Pattern METHOD_DESC_PATTERN; static final Pattern GETTER_METHOD_DESC_PATTERN; static final Pattern SETTER_METHOD_DESC_PATTERN; static final Pattern IS_HAS_CAN_METHOD_DESC_PATTERN; }
@Test public void test_getEmptyObject() throws Exception { assertTrue(ReflectUtils.getEmptyObject(Collection.class) instanceof Collection); assertTrue(ReflectUtils.getEmptyObject(List.class) instanceof List); assertTrue(ReflectUtils.getEmptyObject(Set.class) instanceof Set); assertTrue(ReflectUtils.getEmptyObject(Map.class) instanceof Map); assertTrue(ReflectUtils.getEmptyObject(Object[].class) instanceof Object[]); assertEquals(ReflectUtils.getEmptyObject(String.class), ""); assertEquals(ReflectUtils.getEmptyObject(short.class), Short.valueOf((short) 0)); assertEquals(ReflectUtils.getEmptyObject(byte.class), Byte.valueOf((byte) 0)); assertEquals(ReflectUtils.getEmptyObject(int.class), Integer.valueOf(0)); assertEquals(ReflectUtils.getEmptyObject(long.class), Long.valueOf(0)); assertEquals(ReflectUtils.getEmptyObject(float.class), Float.valueOf(0)); assertEquals(ReflectUtils.getEmptyObject(double.class), Double.valueOf(0)); assertEquals(ReflectUtils.getEmptyObject(char.class), Character.valueOf('\0')); assertEquals(ReflectUtils.getEmptyObject(boolean.class), Boolean.FALSE); EmptyClass object = (EmptyClass) ReflectUtils.getEmptyObject(EmptyClass.class); assertNotNull(object); assertNotNull(object.getProperty()); }
UrlUtils { public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } static URL parseURL(String address, Map<String, String> defaults); static List<URL> parseURLs(String address, Map<String, String> defaults); static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register); static Map<String, String> convertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register); static Map<String, String> revertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify); static List<String> revertForbid(List<String> forbid, Set<URL> subscribed); static URL getEmptyUrl(String service, String category); static boolean isMatchCategory(String category, String categories); static boolean isMatch(URL consumerUrl, URL providerUrl); static boolean isMatchGlobPattern(String pattern, String value, URL param); static boolean isMatchGlobPattern(String pattern, String value); static boolean isServiceKeyMatch(URL pattern, URL value); }
@Test public void testRevertForbid() { String service = "dubbo.test.api.HelloService"; List<String> forbid = new ArrayList<String>(); forbid.add(service); Set<URL> subscribed = new HashSet<URL>(); subscribed.add(URL.valueOf("dubbo: List<String> newForbid = UrlUtils.revertForbid(forbid, subscribed); List<String> expectForbid = new ArrayList<String>(); expectForbid.add("perf/" + service + ":1.0.0"); assertEquals(expectForbid, newForbid); } @Test public void testRevertForbid2() { List<String> newForbid = UrlUtils.revertForbid(null, null); assertNull(newForbid); } @Test public void testRevertForbid3() { String service1 = "dubbo.test.api.HelloService:1.0.0"; String service2 = "dubbo.test.api.HelloService:2.0.0"; List<String> forbid = new ArrayList<String>(); forbid.add(service1); forbid.add(service2); List<String> newForbid = UrlUtils.revertForbid(forbid, null); assertEquals(forbid, newForbid); }
UrlUtils { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); } static URL parseURL(String address, Map<String, String> defaults); static List<URL> parseURLs(String address, Map<String, String> defaults); static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register); static Map<String, String> convertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register); static Map<String, String> revertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify); static List<String> revertForbid(List<String> forbid, Set<URL> subscribed); static URL getEmptyUrl(String service, String category); static boolean isMatchCategory(String category, String categories); static boolean isMatch(URL consumerUrl, URL providerUrl); static boolean isMatchGlobPattern(String pattern, String value, URL param); static boolean isMatchGlobPattern(String pattern, String value); static boolean isServiceKeyMatch(URL pattern, URL value); }
@Test public void testIsMatch() { URL consumerUrl = URL.valueOf("dubbo: URL providerUrl = URL.valueOf("http: assertTrue(UrlUtils.isMatch(consumerUrl, providerUrl)); } @Test public void testIsMatch2() { URL consumerUrl = URL.valueOf("dubbo: URL providerUrl = URL.valueOf("http: assertFalse(UrlUtils.isMatch(consumerUrl, providerUrl)); } @Test public void testIsMatch3() { URL consumerUrl = URL.valueOf("dubbo: URL providerUrl = URL.valueOf("http: assertFalse(UrlUtils.isMatch(consumerUrl, providerUrl)); } @Test public void testIsMatch4() { URL consumerUrl = URL.valueOf("dubbo: URL providerUrl = URL.valueOf("http: assertTrue(UrlUtils.isMatch(consumerUrl, providerUrl)); } @Test public void testIsMatch5() { URL consumerUrl = URL.valueOf("dubbo: URL providerUrl = URL.valueOf("http: assertTrue(UrlUtils.isMatch(consumerUrl, providerUrl)); }
CollectionUtils { public static List<String> join(Map<String, String> map, String separator) { if (map == null) { return null; } List<String> list = new ArrayList<String>(); if (map == null || map.size() == 0) { return list; } for (Map.Entry<String, String> entry : map.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (value == null || value.length() == 0) { list.add(key); } else { list.add(key + separator + value); } } return list; } private CollectionUtils(); @SuppressWarnings({"unchecked", "rawtypes"}) static List<T> sort(List<T> list); static List<String> sortSimpleName(List<String> list); static Map<String, Map<String, String>> splitAll(Map<String, List<String>> list, String separator); static Map<String, List<String>> joinAll(Map<String, Map<String, String>> map, String separator); static Map<String, String> split(List<String> list, String separator); static List<String> join(Map<String, String> map, String separator); static String join(List<String> list, String separator); static boolean mapEquals(Map<?, ?> map1, Map<?, ?> map2); static Map<String, String> toStringMap(String... pairs); @SuppressWarnings("unchecked") static Map<K, V> toMap(Object... pairs); static boolean isEmpty(Collection<?> collection); static boolean isNotEmpty(Collection<?> collection); }
@Test public void test_joinList() throws Exception { List<String> list = Arrays.asList(); assertEquals("", CollectionUtils.join(list, "/")); list = Arrays.asList("x"); assertEquals("x", CollectionUtils.join(list, "-")); list = Arrays.asList("a", "b"); assertEquals("a/b", CollectionUtils.join(list, "/")); }
RouteRuleUtils { public static <T extends Collection<String>> Map<String, RouteRule.MatchPair> expandCondition( Map<String, RouteRule.MatchPair> condition, String srcKeyName, String destKeyName, Map<String, T> expandName2Set) { if (null == condition || StringUtils.isEmpty(srcKeyName) || StringUtils.isEmpty(destKeyName)) { return condition; } RouteRule.MatchPair matchPair = condition.get(srcKeyName); if (matchPair == null) { return condition; } Map<String, RouteRule.MatchPair> ret = new HashMap<String, RouteRule.MatchPair>(); Iterator<Entry<String, RouteRule.MatchPair>> iterator = condition.entrySet().iterator(); for (; iterator.hasNext(); ) { Entry<String, RouteRule.MatchPair> entry = iterator.next(); String condName = entry.getKey(); if (!condName.equals(srcKeyName) && !condName.equals(destKeyName)) { RouteRule.MatchPair p = entry.getValue(); if (p != null) ret.put(condName, p); } else if (condName.equals(srcKeyName)) { RouteRule.MatchPair from = condition.get(srcKeyName); RouteRule.MatchPair to = condition.get(destKeyName); if (from == null || from.getMatches().isEmpty() && from.getUnmatches().isEmpty()) { if (to != null) ret.put(destKeyName, to); continue; } Set<String> matches = new HashSet<String>(); Set<String> unmatches = new HashSet<String>(); for (String s : from.getMatches()) { if (expandName2Set == null || !expandName2Set.containsKey(s)) continue; matches.addAll(expandName2Set.get(s)); } for (String s : from.getUnmatches()) { if (expandName2Set == null || !expandName2Set.containsKey(s)) continue; unmatches.addAll(expandName2Set.get(s)); } if (to != null) { matches.addAll(to.getMatches()); unmatches.addAll(to.getUnmatches()); } ret.put(destKeyName, new RouteRule.MatchPair(matches, unmatches)); } } return ret; } private RouteRuleUtils(); static Map<String, RouteRule.MatchPair> expandCondition( Map<String, RouteRule.MatchPair> condition, String srcKeyName, String destKeyName, Map<String, T> expandName2Set); static boolean isMatchCondition(Map<String, RouteRule.MatchPair> condition, Map<String, String> valueParams, Map<String, String> kv); static Set<String> filterServiceByRule(List<String> services, RouteRule rule); }
@Test public void test_expandCondition() throws Exception { Map<String, RouteRule.MatchPair> condition = new HashMap<String, RouteRule.MatchPair>(); { Set<String> matches = new HashSet<String>(); matches.add("value1_1"); matches.add("value1_2"); matches.add("value1_3"); Set<String> unmatches = new HashSet<String>(); unmatches.add("v1_1"); unmatches.add("v1_2"); unmatches.add("v1_3"); RouteRule.MatchPair p = new RouteRule.MatchPair(matches, unmatches); condition.put("key1", p); matches = new HashSet<String>(); matches.add("value2_1"); matches.add("value2_2"); matches.add("value2_3"); unmatches = new HashSet<String>(); unmatches.add("v2_1"); unmatches.add("v2_2"); unmatches.add("v2_3"); p = new RouteRule.MatchPair(matches, unmatches); condition.put("key2", p); matches = new HashSet<String>(); matches.add("value3_1"); matches.add("value3_2"); matches.add("value3_3"); unmatches = new HashSet<String>(); unmatches.add("v3_1"); unmatches.add("v3_2"); unmatches.add("v3_3"); p = new RouteRule.MatchPair(matches, unmatches); condition.put("key3 ", p); } Map<String, Set<String>> expandName2Set = new HashMap<String, Set<String>>(); { expandName2Set.put("value1_1", new HashSet<String>(Arrays.asList("cat1", "dog1"))); expandName2Set.put("value1_2", new HashSet<String>(Arrays.asList("cat2", "dog2"))); expandName2Set.put("value1_3", new HashSet<String>(Arrays.asList("cat3", "dog3"))); expandName2Set.put("v1_1", new HashSet<String>(Arrays.asList("pig1", "rat1"))); expandName2Set.put("v1_2", new HashSet<String>(Arrays.asList("pig2", "rat2"))); } Map<String, RouteRule.MatchPair> output = RouteRuleUtils.expandCondition(condition, "key1", "key2", expandName2Set); Map<String, RouteRule.MatchPair> expected = new HashMap<String, RouteRule.MatchPair>(); { Set<String> matches = new HashSet<String>(); matches.add("value2_1"); matches.add("value2_2"); matches.add("value2_3"); matches.add("cat1"); matches.add("cat2"); matches.add("cat3"); matches.add("dog1"); matches.add("dog2"); matches.add("dog3"); Set<String> unmatches = new HashSet<String>(); unmatches.add("v2_1"); unmatches.add("v2_2"); unmatches.add("v2_3"); unmatches.add("v2_3"); unmatches.add("pig1"); unmatches.add("pig2"); unmatches.add("rat1"); unmatches.add("rat2"); RouteRule.MatchPair p = new RouteRule.MatchPair(matches, unmatches); expected.put("key2", p); matches = new HashSet<String>(); matches.add("value3_1"); matches.add("value3_2"); matches.add("value3_3"); unmatches = new HashSet<String>(); unmatches.add("v3_1"); unmatches.add("v3_2"); unmatches.add("v3_3"); p = new RouteRule.MatchPair(matches, unmatches); expected.put("key3 ", p); } assertEquals(expected, output); output = RouteRuleUtils.expandCondition(condition, "key1", "keyX", expandName2Set); expected = new HashMap<String, RouteRule.MatchPair>(); { Set<String> matches = new HashSet<String>(); matches.add("cat1"); matches.add("cat2"); matches.add("cat3"); matches.add("dog1"); matches.add("dog2"); matches.add("dog3"); Set<String> unmatches = new HashSet<String>(); unmatches.add("pig1"); unmatches.add("pig2"); unmatches.add("rat1"); unmatches.add("rat2"); RouteRule.MatchPair p = new RouteRule.MatchPair(matches, unmatches); expected.put("keyX", p); matches = new HashSet<String>(); matches.add("value2_1"); matches.add("value2_2"); matches.add("value2_3"); unmatches = new HashSet<String>(); unmatches.add("v2_1"); unmatches.add("v2_2"); unmatches.add("v2_3"); p = new RouteRule.MatchPair(matches, unmatches); expected.put("key2", p); matches = new HashSet<String>(); matches.add("value3_1"); matches.add("value3_2"); matches.add("value3_3"); unmatches = new HashSet<String>(); unmatches.add("v3_1"); unmatches.add("v3_2"); unmatches.add("v3_3"); p = new RouteRule.MatchPair(matches, unmatches); expected.put("key3 ", p); } output = RouteRuleUtils.expandCondition(condition, "keyNotExsited", "key3", expandName2Set); assertSame(condition, output); }
RouteRuleUtils { public static Set<String> filterServiceByRule(List<String> services, RouteRule rule) { if (null == services || services.isEmpty() || rule == null) { return new HashSet<String>(); } RouteRule.MatchPair p = rule.getWhenCondition().get("service"); if (p == null) { return new HashSet<String>(); } Set<String> filter = ParseUtils.filterByGlobPattern(p.getMatches(), services); Set<String> set = ParseUtils.filterByGlobPattern(p.getUnmatches(), services); filter.addAll(set); return filter; } private RouteRuleUtils(); static Map<String, RouteRule.MatchPair> expandCondition( Map<String, RouteRule.MatchPair> condition, String srcKeyName, String destKeyName, Map<String, T> expandName2Set); static boolean isMatchCondition(Map<String, RouteRule.MatchPair> condition, Map<String, String> valueParams, Map<String, String> kv); static Set<String> filterServiceByRule(List<String> services, RouteRule rule); }
@Test public void test_filterServiceByRule() throws Exception { List<String> services = new ArrayList<String>(); services.add("com.alibaba.MemberService"); services.add("com.alibaba.ViewCacheService"); services.add("com.alibaba.PC2Service"); services.add("service2"); Route route = new Route(); route.setMatchRule("service=com.alibaba.*,AuthService&service!=com.alibaba.DomainService,com.alibaba.ViewCacheService&consumer.host!=127.0.0.1,15.11.57.6&consumer.version = 2.0.0&consumer.version != 1.0.0"); route.setFilterRule("provider.application=morgan,pc2&provider.host=10.16.26.51&provider.port=1020"); RouteRule rr = RouteRule.parse(route); Collection<String> changedService = RouteRuleUtils.filterServiceByRule(services, rr); assertEquals(3, changedService.size()); } @Test public void test_filterServiceByRule2() throws Exception { List<String> services = new ArrayList<String>(); services.add("com.alibaba.MemberService"); services.add("com.alibaba.ViewCacheService"); services.add("com.alibaba.PC2Service"); services.add("service2"); Route route = new Route(); route.setMatchRule("service=com.alibaba.PC2Service&service!=com.alibaba.DomainService,com.alibaba.ViewCacheService&consumer.host!=127.0.0.1,15.11.57.6&consumer.version = 2.0.0&consumer.version != 1.0.0"); route.setFilterRule("provider.application=morgan,pc2&provider.host=10.16.26.51&provider.port=1020"); RouteRule rr = RouteRule.parse(route); Collection<String> changedService = RouteRuleUtils.filterServiceByRule(services, rr); assertEquals(2, changedService.size()); }
RouteRuleUtils { public static boolean isMatchCondition(Map<String, RouteRule.MatchPair> condition, Map<String, String> valueParams, Map<String, String> kv) { if (condition != null && condition.size() > 0) { for (Map.Entry<String, RouteRule.MatchPair> entry : condition.entrySet()) { String condName = entry.getKey(); RouteRule.MatchPair p = entry.getValue(); String value = kv.get(condName); Set<String> matches = p.getMatches(); if (matches != null && matches.size() > 0 && !ParseUtils.isMatchGlobPatternsNeedInterpolate(matches, valueParams, value)) { return false; } Set<String> unmatches = p.getUnmatches(); if (unmatches != null && unmatches.size() > 0 && ParseUtils.isMatchGlobPatternsNeedInterpolate(unmatches, valueParams, value)) { return false; } } } return true; } private RouteRuleUtils(); static Map<String, RouteRule.MatchPair> expandCondition( Map<String, RouteRule.MatchPair> condition, String srcKeyName, String destKeyName, Map<String, T> expandName2Set); static boolean isMatchCondition(Map<String, RouteRule.MatchPair> condition, Map<String, String> valueParams, Map<String, String> kv); static Set<String> filterServiceByRule(List<String> services, RouteRule rule); }
@Test public void test_isMatchCondition() throws Exception { Map<String, RouteRule.MatchPair> condition = new HashMap<String, RouteRule.MatchPair>(); Map<String, String> valueParams = new HashMap<String, String>(); Map<String, String> kv = new HashMap<String, String>(); boolean output = RouteRuleUtils.isMatchCondition(condition, valueParams, kv); assertTrue(output); { Set<String> matches = new HashSet<String>(); matches.add("value1_1"); matches.add("value1_2"); matches.add("value1_3"); Set<String> unmatches = new HashSet<String>(); unmatches.add("v1_1"); unmatches.add("v1_2"); unmatches.add("v1_3"); RouteRule.MatchPair p = new RouteRule.MatchPair(matches, unmatches); condition.put("key1", p); matches = new HashSet<String>(); matches.add("value2_1"); matches.add("value2_2"); matches.add("value2_3"); unmatches = new HashSet<String>(); unmatches.add("v2_1"); unmatches.add("v2_2"); unmatches.add("v2_3"); p = new RouteRule.MatchPair(matches, unmatches); condition.put("key2", p); } kv.put("kkk", "vvv"); output = RouteRuleUtils.isMatchCondition(condition, valueParams, kv); assertFalse(output); kv.put("key1", "vvvXXX"); output = RouteRuleUtils.isMatchCondition(condition, valueParams, kv); assertFalse(output); kv.put("key1", "value1_1"); output = RouteRuleUtils.isMatchCondition(condition, valueParams, kv); assertFalse(output); kv.put("key2", "value2_1"); output = RouteRuleUtils.isMatchCondition(condition, valueParams, kv); assertTrue(output); kv.put("key1", "v1_2"); output = RouteRuleUtils.isMatchCondition(condition, valueParams, kv); assertFalse(output); }
ParseUtils { public static String interpolate(String expression, Map<String, String> params) { if (expression == null || expression.length() == 0) { throw new IllegalArgumentException("glob pattern is empty!"); } if (expression.indexOf('$') < 0) { return expression; } Matcher matcher = VARIABLE_PATTERN.matcher(expression); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String key = matcher.group(1); String value = params == null ? null : params.get(key); if (value == null) { value = ""; } matcher.appendReplacement(sb, value); } matcher.appendTail(sb); return sb.toString(); } private ParseUtils(); static String interpolate(String expression, Map<String, String> params); static List<String> interpolate(List<String> expressions, Map<String, String> params); static boolean isMatchGlobPattern(String pattern, String value); static boolean isMatchGlobPatternsNeedInterpolate( Collection<String> patternsNeedInterpolate, Map<String, String> interpolateParams, String value); static Set<String> filterByGlobPattern(String pattern, Collection<String> values); static Set<String> filterByGlobPattern(Collection<String> patterns, Collection<String> values); static boolean hasIntersection(String glob1, String glob2); static Map<String, String> parseQuery(String keyPrefix, String query); static Map<String, String> parseQuery(String query); static String replaceParameter(String query, String key, String value); static String appendParamToUri(String uri, String name, String value); static String appendParamsToUri(String uri, Map<String, String> params); static boolean matchEndStarPattern(String value, String pattern); static String METHOD_SPLIT; }
@Test public void testInterpolateDot() throws Exception { String regexp = ParseUtils.interpolate("com.alibaba.morgan.MemberService", new HashMap<String, String>()); assertEquals("com.alibaba.morgan.MemberService", regexp); } @Test public void testInterpolateWildcard() throws Exception { String regexp = ParseUtils.interpolate("com.alibaba.morgan.*", new HashMap<String, String>()); assertEquals("com.alibaba.morgan.*", regexp); } @Test public void testInterpolateSequence() throws Exception { String regexp = ParseUtils.interpolate("1.0.[0-9]", new HashMap<String, String>()); assertEquals("1.0.[0-9]", regexp.toString()); } @Test public void testInterpolateVariable() throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("consumer.address", "10.20.130.230"); String regexp = ParseUtils.interpolate("xx$consumer.address", params); assertEquals("xx10.20.130.230", regexp); } @Test public void testInterpolateVariableWithParentheses() throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("consumer.address", "10.20.130.230"); String regexp = ParseUtils.interpolate("xx${consumer.address}yy", params); assertEquals("xx10.20.130.230yy", regexp); } @Test public void testInterpolateCollMap_NormalCase() throws Exception { List<String> expressions = new ArrayList<String>(); expressions.add("xx$var1"); expressions.add("yy${var2}zz"); Map<String, String> params = new HashMap<String, String>(); params.put("var1", "CAT"); params.put("var2", "DOG"); List<String> interpolate = ParseUtils.interpolate(expressions, params); List<String> expected = new ArrayList<String>(); expected.add("xxCAT"); expected.add("yyDOGzz"); assertEquals(expected, interpolate); }
AbstractClusterInvoker implements Invoker<T> { public Result invoke(final Invocation invocation) throws RpcException { checkWheatherDestoried(); LoadBalance loadbalance; List<Invoker<T>> invokers = list(invocation); if (invokers != null && invokers.size() > 0) { loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(0).getUrl() .getMethodParameter(invocation.getMethodName(), Constants.LOADBALANCE_KEY, Constants.DEFAULT_LOADBALANCE)); } else { loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(Constants.DEFAULT_LOADBALANCE); } RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation); return doInvoke(invocation, invokers, loadbalance); } AbstractClusterInvoker(Directory<T> directory); AbstractClusterInvoker(Directory<T> directory, URL url); Class<T> getInterface(); URL getUrl(); boolean isAvailable(); void destroy(); Result invoke(final Invocation invocation); @Override String toString(); }
@Test() public void testTimeoutExceptionCode() { List<Invoker<DemoService>> invokers = new ArrayList<Invoker<DemoService>>(); invokers.add(new Invoker<DemoService>() { public Class<DemoService> getInterface() { return DemoService.class; } public URL getUrl() { return URL.valueOf("dubbo: } public boolean isAvailable() { return false; } public Result invoke(Invocation invocation) throws RpcException { throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "test timeout"); } public void destroy() { } }); Directory<DemoService> directory = new StaticDirectory<DemoService>(invokers); FailoverClusterInvoker<DemoService> failoverClusterInvoker = new FailoverClusterInvoker<DemoService>(directory); try { failoverClusterInvoker.invoke(new RpcInvocation("sayHello", new Class<?>[0], new Object[0])); Assert.fail(); } catch (RpcException e) { Assert.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode()); } ForkingClusterInvoker<DemoService> forkingClusterInvoker = new ForkingClusterInvoker<DemoService>(directory); try { forkingClusterInvoker.invoke(new RpcInvocation("sayHello", new Class<?>[0], new Object[0])); Assert.fail(); } catch (RpcException e) { Assert.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode()); } FailfastClusterInvoker<DemoService> failfastClusterInvoker = new FailfastClusterInvoker<DemoService>(directory); try { failfastClusterInvoker.invoke(new RpcInvocation("sayHello", new Class<?>[0], new Object[0])); Assert.fail(); } catch (RpcException e) { Assert.assertEquals(RpcException.TIMEOUT_EXCEPTION, e.getCode()); } }
ParseUtils { public static boolean isMatchGlobPattern(String pattern, String value) { if ("*".equals(pattern)) return true; if ((pattern == null || pattern.length() == 0) && (value == null || value.length() == 0)) return true; if ((pattern == null || pattern.length() == 0) || (value == null || value.length() == 0)) return false; int i = pattern.lastIndexOf('*'); if (i == -1) { return value.equals(pattern); } else if (i == pattern.length() - 1) { return value.startsWith(pattern.substring(0, i)); } else if (i == 0) { return value.endsWith(pattern.substring(i + 1)); } else { String prefix = pattern.substring(0, i); String suffix = pattern.substring(i + 1); return value.startsWith(prefix) && value.endsWith(suffix); } } private ParseUtils(); static String interpolate(String expression, Map<String, String> params); static List<String> interpolate(List<String> expressions, Map<String, String> params); static boolean isMatchGlobPattern(String pattern, String value); static boolean isMatchGlobPatternsNeedInterpolate( Collection<String> patternsNeedInterpolate, Map<String, String> interpolateParams, String value); static Set<String> filterByGlobPattern(String pattern, Collection<String> values); static Set<String> filterByGlobPattern(Collection<String> patterns, Collection<String> values); static boolean hasIntersection(String glob1, String glob2); static Map<String, String> parseQuery(String keyPrefix, String query); static Map<String, String> parseQuery(String query); static String replaceParameter(String query, String key, String value); static String appendParamToUri(String uri, String name, String value); static String appendParamsToUri(String uri, Map<String, String> params); static boolean matchEndStarPattern(String value, String pattern); static String METHOD_SPLIT; }
@Test public void testIsMatchGlobPattern() throws Exception { assertTrue(ParseUtils.isMatchGlobPattern(null, null)); assertFalse(ParseUtils.isMatchGlobPattern("abc", null)); assertFalse(ParseUtils.isMatchGlobPattern(null, "xxx")); assertTrue(ParseUtils.isMatchGlobPattern("", "")); assertFalse(ParseUtils.isMatchGlobPattern("", "xxx")); assertFalse(ParseUtils.isMatchGlobPattern("abc", "")); assertFalse(ParseUtils.isMatchGlobPattern("a*bc", "")); assertFalse(ParseUtils.isMatchGlobPattern("*abc", "")); assertFalse(ParseUtils.isMatchGlobPattern("abc*", "")); assertTrue(ParseUtils.isMatchGlobPattern("*", "")); assertTrue(ParseUtils.isMatchGlobPattern("*", "xxx")); assertTrue(ParseUtils.isMatchGlobPattern("abc*123", "abc123")); assertTrue(ParseUtils.isMatchGlobPattern("abc*123", "abcXXX123")); assertFalse(ParseUtils.isMatchGlobPattern("abc*123", "abcXXX333")); assertTrue(ParseUtils.isMatchGlobPattern("*abc123", "abc123")); assertTrue(ParseUtils.isMatchGlobPattern("*abc123", "XXXabc123")); assertTrue(ParseUtils.isMatchGlobPattern("*abc123", "abc123abc123")); assertFalse(ParseUtils.isMatchGlobPattern("*abc123", "abc123abc333")); assertTrue(ParseUtils.isMatchGlobPattern("abc123*", "abc123")); assertTrue(ParseUtils.isMatchGlobPattern("abc123*", "abc123YYY")); assertTrue(ParseUtils.isMatchGlobPattern("abc123*", "abc123abc123")); assertFalse(ParseUtils.isMatchGlobPattern("abc123*", "abc333abc123")); assertFalse(ParseUtils.isMatchGlobPattern("*abc123*", "abc123abc123")); assertTrue(ParseUtils.isMatchGlobPattern("*abc123*", "*abc123abc123")); assertTrue(ParseUtils.isMatchGlobPattern("*abc123*", "*abc123XXX")); }
ParseUtils { public static boolean isMatchGlobPatternsNeedInterpolate( Collection<String> patternsNeedInterpolate, Map<String, String> interpolateParams, String value) { if (patternsNeedInterpolate != null && !patternsNeedInterpolate.isEmpty()) { for (String patternNeedItp : patternsNeedInterpolate) { if (StringUtils.isEmpty(patternNeedItp)) { continue; } String pattern = interpolate(patternNeedItp, interpolateParams); if (isMatchGlobPattern(pattern, value)) { return true; } } } return false; } private ParseUtils(); static String interpolate(String expression, Map<String, String> params); static List<String> interpolate(List<String> expressions, Map<String, String> params); static boolean isMatchGlobPattern(String pattern, String value); static boolean isMatchGlobPatternsNeedInterpolate( Collection<String> patternsNeedInterpolate, Map<String, String> interpolateParams, String value); static Set<String> filterByGlobPattern(String pattern, Collection<String> values); static Set<String> filterByGlobPattern(Collection<String> patterns, Collection<String> values); static boolean hasIntersection(String glob1, String glob2); static Map<String, String> parseQuery(String keyPrefix, String query); static Map<String, String> parseQuery(String query); static String replaceParameter(String query, String key, String value); static String appendParamToUri(String uri, String name, String value); static String appendParamsToUri(String uri, Map<String, String> params); static boolean matchEndStarPattern(String value, String pattern); static String METHOD_SPLIT; }
@Test public void testIsMatchGlobPatternsNeedInterpolate() throws Exception { Collection<String> patternsNeedInterpolate = new HashSet<String>(); Map<String, String> interpolateParams = new HashMap<String, String>(); boolean match = ParseUtils.isMatchGlobPatternsNeedInterpolate(patternsNeedInterpolate, interpolateParams, "abc"); assertFalse(match); patternsNeedInterpolate.add("abc*$var1"); patternsNeedInterpolate.add("123${var2}*"); interpolateParams.put("var1", "CAT"); interpolateParams.put("var2", "DOG"); match = ParseUtils.isMatchGlobPatternsNeedInterpolate(patternsNeedInterpolate, interpolateParams, "abc"); assertFalse(match); match = ParseUtils.isMatchGlobPatternsNeedInterpolate(patternsNeedInterpolate, interpolateParams, "abcXXXCAT"); assertTrue(match); match = ParseUtils.isMatchGlobPatternsNeedInterpolate(patternsNeedInterpolate, interpolateParams, "123DOGYYY"); assertTrue(match); }
ParseUtils { public static boolean hasIntersection(String glob1, String glob2) { if (null == glob1 || null == glob2) { return false; } if (glob1.contains("*") && glob2.contains("*")) { int index1 = glob1.indexOf("*"); int index2 = glob2.indexOf("*"); String s11 = glob1.substring(0, index1); String s12 = glob1.substring(index1 + 1, glob1.length()); String s21 = glob2.substring(0, index2); String s22 = glob2.substring(index2 + 1, glob2.length()); if (!s11.startsWith(s21) && !s21.startsWith(s11)) return false; if (!s12.endsWith(s22) && !s22.endsWith(s12)) return false; return true; } else if (glob1.contains("*")) { return isMatchGlobPattern(glob1, glob2); } else if (glob2.contains("*")) { return isMatchGlobPattern(glob2, glob1); } else { return glob1.equals(glob2); } } private ParseUtils(); static String interpolate(String expression, Map<String, String> params); static List<String> interpolate(List<String> expressions, Map<String, String> params); static boolean isMatchGlobPattern(String pattern, String value); static boolean isMatchGlobPatternsNeedInterpolate( Collection<String> patternsNeedInterpolate, Map<String, String> interpolateParams, String value); static Set<String> filterByGlobPattern(String pattern, Collection<String> values); static Set<String> filterByGlobPattern(Collection<String> patterns, Collection<String> values); static boolean hasIntersection(String glob1, String glob2); static Map<String, String> parseQuery(String keyPrefix, String query); static Map<String, String> parseQuery(String query); static String replaceParameter(String query, String key, String value); static String appendParamToUri(String uri, String name, String value); static String appendParamsToUri(String uri, Map<String, String> params); static boolean matchEndStarPattern(String value, String pattern); static String METHOD_SPLIT; }
@Test public void test_hasIntersection() throws Exception { assertFalse(ParseUtils.hasIntersection(null, null)); assertFalse(ParseUtils.hasIntersection("dog", null)); assertFalse(ParseUtils.hasIntersection(null, "god")); assertTrue(ParseUtils.hasIntersection("hello", "hello*")); assertTrue(ParseUtils.hasIntersection("helloxxx", "hello*")); assertTrue(ParseUtils.hasIntersection("world", "*world")); assertTrue(ParseUtils.hasIntersection("xxxworld", "*world")); assertTrue(ParseUtils.hasIntersection("helloworld", "hello*world")); assertTrue(ParseUtils.hasIntersection("helloxxxworld", "hello*world")); assertFalse(ParseUtils.hasIntersection("Yhelloxxxworld", "hello*world")); assertTrue(ParseUtils.hasIntersection("hello*", "hello")); assertTrue(ParseUtils.hasIntersection("hello*", "helloxxx")); assertTrue(ParseUtils.hasIntersection("*world", "world")); assertTrue(ParseUtils.hasIntersection("*world", "xxxworld")); assertTrue(ParseUtils.hasIntersection("hello*world", "helloworld")); assertTrue(ParseUtils.hasIntersection("hello*world", "helloxxxworld")); assertFalse(ParseUtils.hasIntersection("hello*world", "Yhelloxxxworld")); assertTrue(ParseUtils.hasIntersection("*world", "hello*world")); assertTrue(ParseUtils.hasIntersection("*world", "hello*Zworld")); assertTrue(ParseUtils.hasIntersection("helloZ*", "hello*world")); assertFalse(ParseUtils.hasIntersection("Zhello*", "hello*world")); assertFalse(ParseUtils.hasIntersection("hello*world", "hello*worldZ")); assertTrue(ParseUtils.hasIntersection("hello*world", "hello*world")); assertTrue(ParseUtils.hasIntersection("hello*world", "hello*Zworld")); assertTrue(ParseUtils.hasIntersection("helloZ*world", "hello*world")); assertFalse(ParseUtils.hasIntersection("Zhello*world", "hello*world")); assertFalse(ParseUtils.hasIntersection("hello*world", "hello*worldZ")); }
ParseUtils { public static Set<String> filterByGlobPattern(String pattern, Collection<String> values) { Set<String> ret = new HashSet<String>(); if (pattern == null || values == null) { return ret; } for (String v : values) { if (isMatchGlobPattern(pattern, v)) { ret.add(v); } } return ret; } private ParseUtils(); static String interpolate(String expression, Map<String, String> params); static List<String> interpolate(List<String> expressions, Map<String, String> params); static boolean isMatchGlobPattern(String pattern, String value); static boolean isMatchGlobPatternsNeedInterpolate( Collection<String> patternsNeedInterpolate, Map<String, String> interpolateParams, String value); static Set<String> filterByGlobPattern(String pattern, Collection<String> values); static Set<String> filterByGlobPattern(Collection<String> patterns, Collection<String> values); static boolean hasIntersection(String glob1, String glob2); static Map<String, String> parseQuery(String keyPrefix, String query); static Map<String, String> parseQuery(String query); static String replaceParameter(String query, String key, String value); static String appendParamToUri(String uri, String name, String value); static String appendParamsToUri(String uri, Map<String, String> params); static boolean matchEndStarPattern(String value, String pattern); static String METHOD_SPLIT; }
@Test public void testFilterByGlobPattern() throws Exception { Collection<String> values = new ArrayList<String>(); values.add("abc123"); values.add("JQKxyz"); values.add("abc123"); values.add("abcLLL"); Set<String> filter = ParseUtils.filterByGlobPattern("abc*", values); Set<String> expected = new HashSet<String>(); expected.add("abc123"); expected.add("abcLLL"); assertEquals(expected, filter); filter = ParseUtils.filterByGlobPattern((Collection<String>) null, values); assertTrue(filter.isEmpty()); Collection<String> patterns = new ArrayList<String>(); patterns.add("000000000"); patterns.add("abc*"); patterns.add("*xyz"); filter = ParseUtils.filterByGlobPattern(patterns, values); expected.add("JQKxyz"); assertEquals(expected, filter); }
RouteUtils { public static boolean matchRoute(String consumerAddress, String consumerQueryUrl, Route route, Map<String, List<String>> clusters) { RouteRule rule = RouteRule.parseQuitely(route); Map<String, RouteRule.MatchPair> when = RouteRuleUtils.expandCondition( rule.getWhenCondition(), "consumer.cluster", "consumer.host", clusters); Map<String, String> consumerSample = ParseUtils.parseQuery("consumer.", consumerQueryUrl); final int index = consumerAddress.lastIndexOf(":"); String consumerHost = null; if (index != -1) { consumerHost = consumerAddress.substring(0, index); } else { consumerHost = consumerAddress; } consumerSample.put("consumer.host", consumerHost); return RouteRuleUtils.isMatchCondition(when, consumerSample, consumerSample); } static boolean matchRoute(String consumerAddress, String consumerQueryUrl, Route route, Map<String, List<String>> clusters); static Map<String, String> previewRoute(String serviceName, String consumerAddress, String queryUrl, Map<String, String> serviceUrls, Route route, Map<String, List<String>> clusters, List<Route> routed); static List<Route> findUsedRoute(String serviceName, String consumerAddress, String consumerQueryUrl, List<Route> routes, Map<String, List<String>> clusters); static List<Provider> route(String serviceName, String consumerAddress, String consumerQueryUrl, List<Provider> providers, List<Override> overrides, List<Route> routes, Map<String, List<String>> clusters, List<Route> routed); static Map<String, String> route(String serviceName, String consumerAddress, String consumerQueryUrl, Map<String, String> serviceUrls, List<Route> routes, Map<String, List<String>> clusters, List<Route> routed); }
@Test public void test_matchRoute() throws Exception { Route route = new Route(); route.setId(1L); route.setPriority(3); route.setMatchRule("consumer.host = 1.1.2.2"); route.setFilterRule("xxx = yyy"); routes.add(route); { assertTrue(RouteUtils.matchRoute("1.1.2.2:20880", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&application=kylin", route, clusters)); assertFalse(RouteUtils.matchRoute("9.9.9.9", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&application=kylin", route, clusters)); route.setMatchRule("consumer.host = 1.1.2.2 & consumer.application = kylin"); assertTrue(RouteUtils.matchRoute("1.1.2.2", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&application=kylin", route, clusters)); route.setMatchRule("consumer.host = 1.1.2.2 & consumer.application = notExstied"); assertFalse(RouteUtils.matchRoute("1.1.2.2", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&methods=getPort,say&application=kylin", route, clusters)); } { route.setMatchRule("consumer.cluster = cluster1"); assertTrue(RouteUtils.matchRoute("7.7.7.7:20880", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&application=kylin", route, clusters)); assertFalse(RouteUtils.matchRoute("9.9.9.9", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&application=kylin", route, clusters)); route.setMatchRule("consumer.cluster = cluster1 & consumer.application = kylin"); assertTrue(RouteUtils.matchRoute("7.7.7.7", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&application=kylin", route, clusters)); route.setMatchRule("consumer.cluster = cluster1 & consumer.application = notExstied"); assertFalse(RouteUtils.matchRoute("7.7.7.7", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&methods=getPort,say&application=kylin", route, clusters)); } }
RouteUtils { public static Map<String, String> previewRoute(String serviceName, String consumerAddress, String queryUrl, Map<String, String> serviceUrls, Route route, Map<String, List<String>> clusters, List<Route> routed) { if (null == route) { throw new IllegalArgumentException("Route is null."); } List<Route> routes = new ArrayList<Route>(); routes.add(route); return route(serviceName, consumerAddress, queryUrl, serviceUrls, routes, clusters, routed); } static boolean matchRoute(String consumerAddress, String consumerQueryUrl, Route route, Map<String, List<String>> clusters); static Map<String, String> previewRoute(String serviceName, String consumerAddress, String queryUrl, Map<String, String> serviceUrls, Route route, Map<String, List<String>> clusters, List<Route> routed); static List<Route> findUsedRoute(String serviceName, String consumerAddress, String consumerQueryUrl, List<Route> routes, Map<String, List<String>> clusters); static List<Provider> route(String serviceName, String consumerAddress, String consumerQueryUrl, List<Provider> providers, List<Override> overrides, List<Route> routes, Map<String, List<String>> clusters, List<Route> routed); static Map<String, String> route(String serviceName, String consumerAddress, String consumerQueryUrl, Map<String, String> serviceUrls, List<Route> routes, Map<String, List<String>> clusters, List<Route> routed); }
@Test public void test_previewRoute() throws Exception { Route route = new Route(); route.setId(1L); route.setService("hello.HelloService"); route.setMatchRule("consumer.host=1.1.2.2,2.2.2.3"); route.setFilterRule("provider.host=3.3.4.4&provider.application=morgan"); { Map<String, String> preview = RouteUtils.previewRoute("hello.HelloService", "1.1.2.2:20880", "application=morgan", serviceUrls, route, clusters, null); Map<String, String> expected = new HashMap<String, String>(); expected.put("dubbo: assertEquals(expected, preview); preview = RouteUtils.previewRoute("hello.HelloService", "1.1.2.2", "application=morgan&methods=getPort,say", serviceUrls, route, clusters, null); expected = new HashMap<String, String>(); expected.put("dubbo: assertEquals(expected, preview); preview = RouteUtils.previewRoute("hello.HelloService", "1.1.2.2", "application=morgan&methods=getPort,say,ghostMethod", serviceUrls, route, clusters, null); expected = new HashMap<String, String>(); expected.put("dubbo: assertEquals(expected, preview); preview = RouteUtils.previewRoute("hello.HelloService", "1.2.3.4", "application=morgan", serviceUrls, route, clusters, null); assertEquals(serviceUrls_starMethods, preview); preview = RouteUtils.previewRoute("hello.HelloService", "1.2.3.4", "application=morgan&methods=getPort,say", serviceUrls, route, clusters, null); assertEquals(serviceUrls, preview); preview = RouteUtils.previewRoute("hello.HelloService", "1.2.3.4", "application=morgan&methods=getPort,say,ghostMethod", serviceUrls, route, clusters, null); assertEquals(serviceUrls_ghostMethods, preview); } { route.setMatchRule("consumer.cluster = cluster1"); Map<String, String> preview = RouteUtils.previewRoute("hello.HelloService", "7.7.7.7:20880", "application=morgan", serviceUrls, route, clusters, null); Map<String, String> expected = new HashMap<String, String>(); expected.put("dubbo: assertEquals(expected, preview); preview = RouteUtils.previewRoute("hello.HelloService", "7.7.7.7", "application=morgan&methods=getPort,say", serviceUrls, route, clusters, null); expected = new HashMap<String, String>(); expected.put("dubbo: assertEquals(expected, preview); preview = RouteUtils.previewRoute("hello.HelloService", "7.7.7.7", "application=morgan&methods=getPort,say,ghostMethod", serviceUrls, route, clusters, null); expected = new HashMap<String, String>(); expected.put("dubbo: assertEquals(expected, preview); preview = RouteUtils.previewRoute("hello.HelloService", "1.2.3.4", "application=morgan", serviceUrls, route, clusters, null); assertEquals(serviceUrls_starMethods, preview); preview = RouteUtils.previewRoute("hello.HelloService", "1.2.3.4", "application=morgan&methods=getPort,say", serviceUrls, route, clusters, null); assertEquals(serviceUrls, preview); preview = RouteUtils.previewRoute("hello.HelloService", "1.2.3.4", "application=morgan&methods=getPort,say,ghostMethod", serviceUrls, route, clusters, null); assertEquals(serviceUrls_ghostMethods, preview); } }
RouteUtils { public static List<Provider> route(String serviceName, String consumerAddress, String consumerQueryUrl, List<Provider> providers, List<Override> overrides, List<Route> routes, Map<String, List<String>> clusters, List<Route> routed) { if (providers == null) { return null; } Map<String, String> urls = new HashMap<String, String>(); urls.put("consumer: for (Provider provider : providers) { if (com.alibaba.dubbo.governance.web.common.pulltool.Tool.isProviderEnabled(provider, overrides)) { urls.put(provider.getUrl(), provider.getParameters()); } } urls = RouteUtils.route(serviceName, consumerAddress, consumerQueryUrl, urls, routes, clusters, routed); List<Provider> result = new ArrayList<Provider>(); for (Provider provider : providers) { if (urls.containsKey(provider.getUrl())) { result.add(provider); } } return result; } static boolean matchRoute(String consumerAddress, String consumerQueryUrl, Route route, Map<String, List<String>> clusters); static Map<String, String> previewRoute(String serviceName, String consumerAddress, String queryUrl, Map<String, String> serviceUrls, Route route, Map<String, List<String>> clusters, List<Route> routed); static List<Route> findUsedRoute(String serviceName, String consumerAddress, String consumerQueryUrl, List<Route> routes, Map<String, List<String>> clusters); static List<Provider> route(String serviceName, String consumerAddress, String consumerQueryUrl, List<Provider> providers, List<Override> overrides, List<Route> routes, Map<String, List<String>> clusters, List<Route> routed); static Map<String, String> route(String serviceName, String consumerAddress, String consumerQueryUrl, Map<String, String> serviceUrls, List<Route> routes, Map<String, List<String>> clusters, List<Route> routed); }
@Test public void testRoute() throws Exception { { Map<String, String> result = RouteUtils.route("hello.HelloService:1.0.0", "1.1.2.2:20880", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&application=kylin", serviceUrls, routes, clusters, null); Map<String, String> expected = new HashMap<String, String>(); expected.put("dubbo: assertEquals(expected, result); result = RouteUtils.route("cn/hello.HelloService", "1.1.2.2", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&methods=getPort,say&application=kylin", serviceUrls, routes, clusters, null); expected = new HashMap<String, String>(); expected.put("dubbo: assertEquals(expected, result); result = RouteUtils.route("cn/hello.HelloService:2.0.0", "1.1.2.2", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&methods=getPort,say,ghostMethod&application=kylin", serviceUrls, routes, clusters, null); expected = new HashMap<String, String>(); expected.put("dubbo: assertEquals(expected, result); result = RouteUtils.route("hello.HelloService", "1.2.3.4", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&application=kylin", serviceUrls, routes, clusters, null); assertEquals(serviceUrls_starMethods, result); result = RouteUtils.route("hello.HelloService", "1.2.3.4", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&methods=getPort,say&application=kylin", serviceUrls, routes, clusters, null); assertEquals(serviceUrls, result); result = RouteUtils.route("hello.HelloService", "1.2.3.4", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&methods=getPort,say,ghostMethod&application=kylin", serviceUrls, routes, clusters, null); assertEquals(serviceUrls_ghostMethods, result); } { routes.get(0).setMatchRule("consumer.cluster = cluster1"); Map<String, String> result = RouteUtils.route("hello.HelloService", "7.7.7.7:20880", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&application=kylin", serviceUrls, routes, clusters, null); Map<String, String> expected = new HashMap<String, String>(); expected.put("dubbo: assertEquals(expected, result); result = RouteUtils.route("hello.HelloService", "7.7.7.7", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&methods=getPort,say&application=kylin", serviceUrls, routes, clusters, null); expected = new HashMap<String, String>(); expected.put("dubbo: assertEquals(expected, result); result = RouteUtils.route("hello.HelloService", "7.7.7.7", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&methods=getPort,say,ghostMethod&application=kylin", serviceUrls, routes, clusters, null); expected = new HashMap<String, String>(); expected.put("dubbo: assertEquals(expected, result); result = RouteUtils.route("hello.HelloService", "1.2.3.4", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&application=kylin", serviceUrls, routes, clusters, null); assertEquals(serviceUrls_starMethods, result); result = RouteUtils.route("hello.HelloService", "1.2.3.4", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&methods=getPort,say&application=kylin", serviceUrls, routes, clusters, null); assertEquals(serviceUrls, result); result = RouteUtils.route("hello.HelloService", "1.2.3.4", "dubbo=2.0.0&version=3.0.0&revision=3.0.0&methods=getPort,say,ghostMethod&application=kylin", serviceUrls, routes, clusters, null); assertEquals(serviceUrls_ghostMethods, result); } }
MockClusterInvoker implements Invoker<T> { public Result invoke(Invocation invocation) throws RpcException { Result result = null; String value = directory .getUrl() .getMethodParameter(invocation.getMethodName(), Constants.MOCK_KEY, Boolean.FALSE.toString()).trim(); if (value.length() == 0 || value.equalsIgnoreCase("false")) { result = this.invoker.invoke(invocation); } else if (value.startsWith("force")) { if (logger.isWarnEnabled()) { logger.info("force-mock: " + invocation.getMethodName() + " force-mock enabled , url : " + directory.getUrl()); } result = doMockInvoke(invocation, null); } else { try { String SF = "no"; String errorrate = directory .getUrl() .getMethodParameter(invocation.getMethodName(), Constants.ERRORRATE_KEY, Boolean.FALSE.toString()).trim(); String supervene = directory .getUrl() .getMethodParameter(invocation.getMethodName(), Constants.SUPERVENE_KEY, Boolean.FALSE.toString()).trim(); if (Float.parseFloat(errorrate) != 0 || Integer.parseInt(supervene) != 0) { SF = fuseCount(errorrate, supervene, "before",(long)-1,invocation.getMethodName()); } if (SF.equals("fail")) { result = doMockInvoke(invocation, null); return result; } if (SF.equals("no")) { result = this.invoker.invoke(invocation); } if (SF.equals("success")) { long timeBefore = System.currentTimeMillis(); result = this.invoker.invoke(invocation); long time = System.currentTimeMillis()-timeBefore; fuseCount(errorrate, supervene, "after",time,invocation.getMethodName()); } } catch (RpcException e) { if (e.isBiz()) { throw e; } else { if (logger.isWarnEnabled()) { logger.info( "fail-mock: " + invocation.getMethodName() + " fail-mock enabled , url : " + directory.getUrl(), e); } result = doMockInvoke(invocation, e); } } } return result; } MockClusterInvoker(Directory<T> directory, Invoker<T> invoker); URL getUrl(); boolean isAvailable(); void destroy(); Class<T> getInterface(); Result invoke(Invocation invocation); @Override String toString(); String fuseCount(String errorrate, String supervene, String status,Long time,String methodName); }
@Test public void testMockInvokerInvoke_normal() { URL url = URL.valueOf("remote: url = url.addParameter(Constants.MOCK_KEY, "fail"); Invoker<IHelloService> cluster = getClusterInvoker(url); URL mockUrl = URL.valueOf("mock: + "?getSomething.mock=return aa"); Protocol protocol = new MockProtocol(); Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl); invokers.add(mInvoker1); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertEquals("something", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assert.assertEquals(null, ret.getValue()); } @Test public void testMockInvokerInvoke_failmock() { URL url = URL.valueOf("remote: .addParameter(Constants.MOCK_KEY, "fail:return null") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); URL mockUrl = URL.valueOf("mock: + "?getSomething.mock=return aa").addParameters(url.getParameters()); Protocol protocol = new MockProtocol(); Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl); invokers.add(mInvoker1); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertEquals("aa", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assert.assertEquals(null, ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assert.assertEquals(null, ret.getValue()); } @Test public void testMockInvokerInvoke_forcemock() { URL url = URL.valueOf("remote: url = url.addParameter(Constants.MOCK_KEY, "force:return null"); Invoker<IHelloService> cluster = getClusterInvoker(url); URL mockUrl = URL.valueOf("mock: + "?getSomething.mock=return aa&getSomething3xx.mock=return xx") .addParameters(url.getParameters()); Protocol protocol = new MockProtocol(); Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl); invokers.add(mInvoker1); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertEquals("aa", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assert.assertEquals(null, ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assert.assertEquals(null, ret.getValue()); } @Test public void testMockInvokerInvoke_forcemock_defaultreturn() { URL url = URL.valueOf("remote: url = url.addParameter(Constants.MOCK_KEY, "force"); Invoker<IHelloService> cluster = getClusterInvoker(url); URL mockUrl = URL.valueOf("mock: + "?getSomething.mock=return aa&getSomething3xx.mock=return xx&sayHello.mock=return ") .addParameters(url.getParameters()); Protocol protocol = new MockProtocol(); Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl); invokers.add(mInvoker1); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); Result ret = cluster.invoke(invocation); Assert.assertEquals(null, ret.getValue()); } @Test public void testMockInvokerFromOverride_Invoke_Fock_someMethods() { URL url = URL.valueOf("remote: .addParameter("getSomething.mock", "fail:return x") .addParameter("getSomething2.mock", "force:return y"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertEquals("something", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assert.assertEquals("y", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); ret = cluster.invoke(invocation); Assert.assertEquals("something3", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assert.assertEquals(null, ret.getValue()); } @Test public void testMockInvokerFromOverride_Invoke_Fock_WithOutDefault() { URL url = URL.valueOf("remote: .addParameter("getSomething.mock", "fail:return x") .addParameter("getSomething2.mock", "force:return y") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertEquals("x", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assert.assertEquals("y", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); try { ret = cluster.invoke(invocation); Assert.fail(); } catch (RpcException e) { } } @Test public void testMockInvokerFromOverride_Invoke_Fock_WithDefault() { URL url = URL.valueOf("remote: .addParameter("mock", "fail:return null") .addParameter("getSomething.mock", "fail:return x") .addParameter("getSomething2.mock", "force:return y") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertEquals("x", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assert.assertEquals("y", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); ret = cluster.invoke(invocation); Assert.assertEquals(null, ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assert.assertEquals(null, ret.getValue()); } @Test public void testMockInvokerFromOverride_Invoke_Fock_WithFailDefault() { URL url = URL.valueOf("remote: .addParameter("mock", "fail:return z") .addParameter("getSomething.mock", "fail:return x") .addParameter("getSomething2.mock", "force:return y") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertEquals("x", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assert.assertEquals("y", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); ret = cluster.invoke(invocation); Assert.assertEquals("z", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assert.assertEquals("z", ret.getValue()); } @Test public void testMockInvokerFromOverride_Invoke_Fock_WithForceDefault() { URL url = URL.valueOf("remote: .addParameter("mock", "force:return z") .addParameter("getSomething.mock", "fail:return x") .addParameter("getSomething2.mock", "force:return y") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertEquals("x", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assert.assertEquals("y", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); ret = cluster.invoke(invocation); Assert.assertEquals("z", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assert.assertEquals("z", ret.getValue()); } @Test public void testMockInvokerFromOverride_Invoke_Fock_Default() { URL url = URL.valueOf("remote: .addParameter("mock", "fail:return x") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertEquals("x", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assert.assertEquals("x", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assert.assertEquals("x", ret.getValue()); } @Test public void testMockInvokerFromOverride_Invoke_checkCompatible_return() { URL url = URL.valueOf("remote: .addParameter("getSomething.mock", "return x") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertEquals("x", ret.getValue()); invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); try { ret = cluster.invoke(invocation); Assert.fail("fail invoke"); } catch (RpcException e) { } } @Test public void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock() { URL url = URL.valueOf("remote: .addParameter("mock", "true") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertEquals("somethingmock", ret.getValue()); } @Test public void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock2() { URL url = URL.valueOf("remote: .addParameter("mock", "fail") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertEquals("somethingmock", ret.getValue()); } @Test public void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock3() { URL url = URL.valueOf("remote: .addParameter("mock", "force"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertEquals("somethingmock", ret.getValue()); } @Test public void testMockInvokerFromOverride_Invoke_check_String() { URL url = URL.valueOf("remote: .addParameter("getSomething.mock", "force:return 1688") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertTrue("result type must be String but was : " + ret.getValue().getClass(), ret.getValue() instanceof String); Assert.assertEquals("1688", (String) ret.getValue()); } @Test public void testMockInvokerFromOverride_Invoke_check_int() { URL url = URL.valueOf("remote: .addParameter("getInt1.mock", "force:return 1688") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getInt1"); Result ret = cluster.invoke(invocation); Assert.assertTrue("result type must be integer but was : " + ret.getValue().getClass(), ret.getValue() instanceof Integer); Assert.assertEquals(new Integer(1688), (Integer) ret.getValue()); } @SuppressWarnings("unchecked") @Test public void testMockInvokerFromOverride_Invoke_check_ListString_empty() { URL url = URL.valueOf("remote: .addParameter("getListString.mock", "force:return empty") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getListString"); Result ret = cluster.invoke(invocation); Assert.assertEquals(0, ((List<String>) ret.getValue()).size()); } @SuppressWarnings("unchecked") @Test public void testMockInvokerFromOverride_Invoke_check_ListString() { URL url = URL.valueOf("remote: .addParameter("getListString.mock", "force:return [\"hi\",\"hi2\"]") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getListString"); Result ret = cluster.invoke(invocation); List<String> rl = (List<String>) ret.getValue(); Assert.assertEquals(2, rl.size()); Assert.assertEquals("hi", rl.get(0)); } @SuppressWarnings("unchecked") @Test public void testMockInvokerFromOverride_Invoke_check_ListPojo_empty() { URL url = URL.valueOf("remote: .addParameter("getUsers.mock", "force:return empty") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getUsers"); Result ret = cluster.invoke(invocation); Assert.assertEquals(0, ((List<User>) ret.getValue()).size()); } @SuppressWarnings("unchecked") @Test public void testMockInvokerFromOverride_Invoke_check_ListPojo() { URL url = URL.valueOf("remote: .addParameter("getUsers.mock", "force:return [{id:1, name:\"hi1\"}, {id:2, name:\"hi2\"}]") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getUsers"); Result ret = cluster.invoke(invocation); List<User> rl = (List<User>) ret.getValue(); System.out.println(rl); Assert.assertEquals(2, rl.size()); Assert.assertEquals("hi1", ((User) rl.get(0)).getName()); } @Test public void testMockInvokerFromOverride_Invoke_check_ListPojo_error() { URL url = URL.valueOf("remote: .addParameter("getUsers.mock", "force:return [{id:x, name:\"hi1\"}]") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getUsers"); try { cluster.invoke(invocation); } catch (RpcException e) { } } @Test public void testMockInvokerFromOverride_Invoke_force_throw() { URL url = URL.valueOf("remote: .addParameter("getBoolean2.mock", "force:throw ") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); try { cluster.invoke(invocation); Assert.fail(); } catch (RpcException e) { Assert.assertFalse("not custem exception", e.isBiz()); } } @Test public void testMockInvokerFromOverride_Invoke_force_throwCustemException() throws Throwable { URL url = URL.valueOf("remote: .addParameter("getBoolean2.mock", "force:throw com.alibaba.dubbo.rpc.cluster.support.wrapper.MyMockException") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); try { cluster.invoke(invocation).recreate(); Assert.fail(); } catch (MyMockException e) { } } @Test public void testMockInvokerFromOverride_Invoke_force_throwCustemExceptionNotFound() { URL url = URL.valueOf("remote: .addParameter("getBoolean2.mock", "force:throw java.lang.RuntimeException2") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); try { cluster.invoke(invocation); Assert.fail(); } catch (Exception e) { Assert.assertTrue(e.getCause() instanceof IllegalStateException); } } @Test public void testMockInvokerFromOverride_Invoke_mock_false() { URL url = URL.valueOf("remote: .addParameter("mock", "false") .addParameter("invoke_return_error", "true"); Invoker<IHelloService> cluster = getClusterInvoker(url); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); try { cluster.invoke(invocation); Assert.fail(); } catch (RpcException e) { Assert.assertTrue(e.isTimeout()); } }
RouteUtils { static boolean isSerivceNameMatched(String servicePattern, String serviceName) { final int pip = servicePattern.indexOf('/'); final int pi = serviceName.indexOf('/'); if (pip != -1) { if (pi == -1) return false; String gp = servicePattern.substring(0, pip); servicePattern = servicePattern.substring(pip + 1); String g = serviceName.substring(0, pi); if (!gp.equals(g)) return false; } if (pi != -1) serviceName = serviceName.substring(pi + 1); final int vip = servicePattern.lastIndexOf(':'); final int vi = serviceName.lastIndexOf(':'); if (vip != -1) { if (vi == -1) return false; String vp = servicePattern.substring(vip + 1); servicePattern = servicePattern.substring(0, vip); String v = serviceName.substring(vi + 1); if (!vp.equals(v)) return false; } if (vi != -1) serviceName = serviceName.substring(0, vi); return ParseUtils.isMatchGlobPattern(servicePattern, serviceName); } static boolean matchRoute(String consumerAddress, String consumerQueryUrl, Route route, Map<String, List<String>> clusters); static Map<String, String> previewRoute(String serviceName, String consumerAddress, String queryUrl, Map<String, String> serviceUrls, Route route, Map<String, List<String>> clusters, List<Route> routed); static List<Route> findUsedRoute(String serviceName, String consumerAddress, String consumerQueryUrl, List<Route> routes, Map<String, List<String>> clusters); static List<Provider> route(String serviceName, String consumerAddress, String consumerQueryUrl, List<Provider> providers, List<Override> overrides, List<Route> routes, Map<String, List<String>> clusters, List<Route> routed); static Map<String, String> route(String serviceName, String consumerAddress, String consumerQueryUrl, Map<String, String> serviceUrls, List<Route> routes, Map<String, List<String>> clusters, List<Route> routed); }
@Test public void test_isSerivceNameMatched() throws Exception { assertTrue(RouteUtils.isSerivceNameMatched("com.alibaba.morgan.MemberService", "com.alibaba.morgan.MemberService:1.0.0")); assertTrue(RouteUtils.isSerivceNameMatched("com.alibaba.morgan.MemberService", "cn/com.alibaba.morgan.MemberService:1.0.0")); assertTrue(RouteUtils.isSerivceNameMatched("com.alibaba.morgan.MemberService", "cn/com.alibaba.morgan.MemberService")); assertTrue(RouteUtils.isSerivceNameMatched("com.alibaba.morgan.MemberService", "com.alibaba.morgan.MemberService")); assertTrue(RouteUtils.isSerivceNameMatched("com.alibaba.morgan.Member*", "com.alibaba.morgan.MemberService:1.0.0")); assertTrue(RouteUtils.isSerivceNameMatched("com.alibaba.morgan.Member*", "cn/com.alibaba.morgan.MemberService:1.0.0")); assertTrue(RouteUtils.isSerivceNameMatched("com.alibaba.morgan.Member*", "cn/com.alibaba.morgan.MemberService")); assertTrue(RouteUtils.isSerivceNameMatched("com.alibaba.morgan.Member*", "com.alibaba.morgan.MemberService")); assertFalse(RouteUtils.isSerivceNameMatched("cn/com.alibaba.morgan.Member*", "com.alibaba.morgan.MemberService:1.0.0")); assertTrue(RouteUtils.isSerivceNameMatched("cn/com.alibaba.morgan.MemberService", "cn/com.alibaba.morgan.MemberService:1.0.0")); assertTrue(RouteUtils.isSerivceNameMatched("cn/com.alibaba.morgan.Member*", "cn/com.alibaba.morgan.MemberService")); assertFalse(RouteUtils.isSerivceNameMatched("cn/com.alibaba.morgan.Member*", "intl/com.alibaba.morgan.MemberService")); assertFalse(RouteUtils.isSerivceNameMatched("cn/com.alibaba.morgan.Member*", "com.alibaba.morgan.MemberService")); assertTrue(RouteUtils.isSerivceNameMatched("com.alibaba.morgan.Member*:1.0.0", "com.alibaba.morgan.MemberService:1.0.0")); assertTrue(RouteUtils.isSerivceNameMatched("com.alibaba.morgan.MemberService:1.0.0", "cn/com.alibaba.morgan.MemberService:1.0.0")); assertFalse(RouteUtils.isSerivceNameMatched("com.alibaba.morgan.MemberService:1.0.0", "cn/com.alibaba.morgan.MemberService:2.0.0")); assertFalse(RouteUtils.isSerivceNameMatched("com.alibaba.morgan.Member*:1.0.0", "cn/com.alibaba.morgan.MemberService")); assertFalse(RouteUtils.isSerivceNameMatched("com.alibaba.morgan.Member*:1.0.0", "com.alibaba.morgan.MemberService")); }
PageList implements Serializable { public int getPageCount() { int lim = limit; if (limit < 1) { lim = 1; } int page = total / lim; if (page < 1) { return 1; } int remain = total % lim; if (remain > 0) { page += 1; } return page; } PageList(); PageList(int start, int limit, int total, List<T> list); int getStart(); void setStart(int start); int getLimit(); void setLimit(int limit); int getTotal(); void setTotal(int total); List<T> getList(); void setList(List<T> list); int getPageCount(); }
@Test public void testGetPageCount() { PageList<Object> pl = new PageList<Object>(0, 100, 52, null); Assert.assertEquals(1, pl.getPageCount()); pl = new PageList<Object>(0, -100, -3, null); Assert.assertEquals(1, pl.getPageCount()); pl = new PageList<Object>(0, 30, 100, null); Assert.assertEquals(4, pl.getPageCount()); }
HeartBeatTask implements Runnable { public void run() { try { long now = System.currentTimeMillis(); for (Channel channel : channelProvider.getChannels()) { if (channel.isClosed()) { continue; } try { Long lastRead = (Long) channel.getAttribute( HeaderExchangeHandler.KEY_READ_TIMESTAMP); Long lastWrite = (Long) channel.getAttribute( HeaderExchangeHandler.KEY_WRITE_TIMESTAMP); if ((lastRead != null && now - lastRead > heartbeat) || (lastWrite != null && now - lastWrite > heartbeat)) { Request req = new Request(); req.setVersion("2.0.0"); req.setTwoWay(true); req.setEvent(Request.HEARTBEAT_EVENT); channel.send(req); if (logger.isDebugEnabled()) { logger.debug("Send heartbeat to remote channel " + channel.getRemoteAddress() + ", cause: The channel has no data-transmission exceeds a heartbeat period: " + heartbeat + "ms"); } } if (lastRead != null && now - lastRead > heartbeatTimeout) { logger.warn("Close channel " + channel + ", because heartbeat read idle time out: " + heartbeatTimeout + "ms"); if (channel instanceof Client) { try { ((Client) channel).reconnect(); } catch (Exception e) { } } else { channel.close(); } } } catch (Throwable t) { logger.warn("Exception when heartbeat to remote channel " + channel.getRemoteAddress(), t); } } } catch (Throwable t) { logger.warn("Unhandled exception when heartbeat, cause: " + t.getMessage(), t); } } HeartBeatTask(ChannelProvider provider, int heartbeat, int heartbeatTimeout); void run(); }
@Test public void testHeartBeat() throws Exception { url = url.addParameter(Constants.DUBBO_VERSION_KEY, "2.1.1"); channel.setAttribute( HeaderExchangeHandler.KEY_READ_TIMESTAMP, System.currentTimeMillis()); channel.setAttribute( HeaderExchangeHandler.KEY_WRITE_TIMESTAMP, System.currentTimeMillis()); Thread.sleep(2000L); task.run(); List<Object> objects = channel.getSentObjects(); Assert.assertTrue(objects.size() > 0); Object obj = objects.get(0); Assert.assertTrue(obj instanceof Request); Request request = (Request) obj; Assert.assertTrue(request.isHeartbeat()); }
ReferenceConfigCache { public void destroyAll() { Set<String> set = new HashSet<String>(cache.keySet()); for (String key : set) { destroyKey(key); } } private ReferenceConfigCache(String name, KeyGenerator generator); static ReferenceConfigCache getCache(); static ReferenceConfigCache getCache(String name); static ReferenceConfigCache getCache(String name, KeyGenerator keyGenerator); @SuppressWarnings("unchecked") T get(ReferenceConfig<T> referenceConfig); void destroy(ReferenceConfig<T> referenceConfig); void destroyAll(); @Override String toString(); static final String DEFAULT_NAME; static final KeyGenerator DEFAULT_KEY_GENERATOR; }
@Test public void testDestroyAll() throws Exception { ReferenceConfigCache cache = ReferenceConfigCache.getCache(); MockReferenceConfig config = new MockReferenceConfig(); config.setInterface("FooService"); config.setGroup("group1"); config.setVersion("1.0.0"); cache.get(config); MockReferenceConfig configCopy = new MockReferenceConfig(); configCopy.setInterface("XxxService"); configCopy.setGroup("group1"); configCopy.setVersion("1.0.0"); cache.get(configCopy); assertEquals(2, cache.cache.size()); cache.destroyAll(); assertTrue(config.isDestroyMethodRun()); assertTrue(configCopy.isDestroyMethodRun()); assertEquals(0, cache.cache.size()); }
LogTelnetHandler implements TelnetHandler { public String telnet(Channel channel, String message) { long size = 0; File file = LoggerFactory.getFile(); StringBuffer buf = new StringBuffer(); if (message == null || message.trim().length() == 0) { buf.append("EXAMPLE: log error / log 100"); } else { String str[] = message.split(" "); if (!StringUtils.isInteger(str[0])) { LoggerFactory.setLevel(Level.valueOf(message.toUpperCase())); } else { int SHOW_LOG_LENGTH = Integer.parseInt(str[0]); if (file != null && file.exists()) { try { FileInputStream fis = new FileInputStream(file); FileChannel filechannel = fis.getChannel(); size = filechannel.size(); ByteBuffer bb; if (size <= SHOW_LOG_LENGTH) { bb = ByteBuffer.allocate((int) size); filechannel.read(bb, 0); } else { int pos = (int) (size - SHOW_LOG_LENGTH); bb = ByteBuffer.allocate(SHOW_LOG_LENGTH); filechannel.read(bb, pos); } bb.flip(); String content = new String(bb.array()).replace("<", "&lt;") .replace(">", "&gt;").replace("\n", "<br/><br/>"); buf.append("\r\ncontent:" + content); buf.append("\r\nmodified:" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date(file.lastModified())))); buf.append("\r\nsize:" + size + "\r\n"); } catch (Exception e) { buf.append(e.getMessage()); } } else { size = 0; buf.append("\r\nMESSAGE: log file not exists or log appender is console ."); } } } buf.append("\r\nCURRENT LOG LEVEL:" + LoggerFactory.getLevel()) .append("\r\nCURRENT LOG APPENDER:" + (file == null ? "console" : file.getAbsolutePath())); return buf.toString(); } String telnet(Channel channel, String message); static final String SERVICE_KEY; }
@Test public void testChangeLogLevel() throws RemotingException { mockChannel = EasyMock.createMock(Channel.class); EasyMock.replay(mockChannel); String result = log.telnet(mockChannel, "error"); assertTrue(result.contains("\r\nCURRENT LOG LEVEL:ERROR")); String result2 = log.telnet(mockChannel, "warn"); assertTrue(result2.contains("\r\nCURRENT LOG LEVEL:WARN")); EasyMock.reset(mockChannel); } @Test public void testPrintLog() throws RemotingException { mockChannel = EasyMock.createMock(Channel.class); EasyMock.replay(mockChannel); String result = log.telnet(mockChannel, "100"); assertTrue(result.contains("CURRENT LOG APPENDER")); EasyMock.reset(mockChannel); }
PortTelnetHandler implements TelnetHandler { public String telnet(Channel channel, String message) { StringBuilder buf = new StringBuilder(); String port = null; boolean detail = false; if (message.length() > 0) { String[] parts = message.split("\\s+"); for (String part : parts) { if ("-l".equals(part)) { detail = true; } else { if (!StringUtils.isInteger(part)) { return "Illegal port " + part + ", must be integer."; } port = part; } } } if (port == null || port.length() == 0) { for (ExchangeServer server : DubboProtocol.getDubboProtocol().getServers()) { if (buf.length() > 0) { buf.append("\r\n"); } if (detail) { buf.append(server.getUrl().getProtocol() + ": } else { buf.append(server.getUrl().getPort()); } } } else { int p = Integer.parseInt(port); ExchangeServer server = null; for (ExchangeServer s : DubboProtocol.getDubboProtocol().getServers()) { if (p == s.getUrl().getPort()) { server = s; break; } } if (server != null) { Collection<ExchangeChannel> channels = server.getExchangeChannels(); for (ExchangeChannel c : channels) { if (buf.length() > 0) { buf.append("\r\n"); } if (detail) { buf.append(c.getRemoteAddress() + " -> " + c.getLocalAddress()); } else { buf.append(c.getRemoteAddress()); } } } else { buf.append("No such port " + port); } } return buf.toString(); } String telnet(Channel channel, String message); }
@Test public void testListClient() throws Exception { ExchangeClient client1 = Exchangers.connect("dubbo: ExchangeClient client2 = Exchangers.connect("dubbo: Thread.sleep(5000); String result = port.telnet(null, "-l 20887"); String client1Addr = client1.getLocalAddress().toString(); String client2Addr = client2.getLocalAddress().toString(); System.out.printf("Result: %s %n", result); System.out.printf("Client 1 Address %s %n", client1Addr); System.out.printf("Client 2 Address %s %n", client2Addr); assertTrue(result.contains(client1Addr)); assertTrue(result.contains(client2Addr)); } @Test public void testListDetail() throws RemotingException { String result = port.telnet(null, "-l"); assertEquals("dubbo: } @Test public void testListAllPort() throws RemotingException { String result = port.telnet(null, ""); assertEquals("20887", result); } @Test public void testErrorMessage() throws RemotingException { String result = port.telnet(null, "a"); assertEquals("Illegal port a, must be integer.", result); } @Test public void testNoPort() throws RemotingException { String result = port.telnet(null, "-l 20880"); assertEquals("No such port 20880", result); }
InjvmProtocol extends AbstractProtocol implements Protocol { public boolean isInjvmRefer(URL url) { final boolean isJvmRefer; String scope = url.getParameter(Constants.SCOPE_KEY); if (Constants.LOCAL_PROTOCOL.toString().equals(url.getProtocol())) { isJvmRefer = false; } else if (Constants.SCOPE_LOCAL.equals(scope) || (url.getParameter("injvm", false))) { isJvmRefer = true; } else if (Constants.SCOPE_REMOTE.equals(scope)) { isJvmRefer = false; } else if (url.getParameter(Constants.GENERIC_KEY, false)) { isJvmRefer = false; } else if (getExporter(exporterMap, url) != null) { isJvmRefer = true; } else { isJvmRefer = false; } return isJvmRefer; } InjvmProtocol(); int getDefaultPort(); static InjvmProtocol getInjvmProtocol(); Exporter<T> export(Invoker<T> invoker); Invoker<T> refer(Class<T> serviceType, URL url); boolean isInjvmRefer(URL url); static final String NAME; static final int DEFAULT_PORT; }
@Test public void testIsInjvmRefer() throws Exception { DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm: .addParameter(Constants.INTERFACE_KEY, DemoService.class.getName()); Exporter<?> exporter = protocol.export(proxy.getInvoker(service, DemoService.class, url)); exporters.add(exporter); url = url.setProtocol("dubbo"); assertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url)); url = url.addParameter(Constants.GROUP_KEY, "*") .addParameter(Constants.VERSION_KEY, "*"); assertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url)); }
ThriftCodec implements Codec2 { private void encodeRequest(Channel channel, ChannelBuffer buffer, Request request) throws IOException { RpcInvocation inv = (RpcInvocation) request.getData(); int seqId = nextSeqId(); String serviceName = inv.getAttachment(Constants.INTERFACE_KEY); if (StringUtils.isEmpty(serviceName)) { throw new IllegalArgumentException( new StringBuilder(32) .append("Could not find service name in attachment with key ") .append(Constants.INTERFACE_KEY) .toString()); } TMessage message = new TMessage( inv.getMethodName(), TMessageType.CALL, seqId); String methodArgs = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) .getExtension(channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME)) .generateArgsClassName(serviceName, inv.getMethodName()); if (StringUtils.isEmpty(methodArgs)) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, new StringBuilder(32).append( "Could not encode request, the specified interface may be incorrect.").toString()); } Class<?> clazz = cachedClass.get(methodArgs); if (clazz == null) { try { clazz = ClassHelper.forNameWithThreadContextClassLoader(methodArgs); cachedClass.putIfAbsent(methodArgs, clazz); } catch (ClassNotFoundException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } TBase args; try { args = (TBase) clazz.newInstance(); } catch (InstantiationException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } catch (IllegalAccessException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } for (int i = 0; i < inv.getArguments().length; i++) { Object obj = inv.getArguments()[i]; if (obj == null) { continue; } TFieldIdEnum field = args.fieldForId(i + 1); String setMethodName = ThriftUtils.generateSetMethodName(field.getFieldName()); Method method; try { method = clazz.getMethod(setMethodName, inv.getParameterTypes()[i]); } catch (NoSuchMethodException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } try { method.invoke(args, obj); } catch (IllegalAccessException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } catch (InvocationTargetException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } } RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024); TIOStreamTransport transport = new TIOStreamTransport(bos); TBinaryProtocol protocol = new TBinaryProtocol(transport); int headerLength, messageLength; byte[] bytes = new byte[4]; try { protocol.writeI16(MAGIC); protocol.writeI32(Integer.MAX_VALUE); protocol.writeI16(Short.MAX_VALUE); protocol.writeByte(VERSION); protocol.writeString(serviceName); protocol.writeI64(request.getId()); protocol.getTransport().flush(); headerLength = bos.size(); protocol.writeMessageBegin(message); args.write(protocol); protocol.writeMessageEnd(); protocol.getTransport().flush(); int oldIndex = messageLength = bos.size(); try { TFramedTransport.encodeFrameSize(messageLength, bytes); bos.setWriteIndex(MESSAGE_LENGTH_INDEX); protocol.writeI32(messageLength); bos.setWriteIndex(MESSAGE_HEADER_LENGTH_INDEX); protocol.writeI16((short) (0xffff & headerLength)); } finally { bos.setWriteIndex(oldIndex); } } catch (TException e) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); } buffer.writeBytes(bytes); buffer.writeBytes(bos.toByteArray()); } void encode(Channel channel, ChannelBuffer buffer, Object message); Object decode(Channel channel, ChannelBuffer buffer); static final int MESSAGE_LENGTH_INDEX; static final int MESSAGE_HEADER_LENGTH_INDEX; static final int MESSAGE_SHORTEST_LENGTH; static final String NAME; static final String PARAMETER_CLASS_NAME_GENERATOR; static final byte VERSION; static final short MAGIC; }
@Test public void testEncodeRequest() throws Exception { Request request = createRequest(); ChannelBuffer output = ChannelBuffers.dynamicBuffer(1024); codec.encode(channel, output, request); byte[] bytes = new byte[output.readableBytes()]; output.readBytes(bytes); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); TTransport transport = new TIOStreamTransport(bis); TBinaryProtocol protocol = new TBinaryProtocol(transport); byte[] length = new byte[4]; transport.read(length, 0, 4); if (bis.markSupported()) { bis.mark(0); } Assert.assertEquals(ThriftCodec.MAGIC, protocol.readI16()); int messageLength = protocol.readI32(); Assert.assertEquals(messageLength + 4, bytes.length); short headerLength = protocol.readI16(); Assert.assertEquals(ThriftCodec.VERSION, protocol.readByte()); Assert.assertEquals(Demo.Iface.class.getName(), protocol.readString()); Assert.assertEquals(request.getId(), protocol.readI64()); if (bis.markSupported()) { bis.reset(); bis.skip(headerLength); } TMessage message = protocol.readMessageBegin(); Demo.echoString_args args = new Demo.echoString_args(); args.read(protocol); protocol.readMessageEnd(); Assert.assertEquals("echoString", message.name); Assert.assertEquals(TMessageType.CALL, message.type); Assert.assertEquals("Hello, World!", args.getArg()); }
ThriftProtocol extends AbstractProtocol { public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { ThriftInvoker<T> invoker = new ThriftInvoker<T>(type, url, getClients(url), invokers); invokers.add(invoker); return invoker; } int getDefaultPort(); Exporter<T> export(Invoker<T> invoker); void destroy(); Invoker<T> refer(Class<T> type, URL url); static final int DEFAULT_PORT; static final String NAME; }
@Test public void testRefer() throws Exception { }
ExceptionFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { try { Result result = invoker.invoke(invocation); if (result.hasException() && GenericService.class != invoker.getInterface()) { try { Throwable exception = result.getException(); if (!(exception instanceof RuntimeException) && (exception instanceof Exception)) { return result; } try { Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()); Class<?>[] exceptionClassses = method.getExceptionTypes(); for (Class<?> exceptionClass : exceptionClassses) { if (exception.getClass().equals(exceptionClass)) { return result; } } } catch (NoSuchMethodException e) { return result; } logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception); String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface()); String exceptionFile = ReflectUtils.getCodeBase(exception.getClass()); if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)) { return result; } String className = exception.getClass().getName(); if (className.startsWith("java.") || className.startsWith("javax.")) { return result; } if (exception instanceof RpcException) { return result; } return new RpcResult(new RuntimeException(StringUtils.toString(exception))); } catch (Throwable e) { logger.warn("Fail to ExceptionFilter when called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); return result; } } return result; } catch (RuntimeException e) { logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); throw e; } } ExceptionFilter(); ExceptionFilter(Logger logger); Result invoke(Invoker<?> invoker, Invocation invocation); }
@SuppressWarnings("unchecked") @Test public void testRpcException() { Logger logger = EasyMock.createMock(Logger.class); RpcContext.getContext().setRemoteAddress("127.0.0.1", 1234); RpcException exception = new RpcException("TestRpcException"); logger.error(EasyMock.eq("Got unchecked and undeclared exception which called by 127.0.0.1. service: " + DemoService.class.getName() + ", method: sayHello, exception: " + RpcException.class.getName() + ": TestRpcException"), EasyMock.eq(exception)); ExceptionFilter exceptionFilter = new ExceptionFilter(logger); RpcInvocation invocation = new RpcInvocation("sayHello", new Class<?>[]{String.class}, new Object[]{"world"}); Invoker<DemoService> invoker = EasyMock.createMock(Invoker.class); EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class); EasyMock.expect(invoker.invoke(EasyMock.eq(invocation))).andThrow(exception); EasyMock.replay(logger, invoker); try { exceptionFilter.invoke(invoker, invocation); } catch (RpcException e) { assertEquals("TestRpcException", e.getMessage()); } EasyMock.verify(logger, invoker); RpcContext.removeContext(); }
DeprecatedFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { String key = invoker.getInterface().getName() + "." + invocation.getMethodName(); if (!logged.contains(key)) { logged.add(key); if (invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.DEPRECATED_KEY, false)) { LOGGER.error("The service method " + invoker.getInterface().getName() + "." + getMethodSignature(invocation) + " is DEPRECATED! Declare from " + invoker.getUrl()); } } return invoker.invoke(invocation); } Result invoke(Invoker<?> invoker, Invocation invocation); }
@Test public void testDeprecatedFilter() { URL url = URL.valueOf("test: LogUtil.start(); deprecatedFilter.invoke(new MyInvoker<DemoService>(url), new MockInvocation()); assertEquals(1, LogUtil.findMessage("The service method com.alibaba.dubbo.rpc.support.DemoService.echo(String) is DEPRECATED")); LogUtil.stop(); }
ActiveLimitFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { URL url = invoker.getUrl(); String methodName = invocation.getMethodName(); int max = invoker.getUrl().getMethodParameter(methodName, Constants.ACTIVES_KEY, 0); RpcStatus count = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()); if (max > 0) { long timeout = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.TIMEOUT_KEY, 0); long start = System.currentTimeMillis(); long remain = timeout; int active = count.getActive(); if (active >= max) { synchronized (count) { while ((active = count.getActive()) >= max) { try { count.wait(remain); } catch (InterruptedException e) { } long elapsed = System.currentTimeMillis() - start; remain = timeout - elapsed; if (remain <= 0) { throw new RpcException("Waiting concurrent invoke timeout in client-side for service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", elapsed: " + elapsed + ", timeout: " + timeout + ". concurrent invokes: " + active + ". max concurrent invoke limit: " + max); } } } } } try { long begin = System.currentTimeMillis(); RpcStatus.beginCount(url, methodName); try { Result result = invoker.invoke(invocation); RpcStatus.endCount(url, methodName, System.currentTimeMillis() - begin, true); return result; } catch (RuntimeException t) { RpcStatus.endCount(url, methodName, System.currentTimeMillis() - begin, false); throw t; } } finally { if (max > 0) { synchronized (count) { count.notify(); } } } } Result invoke(Invoker<?> invoker, Invocation invocation); }
@Test public void testInvokeNoActives() { URL url = URL.valueOf("test: Invoker<ActiveLimitFilterTest> invoker = new MyInvoker<ActiveLimitFilterTest>(url); Invocation invocation = new MockInvocation(); activeLimitFilter.invoke(invoker, invocation); } @Test public void testInvokeLessActives() { URL url = URL.valueOf("test: Invoker<ActiveLimitFilterTest> invoker = new MyInvoker<ActiveLimitFilterTest>(url); Invocation invocation = new MockInvocation(); activeLimitFilter.invoke(invoker, invocation); } @Test public void testInvokeGreaterActives() { URL url = URL.valueOf("test: final Invoker<ActiveLimitFilterTest> invoker = new MyInvoker<ActiveLimitFilterTest>(url); final Invocation invocation = new MockInvocation(); for (int i = 0; i < 100; i++) { Thread thread = new Thread(new Runnable() { public void run() { for (int i = 0; i < 100; i++) { try { activeLimitFilter.invoke(invoker, invocation); } catch (RpcException expected) { count++; } } } }); thread.start(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } assertNotSame(0, count); }
ContextFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { Map<String, String> attachments = invocation.getAttachments(); if (attachments != null) { attachments = new HashMap<String, String>(attachments); attachments.remove(Constants.PATH_KEY); attachments.remove(Constants.GROUP_KEY); attachments.remove(Constants.VERSION_KEY); attachments.remove(Constants.DUBBO_VERSION_KEY); attachments.remove(Constants.TOKEN_KEY); attachments.remove(Constants.TIMEOUT_KEY); } RpcContext.getContext() .setInvoker(invoker) .setInvocation(invocation) .setAttachments(attachments) .setLocalAddress(invoker.getUrl().getHost(), invoker.getUrl().getPort()); if (invocation instanceof RpcInvocation) { ((RpcInvocation) invocation).setInvoker(invoker); } try { return invoker.invoke(invocation); } finally { RpcContext.removeContext(); } } Result invoke(Invoker<?> invoker, Invocation invocation); }
@SuppressWarnings("unchecked") @Test public void testSetContext() { invocation = EasyMock.createMock(Invocation.class); EasyMock.expect(invocation.getMethodName()).andReturn("$enumlength").anyTimes(); EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[]{Enum.class}).anyTimes(); EasyMock.expect(invocation.getArguments()).andReturn(new Object[]{"hello"}).anyTimes(); EasyMock.expect(invocation.getAttachments()).andReturn(null).anyTimes(); EasyMock.replay(invocation); invoker = EasyMock.createMock(Invoker.class); EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes(); EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes(); RpcResult result = new RpcResult(); result.setValue("High"); EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes(); URL url = URL.valueOf("test: EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes(); EasyMock.replay(invoker); contextFilter.invoke(invoker, invocation); assertNull(RpcContext.getContext().getInvoker()); } @Test public void testWithAttachments() { URL url = URL.valueOf("test: Invoker<DemoService> invoker = new MyInvoker<DemoService>(url); Invocation invocation = new MockInvocation(); Result result = contextFilter.invoke(invoker, invocation); assertNull(RpcContext.getContext().getInvoker()); }
ConsumerContextFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { RpcContext.getContext() .setInvoker(invoker) .setInvocation(invocation) .setLocalAddress(NetUtils.getLocalHost(), 0) .setRemoteAddress(invoker.getUrl().getHost(), invoker.getUrl().getPort()); if (invocation instanceof RpcInvocation) { ((RpcInvocation) invocation).setInvoker(invoker); } try { return invoker.invoke(invocation); } finally { RpcContext.getContext().clearAttachments(); } } Result invoke(Invoker<?> invoker, Invocation invocation); }
@Test public void testSetContext() { URL url = URL.valueOf("test: Invoker<DemoService> invoker = new MyInvoker<DemoService>(url); Invocation invocation = new MockInvocation(); consumerContextFilter.invoke(invoker, invocation); assertEquals(invoker, RpcContext.getContext().getInvoker()); assertEquals(invocation, RpcContext.getContext().getInvocation()); assertEquals(NetUtils.getLocalHost() + ":0", RpcContext.getContext().getLocalAddressString()); assertEquals("test:11", RpcContext.getContext().getRemoteAddressString()); }
EchoFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) return new RpcResult(inv.getArguments()[0]); return invoker.invoke(inv); } Result invoke(Invoker<?> invoker, Invocation inv); }
@SuppressWarnings("unchecked") @Test public void testEcho() { Invocation invocation = EasyMock.createMock(Invocation.class); EasyMock.expect(invocation.getMethodName()).andReturn("$echo").anyTimes(); EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[]{Enum.class}).anyTimes(); EasyMock.expect(invocation.getArguments()).andReturn(new Object[]{"hello"}).anyTimes(); EasyMock.expect(invocation.getAttachments()).andReturn(null).anyTimes(); EasyMock.replay(invocation); Invoker<DemoService> invoker = EasyMock.createMock(Invoker.class); EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes(); EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes(); RpcResult result = new RpcResult(); result.setValue("High"); EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes(); URL url = URL.valueOf("test: EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes(); EasyMock.replay(invoker); Result filterResult = echoFilter.invoke(invoker, invocation); assertEquals("hello", filterResult.getValue()); } @SuppressWarnings("unchecked") @Test public void testNonEcho() { Invocation invocation = EasyMock.createMock(Invocation.class); EasyMock.expect(invocation.getMethodName()).andReturn("echo").anyTimes(); EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[]{Enum.class}).anyTimes(); EasyMock.expect(invocation.getArguments()).andReturn(new Object[]{"hello"}).anyTimes(); EasyMock.expect(invocation.getAttachments()).andReturn(null).anyTimes(); EasyMock.replay(invocation); Invoker<DemoService> invoker = EasyMock.createMock(Invoker.class); EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes(); EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes(); RpcResult result = new RpcResult(); result.setValue("High"); EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes(); URL url = URL.valueOf("test: EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes(); EasyMock.replay(invoker); Result filterResult = echoFilter.invoke(invoker, invocation); assertEquals("High", filterResult.getValue()); }
ExplorerApiHelper { static HashCode parseSubmitTxResponse(String json) { SubmitTxResponse response = JSON.fromJson(json, SubmitTxResponse.class); return response.getTxHash(); } private ExplorerApiHelper(); }
@Test void parseSubmitTxResponse() { String expected = "f128c720e04b8243"; String json = "{'tx_hash':'" + expected + "'}"; HashCode actual = ExplorerApiHelper.parseSubmitTxResponse(json); assertThat(actual, equalTo(HashCode.fromString(expected))); }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); abstract int bits(); abstract int asInt(); abstract long asLong(); abstract long padToLong(); abstract byte[] asBytes(); @CanIgnoreReturnValue int writeBytesTo(byte[] dest, int offset, int maxLength); static HashCode fromInt(int hash); static HashCode fromLong(long hash); static HashCode fromBytes(byte[] bytes); static HashCode fromString(String string); @Override final boolean equals(@Nullable Object object); @Override final int hashCode(); @Override final String toString(); }
@Test void testWriteBytesToOversizedArray() { byte[] dest = new byte[5]; HASH_ABCD.writeBytesTo(dest, 0, 4); assertArrayEquals(new byte[]{(byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd, (byte) 0x00}, dest); } @Test void testWriteBytesToOversizedArrayLongMaxLength() { byte[] dest = new byte[5]; HASH_ABCD.writeBytesTo(dest, 0, 5); assertArrayEquals(new byte[]{(byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd, (byte) 0x00}, dest); } @Test void testWriteBytesToOversizedArrayShortMaxLength() { byte[] dest = new byte[5]; HASH_ABCD.writeBytesTo(dest, 0, 3); assertArrayEquals(new byte[]{(byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0x00, (byte) 0x00}, dest); } @Test void testWriteBytesToUndersizedArray() { byte[] dest = new byte[3]; assertThrows(IndexOutOfBoundsException.class, () -> HASH_ABCD.writeBytesTo(dest, 0, 4)); } @Test void testWriteBytesToUndersizedArrayLongMaxLength() { byte[] dest = new byte[3]; assertThrows(IndexOutOfBoundsException.class, () -> HASH_ABCD.writeBytesTo(dest, 0, 5)); } @Test void testWriteBytesToUndersizedArrayShortMaxLength() { byte[] dest = new byte[3]; HASH_ABCD.writeBytesTo(dest, 0, 2); assertArrayEquals(new byte[]{(byte) 0xaa, (byte) 0xbb, (byte) 0x00}, dest); } @Test void testWriteBytesTo() { byte[] dest = new byte[4]; HASH_ABCD.writeBytesTo(dest, 0, 4); assertArrayEquals(new byte[]{(byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd}, dest); }
Funnels { public static Funnel<byte[]> byteArrayFunnel() { return ByteArrayFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testForBytes() { PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.byteArrayFunnel().funnel(new byte[]{4, 3, 2, 1}, primitiveSink); verify(primitiveSink).putBytes(new byte[]{4, 3, 2, 1}); } @Test void testForBytes_null() { assertNullsThrowException(Funnels.byteArrayFunnel()); }
Funnels { public static Funnel<CharSequence> unencodedCharsFunnel() { return UnencodedCharsFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testForStrings() { PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.unencodedCharsFunnel().funnel("test", primitiveSink); verify(primitiveSink).putUnencodedChars("test"); } @Test void testForStrings_null() { assertNullsThrowException(Funnels.unencodedCharsFunnel()); }
ApiController { private void getCounter(RoutingContext rc) { String counterName = getRequiredParameter(rc.request(), COUNTER_NAME_PARAM, identity()); Optional<Counter> counter = service.getValue(counterName); respondWithJson(rc, counter); } ApiController(QaService service); }
@Test void getCounter(VertxTestContext context) { String name = "counter"; long value = 10L; Counter counter = new Counter(name, value); when(qaService.getValue(name)).thenReturn(Optional.of(counter)); String getCounterUri = getCounterUri(name); get(getCounterUri) .send(context.succeeding(response -> context.verify(() -> { assertThat(response.statusCode()) .isEqualTo(HTTP_OK); String body = response.bodyAsString(); Counter actualCounter = JSON_SERIALIZER.fromJson(body, Counter.class); assertThat(actualCounter).isEqualTo(counter); context.completeNow(); }))); }
Funnels { public static Funnel<CharSequence> stringFunnel(Charset charset) { return new StringCharsetFunnel(charset); } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testForStringsCharset() { for (Charset charset : Charset.availableCharsets().values()) { PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.stringFunnel(charset).funnel("test", primitiveSink); verify(primitiveSink).putString("test", charset); } } @Test void testForStringsCharset_null() { for (Charset charset : Charset.availableCharsets().values()) { assertNullsThrowException(Funnels.stringFunnel(charset)); } }
Funnels { public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testForInts() { Integer value = 1234; PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.integerFunnel().funnel(value, primitiveSink); verify(primitiveSink).putInt(1234); } @Test void testForInts_null() { assertNullsThrowException(Funnels.integerFunnel()); }
Funnels { public static Funnel<Long> longFunnel() { return LongFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testForLongs() { Long value = 1234L; PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.longFunnel().funnel(value, primitiveSink); verify(primitiveSink).putLong(1234); } @Test void testForLongs_null() { assertNullsThrowException(Funnels.longFunnel()); }
Funnels { public static <E> Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel) { return new SequentialFunnel<>(elementFunnel); } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testSequential() { @SuppressWarnings("unchecked") Funnel<Object> elementFunnel = mock(Funnel.class); PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnel<Iterable<?>> sequential = Funnels.sequentialFunnel(elementFunnel); sequential.funnel(Arrays.asList("foo", "bar", "baz", "quux"), primitiveSink); InOrder inOrder = inOrder(elementFunnel); inOrder.verify(elementFunnel).funnel("foo", primitiveSink); inOrder.verify(elementFunnel).funnel("bar", primitiveSink); inOrder.verify(elementFunnel).funnel("baz", primitiveSink); inOrder.verify(elementFunnel).funnel("quux", primitiveSink); }
Funnels { public static OutputStream asOutputStream(PrimitiveSink sink) { return new SinkAsStream(sink); } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testAsOutputStream() throws Exception { PrimitiveSink sink = mock(PrimitiveSink.class); OutputStream out = Funnels.asOutputStream(sink); byte[] bytes = {1, 2, 3, 4}; out.write(255); out.write(bytes); out.write(bytes, 1, 2); verify(sink).putByte((byte) 255); verify(sink).putBytes(bytes); verify(sink).putBytes(bytes, 1, 2); }
Cleaner implements AutoCloseable { @Override public String toString() { String hash = Integer.toHexString(System.identityHashCode(this)); MoreObjects.ToStringHelper sb = MoreObjects.toStringHelper(this); sb.add("hash", hash); if (!description.isEmpty()) { sb.add("description", description); } return sb .add("numRegisteredActions", getNumRegisteredActions()) .add("closed", closed) .toString(); } Cleaner(); Cleaner(String description); boolean isClosed(); void add(CleanAction<?> cleanAction); @Override void close(); String getDescription(); int getNumRegisteredActions(); @Override String toString(); }
@Test void toStringIncludesContextInformation() { String r = context.toString(); assertThat(r).contains("hash"); assertThat(r).contains("numRegisteredActions=0"); assertThat(r).contains("closed=false"); } @Test void toStringWithDescriptionIncludesContextInformation() { String description = "Transaction#execute"; context = new Cleaner(description); String r = context.toString(); assertThat(r).contains("description=" + description); }
ApiController { private void getConsensusConfiguration(RoutingContext rc) { Config configuration = service.getConsensusConfiguration(); rc.response() .putHeader(CONTENT_TYPE, OCTET_STREAM.toString()) .end(Buffer.buffer(configuration.toByteArray())); } ApiController(QaService service); }
@Test void getConsensusConfiguration(VertxTestContext context) { Config configuration = createConfiguration(); when(qaService.getConsensusConfiguration()).thenReturn(configuration); get(GET_CONSENSUS_CONFIGURATION_PATH) .send(context.succeeding(response -> context.verify(() -> { assertAll( () -> assertThat(response.statusCode()).isEqualTo(HTTP_OK), () -> { Buffer body = response.bodyAsBuffer(); Config consensusConfig = Config.parseFrom(body.getBytes()); assertThat(consensusConfig).isEqualTo(configuration); }); context.completeNow(); }))); }
NativeHandle implements AutoCloseable { @Override public void close() { if (isValid()) { invalidate(); } } NativeHandle(long nativeHandle); long get(); @Override void close(); @Override String toString(); static final long INVALID_NATIVE_HANDLE; }
@Test void close() { nativeHandle = new NativeHandle(HANDLE); nativeHandle.close(); assertFalse(nativeHandle.isValid()); assertThat(nativeHandle.toString()).contains(HANDLE_STRING_REPRESENTATION); }
NativeHandle implements AutoCloseable { @Override public String toString() { return MoreObjects.toStringHelper(this) .add("pointer", Long.toHexString(nativeHandle).toUpperCase()) .toString(); } NativeHandle(long nativeHandle); long get(); @Override void close(); @Override String toString(); static final long INVALID_NATIVE_HANDLE; }
@Test void toStringHexRepresentation() { nativeHandle = new NativeHandle(HANDLE); assertThat(nativeHandle.toString()).contains(HANDLE_STRING_REPRESENTATION); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
@Test void closeShallCallDispose() { proxy = new NativeProxyFake(1L, true); proxy.close(); assertThat(proxy.timesDisposed, equalTo(1)); } @Test void closeShallCallDisposeOnce() { proxy = new NativeProxyFake(1L, true); proxy.close(); proxy.close(); assertThat(proxy.timesDisposed, equalTo(1)); } @Test void closeShallNotDisposeNotOwningHandle() { proxy = new NativeProxyFake(1L, false); proxy.close(); assertThat(proxy.timesDisposed, equalTo(0)); } @Test void closeShallThrowIfReferencedObjectInvalid() { NativeProxyFake reference = makeProxy(2L); proxy = new NativeProxyFake(1L, true, reference); reference.close(); assertThrows(IllegalStateException.class, () -> proxy.close()); } @Test void shallNotBeValidOnceClosed() { proxy = new NativeProxyFake(1L, true); proxy.close(); assertFalse(proxy.isValidHandle()); } @Test void notOwningShallNotBeValidOnceClosed() { proxy = new NativeProxyFake(1L, false); proxy.close(); assertFalse(proxy.isValidHandle()); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override protected final long getNativeHandle() { checkAllRefsValid(); return super.getNativeHandle(); } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
@Test void getNativeHandle() { long expectedNativeHandle = 0x1FL; proxy = new NativeProxyFake(expectedNativeHandle, true); assertThat(proxy.getNativeHandle(), equalTo(expectedNativeHandle)); } @Test void getNativeHandle_DirectMultiReferencedAll() { long nativeHandle = 1L; List<AbstractCloseableNativeProxy> referenced = asList(makeProxy(20L), makeProxy(21L), makeProxy(22L) ); proxy = new NativeProxyFake(nativeHandle, true, referenced); assertThat(proxy.getNativeHandle(), equalTo(nativeHandle)); referenced.forEach(CloseableNativeProxy::close); assertThat(proxy, hasInvalidReferences(referenced)); assertThrows(IllegalStateException.class, () -> proxy.getNativeHandle()); }
ApiController { private void getTime(RoutingContext rc) { Optional<TimeDto> time = service.getTime().map(TimeDto::new); respondWithJson(rc, time); } ApiController(QaService service); }
@Test void getTime(VertxTestContext context) { ZonedDateTime time = ZonedDateTime.of(2018, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); when(qaService.getTime()).thenReturn(Optional.of(time)); get(TIME_PATH) .send(context.succeeding(response -> context.verify(() -> { assertThat(response.statusCode()) .isEqualTo(HTTP_OK); String body = response.bodyAsString(); TimeDto actualTime = JSON_SERIALIZER .fromJson(body, TimeDto.class); assertThat(actualTime.getTime()).isEqualTo(time); context.completeNow(); }))); }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @CanIgnoreReturnValue public static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction) { ProxyDestructor d = new ProxyDestructor(nativeHandle, proxyClass, destructorFunction); cleaner.add(d); return d; } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @Override void clean(); @Override Optional<Class<?>> resourceType(); @Override void cancel(); @Override String toString(); }
@Test void newRegistered() { Cleaner cleaner = mock(Cleaner.class); NativeHandle handle = new NativeHandle(1L); LongConsumer destructor = (nh) -> { }; ProxyDestructor d = ProxyDestructor.newRegistered(cleaner, handle, CloseableNativeProxy.class, destructor); assertNotNull(d); verify(cleaner).add(d); }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public void clean() { if (destroyed || cancelled) { return; } destroyed = true; if (!nativeHandle.isValid()) { return; } long handle = nativeHandle.get(); nativeHandle.close(); cleanFunction.accept(handle); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @Override void clean(); @Override Optional<Class<?>> resourceType(); @Override void cancel(); @Override String toString(); }
@Test void clean() { long rawNativeHandle = 1L; NativeHandle handle = new NativeHandle(rawNativeHandle); LongConsumer destructor = mock(LongConsumer.class); ProxyDestructor d = newDestructor(handle, destructor); d.clean(); assertFalse(handle.isValid()); verify(destructor).accept(rawNativeHandle); } @Test void cleanIdempotent() { long rawNativeHandle = 1L; NativeHandle handle = spy(new NativeHandle(rawNativeHandle)); LongConsumer destructor = mock(LongConsumer.class); ProxyDestructor d = newDestructor(handle, destructor); int attemptsToClean = 3; for (int i = 0; i < attemptsToClean; i++) { d.clean(); } assertFalse(handle.isValid()); verify(handle).close(); verify(destructor).accept(rawNativeHandle); }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public Optional<Class<?>> resourceType() { return Optional.of(proxyClass); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @Override void clean(); @Override Optional<Class<?>> resourceType(); @Override void cancel(); @Override String toString(); }
@Test void getResourceType() { NativeHandle handle = new NativeHandle(1L); Class<?> proxyClass = CloseableNativeProxy.class; LongConsumer destructor = mock(LongConsumer.class); ProxyDestructor d = new ProxyDestructor(handle, proxyClass, destructor); assertThat(d.resourceType()).hasValue(proxyClass); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
@Test void itemsFrequencyNoItems() { Collection<?> c = Collections.emptyList(); String s = FrequencyStatsFormatter.itemsFrequency(c, Object::getClass); assertThat(s).isEqualTo("{}"); } @Test void itemsFrequencyOneItem() { Collection<Boolean> c = ImmutableList.of(true); String s = FrequencyStatsFormatter.itemsFrequency(c, Boolean::booleanValue); assertThat(s).isEqualTo("{true=1}"); } @Test void itemsFrequencySeveralItemsSameCategory() { Collection<Boolean> c = ImmutableList.of(true, true); String s = FrequencyStatsFormatter.itemsFrequency(c, Boolean::booleanValue); assertThat(s).isEqualTo("{true=2}"); } @Test void itemsFrequencyMoreTrue() { Collection<Boolean> c = ImmutableList.of(true, true, false); String s = FrequencyStatsFormatter.itemsFrequency(c, Boolean::booleanValue); assertThat(s).isEqualTo("{true=2, false=1}"); } @Test void itemsFrequencyMoreFalse() { Collection<Boolean> c = ImmutableList.of(false, false, true); String s = FrequencyStatsFormatter.itemsFrequency(c, Boolean::booleanValue); assertThat(s).isEqualTo("{false=2, true=1}"); } @Test void itemsFrequencySeveralElementsSameFrequency() { Collection<Boolean> c = ImmutableList.of(false, false, true, true); String s = FrequencyStatsFormatter.itemsFrequency(c, Boolean::booleanValue); assertThat(s).matches("\\{((true=2, false=2)|(false=2, true=2))\\}"); } @Test void itemsFrequency() { Collection<String> c = ImmutableList.of("aa", "bb", "cc", "a", "c", ""); String s = FrequencyStatsFormatter.itemsFrequency(c, String::length); assertThat(s).isEqualTo("{2=3, 1=2, 0=1}"); }
ApiController { private void getValidatorsTimes(RoutingContext rc) { Map<PublicKey, ZonedDateTime> validatorsTimes = service.getValidatorsTimes(); respondWithJson(rc, validatorsTimes); } ApiController(QaService service); }
@Test void getValidatorsTimes(VertxTestContext context) { Map<PublicKey, ZonedDateTime> validatorsTimes = ImmutableMap.of( PublicKey.fromHexString("11"), ZonedDateTime.of(2018, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC), PublicKey.fromHexString("22"), ZonedDateTime.of(2018, 1, 1, 0, 0, 1, 0, ZoneOffset.UTC)); when(qaService.getValidatorsTimes()).thenReturn(validatorsTimes); get(VALIDATORS_TIMES_PATH) .send(context.succeeding(response -> context.verify(() -> { assertThat(response.statusCode()) .isEqualTo(HTTP_OK); String body = response.bodyAsString(); Map<PublicKey, ZonedDateTime> actualValidatorsTimes = JSON_SERIALIZER .fromJson(body, new TypeToken<Map<PublicKey, ZonedDateTime>>() { }.getType()); assertThat(actualValidatorsTimes).isEqualTo(validatorsTimes); context.completeNow(); }))); }
AbstractService implements Service { protected final String getName() { return instanceSpec.getName(); } protected AbstractService(ServiceInstanceSpec instanceSpec); }
@Test void getName() { AbstractService service = new ServiceUnderTest(INSTANCE_SPEC); assertThat(service.getName()).isEqualTo(NAME); }
AbstractService implements Service { protected final int getId() { return instanceSpec.getId(); } protected AbstractService(ServiceInstanceSpec instanceSpec); }
@Test void getId() { AbstractService service = new ServiceUnderTest(INSTANCE_SPEC); assertThat(service.getId()).isEqualTo(ID); }
GuiceServicesFactory implements ServicesFactory { @Override public ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node) { Supplier<ServiceModule> serviceModuleSupplier = definition.getModuleSupplier(); Module serviceModule = serviceModuleSupplier.get(); Module serviceFrameworkModule = new ServiceFrameworkModule(instanceSpec, node); Injector serviceInjector = frameworkInjector.createChildInjector(serviceModule, serviceFrameworkModule); return serviceInjector.getInstance(ServiceWrapper.class); } @Inject GuiceServicesFactory(Injector frameworkInjector); @Override ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node); }
@Test void createService() { ServiceArtifactId artifactId = ServiceArtifactId.newJavaId("com.acme/foo-service", "1.0.0"); LoadedServiceDefinition serviceDefinition = LoadedServiceDefinition .newInstance(artifactId, TestServiceModule::new); ServiceInstanceSpec instanceSpec = ServiceInstanceSpec.newInstance(TEST_NAME, TEST_ID, artifactId); Node node = mock(Node.class); ServiceWrapper service = factory.createService(serviceDefinition, instanceSpec, node); assertThat(service.getName()).isEqualTo(TEST_NAME); assertThat(service.getService()).isInstanceOf(TestService.class); } @Test void createServiceFailsIfNoServiceBindingsInModule() { ServiceArtifactId artifactId = ServiceArtifactId .newJavaId("com.acme/incomplete-service", "1.0.0"); LoadedServiceDefinition serviceDefinition = LoadedServiceDefinition .newInstance(artifactId, IncompleteServiceModule::new); ServiceInstanceSpec instanceSpec = ServiceInstanceSpec.newInstance(TEST_NAME, TEST_ID, artifactId); Node node = mock(Node.class); Exception e = assertThrows(ConfigurationException.class, () -> factory.createService(serviceDefinition, instanceSpec, node)); assertThat(e).hasMessageContaining(Service.class.getSimpleName()); }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } @Inject ClassLoadingScopeChecker( @Named(DEPENDENCY_REFERENCE_CLASSES_KEY) Map<String, Class<?>> dependencyReferenceClasses); }
@Test void checkNoCopiesOfAppClasses() throws ClassNotFoundException { Class<?> referenceClass = Vertx.class; Map<String, Class<?>> referenceClasses = ImmutableMap.of( "vertx", referenceClass ); ClassLoadingScopeChecker checker = new ClassLoadingScopeChecker(referenceClasses); ClassLoader classLoader = mock(ClassLoader.class); when(classLoader.loadClass(referenceClass.getName())) .thenReturn((Class) referenceClass); checker.checkNoCopiesOfAppClasses(classLoader); } @Test void checkNoCopiesOfAppClassesDetectsCopies() throws ClassNotFoundException { String dependency = "vertx"; Class<?> referenceClass = Vertx.class; Map<String, Class<?>> referenceClasses = ImmutableMap.of( dependency, referenceClass ); ClassLoadingScopeChecker checker = new ClassLoadingScopeChecker(referenceClasses); ClassLoader classLoader = mock(ClassLoader.class); Class actual = Set.class; when(classLoader.loadClass(referenceClass.getName())) .thenReturn(actual); Exception e = assertThrows(IllegalArgumentException.class, () -> checker.checkNoCopiesOfAppClasses(classLoader)); assertThat(e).hasMessageContaining(dependency); } @Test void checkNoCopiesOfAppClassesDetectsAllCopies() throws ClassNotFoundException { Set<String> copiedLibraries = ImmutableSet.of("vertx", "gson"); Set<String> nonCopiedLibraries = ImmutableSet.of("guice"); Map<String, Class<?>> referenceClasses = ImmutableMap.of( "vertx", Vertx.class, "guice", Guice.class, "gson", Gson.class ); assertThat(Sets.union(copiedLibraries, nonCopiedLibraries)) .isEqualTo(referenceClasses.keySet()); ClassLoadingScopeChecker checker = new ClassLoadingScopeChecker(referenceClasses); ClassLoader classLoader = mock(ClassLoader.class); for (String library : copiedLibraries) { Class actual = Set.class; Class<?> referenceClass = referenceClasses.get(library); when(classLoader.loadClass(referenceClass.getName())) .thenReturn(actual); } for (String library : nonCopiedLibraries) { Class actual = referenceClasses.get(library); when(classLoader.loadClass(actual.getName())) .thenReturn(actual); } Exception e = assertThrows(IllegalArgumentException.class, () -> checker.checkNoCopiesOfAppClasses(classLoader)); for (String libraryName : copiedLibraries) { assertThat(e).hasMessageContaining(libraryName); } for (String libraryName : nonCopiedLibraries) { assertThat(e).hasMessageNotContaining(libraryName); } } @Test void checkNoCopiesOfAppClassesClassloaderFailsToDelegate() throws ClassNotFoundException { Class<?> referenceClass = Vertx.class; Map<String, Class<?>> referenceClasses = ImmutableMap.of( "vertx", referenceClass ); ClassLoadingScopeChecker checker = new ClassLoadingScopeChecker(referenceClasses); ClassLoader pluginClassLoader = mock(ClassLoader.class); when(pluginClassLoader.loadClass(referenceClass.getName())) .thenThrow(ClassNotFoundException.class); Exception e = assertThrows(IllegalStateException.class, () -> checker.checkNoCopiesOfAppClasses(pluginClassLoader)); assertThat(e).hasMessageFindingMatch("Classloader .+ failed to load the reference " + "application class .+ from vertx library"); }
RuntimeTransport implements AutoCloseable { void start() { try { server.start(port).get(); } catch (ExecutionException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { logger.error("Start services API server was interrupted", e); Thread.currentThread().interrupt(); } } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }
@Test void start() { when(server.start(PORT)).thenReturn(CompletableFuture.completedFuture(PORT)); transport.start(); verify(server).start(PORT); }
QaServiceImpl extends AbstractService implements QaService { @Override public void initialize(ExecutionContext context, Configuration configuration) { updateTimeOracle(context, configuration); Stream.of( DEFAULT_COUNTER_NAME, BEFORE_TXS_COUNTER_NAME, AFTER_TXS_COUNTER_NAME, AFTER_COMMIT_COUNTER_NAME) .forEach(name -> createCounter(name, context)); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuration configuration); @Override void resume(ExecutionContext context, byte[] arguments); @Override void createPublicApiHandlers(Node node, Router router); @Override void beforeTransactions(ExecutionContext context); @Override void afterTransactions(ExecutionContext context); @Override void afterCommit(BlockCommittedEvent event); @Override HashCode submitIncrementCounter(long requestSeed, String counterName); @Override HashCode submitUnknownTx(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<Counter> getValue(String counterName); @Override Config getConsensusConfiguration(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<ZonedDateTime> getTime(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Map<PublicKey, ZonedDateTime> getValidatorsTimes(); @Override void verifyConfiguration(ExecutionContext context, Configuration configuration); @Override void applyConfiguration(ExecutionContext context, Configuration configuration); @Override @Transaction(CREATE_COUNTER_TX_ID) void createCounter(TxMessageProtos.CreateCounterTxBody arguments, ExecutionContext context); @Override @Transaction(INCREMENT_COUNTER_TX_ID) void incrementCounter(TxMessageProtos.IncrementCounterTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_THROWING_TX_ID) void throwing(TxMessageProtos.ThrowingTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_ERROR_TX_ID) void error(TxMessageProtos.ErrorTxBody arguments, ExecutionContext context); }
@Test void initialize() { String serviceName = "qa"; String timeServiceName = "time"; try (TestKit testKit = TestKit.builder() .withArtifactsDirectory(QaArtifactInfo.ARTIFACT_DIR) .withDeployedArtifact(QaArtifactInfo.ARTIFACT_ID, QaArtifactInfo.ARTIFACT_FILENAME) .withService(QaArtifactInfo.ARTIFACT_ID, serviceName, 1, QaConfiguration.newBuilder() .setTimeOracleName(timeServiceName) .build()) .withTimeService(timeServiceName, 2, TimeProvider.systemTime()) .build()) { BlockchainData snapshot = testKit.getBlockchainData(serviceName); QaSchema schema = new QaSchema(snapshot); Optional<String> timeService = schema.timeOracleName().toOptional(); assertThat(timeService).hasValue(timeServiceName); MapIndex<String, Long> counters = schema.counters(); assertThat(counters.get(DEFAULT_COUNTER_NAME)).isEqualTo(0L); assertThat(counters.get(AFTER_COMMIT_COUNTER_NAME)).isEqualTo(0L); assertThat(counters.get(BEFORE_TXS_COUNTER_NAME)).isEqualTo(0L); assertThat(counters.get(AFTER_TXS_COUNTER_NAME)).isEqualTo(1L); } }
RuntimeTransport implements AutoCloseable { void connectServiceApi(ServiceWrapper service) { Router router = server.createRouter(); service.createPublicApiHandlers(router); String serviceApiPath = createServiceApiPath(service); server.mountSubRouter(serviceApiPath, router); logApiMountEvent(service, serviceApiPath, router); } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }
@Test void connectServiceApi() { Router serviceRouter = mock(Router.class); when(serviceRouter.getRoutes()).thenReturn(emptyList()); when(server.createRouter()).thenReturn(serviceRouter); String serviceApiPath = "test-service"; ServiceWrapper service = mock(ServiceWrapper.class); when(service.getPublicApiRelativePath()).thenReturn(serviceApiPath); transport.connectServiceApi(service); verify(service).createPublicApiHandlers(serviceRouter); verify(server).mountSubRouter(API_ROOT_PATH + "/" + serviceApiPath, serviceRouter); }
RuntimeTransport implements AutoCloseable { void disconnectServiceApi(ServiceWrapper service) { String serviceApiPath = createServiceApiPath(service); server.removeSubRouter(serviceApiPath); logger.info("Removed the service API endpoints at {}", serviceApiPath); } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }
@Test void disconnectServiceApi() { String serviceApiPath = "test-service"; ServiceWrapper service = mock(ServiceWrapper.class); when(service.getPublicApiRelativePath()).thenReturn(serviceApiPath); transport.disconnectServiceApi(service); verify(server).removeSubRouter(API_ROOT_PATH + "/" + serviceApiPath); }
RuntimeTransport implements AutoCloseable { @Override public void close() throws InterruptedException { try { server.stop().get(); } catch (ExecutionException e) { throw new IllegalStateException(e.getCause()); } } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }
@Test void close() throws InterruptedException { when(server.stop()).thenReturn(CompletableFuture.completedFuture(null)); transport.close(); verify(server).stop(); } @Test void closeReportsOtherFailures() { CompletableFuture<Void> stopResult = new CompletableFuture<>(); Throwable stopCause = new RuntimeException("Stop failure cause"); stopResult.completeExceptionally(stopCause); when(server.stop()).thenReturn(stopResult); IllegalStateException e = assertThrows(IllegalStateException.class, () -> transport.close()); assertThat(e).hasCause(stopCause); }
ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } ReflectiveModuleSupplier(Class<? extends ServiceModule> moduleClass); @Override ServiceModule get(); @Override String toString(); }
@Test void get() throws NoSuchMethodException, IllegalAccessException { supplier = new ReflectiveModuleSupplier(Good.class); ServiceModule serviceModule = supplier.get(); assertThat(serviceModule, instanceOf(Good.class)); } @Test void getProducesFreshInstances() throws NoSuchMethodException, IllegalAccessException { supplier = new ReflectiveModuleSupplier(Good.class); ServiceModule serviceModule1 = supplier.get(); ServiceModule serviceModule2 = supplier.get(); assertThat(serviceModule1, instanceOf(Good.class)); assertThat(serviceModule2, instanceOf(Good.class)); assertThat(serviceModule1, not(sameInstance(serviceModule2))); } @Test void getPropagatesExceptions() throws NoSuchMethodException, IllegalAccessException { supplier = new ReflectiveModuleSupplier(BadThrowsInCtor.class); IllegalStateException e = assertThrows(IllegalStateException.class, () -> supplier.get()); Throwable cause = e.getCause(); assertThat(cause, instanceOf(RuntimeException.class)); assertThat(cause.getMessage(), equalTo("BadThrowsInCtor indeed")); }
ServiceConfiguration implements Configuration { @Override public <MessageT extends MessageLite> MessageT getAsMessage(Class<MessageT> parametersType) { Serializer<MessageT> serializer = StandardSerializers.protobuf(parametersType); return serializer.fromBytes(configuration); } ServiceConfiguration(byte[] configuration); @Override MessageT getAsMessage(Class<MessageT> parametersType); @Override Format getConfigurationFormat(); @Override String getAsString(); @Override T getAsJson(Class<T> configType); @Override Properties getAsProperties(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test void getAsMessage() { Id config = anyId(); byte[] serializedConfig = config.toByteArray(); ServiceConfiguration serviceConfiguration = new ServiceConfiguration(serializedConfig); Id unpackedConfig = serviceConfiguration.getAsMessage(Id.class); assertThat(unpackedConfig).isEqualTo(config); } @Test void getAsMessageNotMessage() { byte[] serializedConfig = bytes(1, 2, 3, 4); ServiceConfiguration serviceConfiguration = new ServiceConfiguration(serializedConfig); Exception e = assertThrows(IllegalArgumentException.class, () -> serviceConfiguration.getAsMessage(Id.class)); assertThat(e).hasCauseInstanceOf(InvalidProtocolBufferException.class); }
ServiceConfiguration implements Configuration { @Override public <T> T getAsJson(Class<T> configType) { String configuration = getServiceConfigurationInFormat(Format.JSON); return JsonSerializer.json().fromJson(configuration, configType); } ServiceConfiguration(byte[] configuration); @Override MessageT getAsMessage(Class<MessageT> parametersType); @Override Format getConfigurationFormat(); @Override String getAsString(); @Override T getAsJson(Class<T> configType); @Override Properties getAsProperties(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test void getAsJson() { byte[] configuration = Service.ServiceConfiguration.newBuilder() .setFormat(Format.JSON) .setValue("{'foo' : 'bar'}") .build() .toByteArray(); ServiceConfiguration serviceConfiguration = new ServiceConfiguration(configuration); Foo actualConfig = serviceConfiguration.getAsJson(Foo.class); assertThat(actualConfig.foo).isEqualTo("bar"); }
QaServiceImpl extends AbstractService implements QaService { @Override public void resume(ExecutionContext context, byte[] arguments) { QaResumeArguments resumeArguments = parseResumeArguments(arguments); checkExecution(!resumeArguments.getShouldThrowException(), RESUME_SERVICE_ERROR.code); createCounter(resumeArguments.getCounterName(), context); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuration configuration); @Override void resume(ExecutionContext context, byte[] arguments); @Override void createPublicApiHandlers(Node node, Router router); @Override void beforeTransactions(ExecutionContext context); @Override void afterTransactions(ExecutionContext context); @Override void afterCommit(BlockCommittedEvent event); @Override HashCode submitIncrementCounter(long requestSeed, String counterName); @Override HashCode submitUnknownTx(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<Counter> getValue(String counterName); @Override Config getConsensusConfiguration(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<ZonedDateTime> getTime(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Map<PublicKey, ZonedDateTime> getValidatorsTimes(); @Override void verifyConfiguration(ExecutionContext context, Configuration configuration); @Override void applyConfiguration(ExecutionContext context, Configuration configuration); @Override @Transaction(CREATE_COUNTER_TX_ID) void createCounter(TxMessageProtos.CreateCounterTxBody arguments, ExecutionContext context); @Override @Transaction(INCREMENT_COUNTER_TX_ID) void incrementCounter(TxMessageProtos.IncrementCounterTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_THROWING_TX_ID) void throwing(TxMessageProtos.ThrowingTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_ERROR_TX_ID) void error(TxMessageProtos.ErrorTxBody arguments, ExecutionContext context); }
@Test void resume() throws CloseFailuresException { String counterName = "resume"; ServiceInstanceSpec spec = ServiceInstanceSpec .newInstance(QA_SERVICE_NAME, QA_SERVICE_ID, ARTIFACT_ID); byte[] arguments = QaResumeArguments.newBuilder() .setCounterName(counterName) .setShouldThrowException(false) .build() .toByteArray(); try (TemporaryDb db = TemporaryDb.newInstance(); Cleaner cleaner = new Cleaner()) { Fork fork = db.createFork(cleaner); BlockchainData blockchainData = BlockchainData.fromRawAccess(fork, QA_SERVICE_NAME); ExecutionContext context = ExecutionContext.builder() .serviceName(QA_SERVICE_NAME) .serviceId(QA_SERVICE_ID) .blockchainData(blockchainData) .build(); QaServiceImpl qaService = new QaServiceImpl(spec); qaService.resume(context, arguments); QaSchema schema = new QaSchema(blockchainData); MapIndex<String, Long> counters = schema.counters(); assertThat(counters.get(counterName)).isEqualTo(0L); } } @Test void resumeShouldThrowException() { ServiceInstanceSpec spec = ServiceInstanceSpec .newInstance(QA_SERVICE_NAME, QA_SERVICE_ID, ARTIFACT_ID); byte[] arguments = QaResumeArguments.newBuilder() .setShouldThrowException(true) .build() .toByteArray(); ExecutionContext context = mock(ExecutionContext.class); QaServiceImpl qaService = new QaServiceImpl(spec); ExecutionException exception = assertThrows(ExecutionException.class, () -> qaService.resume(context, arguments)); assertThat(exception.getErrorCode()).isEqualTo(RESUME_SERVICE_ERROR.code); }