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);...
@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...
@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...
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"); }...
@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 = ne...
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.getI...
@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(dat...
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...
@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);...
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)) { r...
@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.set...
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"); } GatewayFlo...
@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_G...
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"); } Lon...
@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.set...
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.of...
@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.s...
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 getAuthPasswor...
@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")); DashboardConfi...
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, Buffere...
@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, ...
@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, ABG...
@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....
@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.setFo...
@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...
@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(0x0...
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...
@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(...
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; } ...
@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...
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(...
@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.from...
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 gr...
@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(shor...
@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 ...
@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 Arra...
@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>()); invoker...
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(Co...
@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...
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.s...
@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 = ...
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...
@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, Stri...
@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, ...
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 ArrayLis...
@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() { Li...
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 c...
@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_loadP...
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.getMe...
@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 publi...
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; } st...
@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(...
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.equal...
@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(inpu...
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(parameter...
@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(")...
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 isCom...
@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.c...
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 ...
@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> expectF...
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))) ret...
@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, p...
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 ...
@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)...
@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>(); un...
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<Strin...
@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("servi...
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(); Ro...
@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(...
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(expressi...
@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.inter...
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(LoadBala...
@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() {...
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)) ret...
@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.isMatchGlobPatt...
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.i...
@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, interpolateParam...
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...
@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("h...
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(); sta...
@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>(); e...
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...
@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&appli...
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...
@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.previewRo...
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 Ha...
@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("du...
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("f...
@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...
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...
@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")); assert...
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(); vo...
@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...
@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...
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 Ref...
@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 Mo...
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[] = messag...
@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(res...
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...
@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.getLoca...
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) || (...
@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 ...
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)) {...
@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(byt...
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(...
@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 in...
@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 call...
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(), C...
@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.getStat...
@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("tes...
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.re...
@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(invoc...
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()); ...
@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, RpcCont...
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...
@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(invoca...
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(); abs...
@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.writeBytesT...
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<...
@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()...
@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(() ...
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> integ...
@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 (C...
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<Ite...
@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<? e...
@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)...
@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);...
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(); s...
@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...
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("numRegiste...
@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"; contex...
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.sta...
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_NA...
@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 dispos...
@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 closeShallNotD...
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override protected final long getNativeHandle() { checkAllRefsValid(); return super.getNativeHandle(); } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long n...
@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 =...
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 ...
ProxyDestructor implements CancellableCleanAction<Class<?>> { @CanIgnoreReturnValue public static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction) { ProxyDestructor d = new ProxyDestructor(nativeHandle, proxyClass, destructorFunction); clean...
@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 nativeHand...
@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 cleanIdem...
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public Optional<Class<?>> resourceType() { return Optional.of(proxyClass); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor new...
@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() .sorte...
@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(...
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.get...
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 se...
@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, TE...
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....
@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...
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 RuntimeTranspo...
@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 -> c...
@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,...
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, rou...
@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()...
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...
@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 ...
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 { su...
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)...
@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 getAsMessag...
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(Cla...
@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); asser...
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(resumeArgument...
@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() .toByteArra...