method2testcases
stringlengths
118
6.63k
### Question: JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } static JsDoc parse(String ...
### Question: JsDocParser { static Map<String,String> extractAttributes(String jsDocWithNoStars) { return null; } static JsDoc parse(String moduleId, String content); static final JsDoc EMPTY_JSDOC; }### Answer: @Test public void testExtractAttributes() { JsDoc doc = JsDocParser.parse("foo", ""); assertEquals("Desc", ...
### Question: DashboardConfig { protected static int getConfigInt(String name, int defaultVal, int minVal) { if (cacheMap.containsKey(name)) { return (int)cacheMap.get(name); } int val = NumberUtils.toInt(getConfig(name)); if (val == 0) { val = defaultVal; } else if (val < minVal) { val = minVal; } cacheMap.put(name, v...
### Question: InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public void save(MetricEntity entity) { if (entity == null || StringUtil.isBlank(entity.getApp())) { return; } readWriteLock.writeLock().lock(); try { allMetrics.computeIfAbsent(entity.getApp(), e -> new HashMap<>(16)) .compu...
### Question: InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public void saveAll(Iterable<MetricEntity> metrics) { if (metrics == null) { return; } readWriteLock.writeLock().lock(); try { metrics.forEach(this::save); } finally { readWriteLock.writeLock().unlock(); } } @Override void s...
### Question: InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public List<String> listResourcesOfApp(String app) { List<String> results = new ArrayList<>(); if (StringUtil.isBlank(app)) { return results; } Map<String, LinkedHashMap<Long, MetricEntity>> resourceMap = allMetrics.get(app);...
### Question: SentinelVersion { public boolean greaterThan(SentinelVersion version) { if (version == null) { return true; } return getFullVersion() > version.getFullVersion(); } SentinelVersion(); SentinelVersion(int major, int minor, int fix); SentinelVersion(int major, int minor, int fix, String postfix); int getFu...
### Question: SpringContextHolder implements ApplicationContextAware { public static ApplicationContext getApplicationContext() { checkApplicationContext(); return context; } @Override void setApplicationContext(ApplicationContext applicationContext); static ApplicationContext getApplicationContext(); static T getBean...
### Question: 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....
### Question: 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) { re...
### Question: 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 ...
### Question: 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, H...
### Question: 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(W...
### Question: 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...
### Question: 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,...
### Question: 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); ...
### Question: 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...
### Question: 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) { ne...
### Question: 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); } ...
### Question: 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 withGre...
### Question: 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 wit...
### Question: 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 withG...
### Question: 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.g...
### Question: 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 != ...
### Question: 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 getWrap...
### Question: 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 ...
### Question: 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<?> ...
### Question: 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]); } retur...
### Question: 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...
### Question: 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 : sub...
### Question: 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, providerIn...
### Question: 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.get...
### Question: 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>(...
### Question: 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 = entr...
### Question: 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.ma...
### Question: 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.getExtensionL...
### Question: ParseUtils { public static boolean isMatchGlobPatternsNeedInterpolate( Collection<String> patternsNeedInterpolate, Map<String, String> interpolateParams, String value) { if (patternsNeedInterpolate != null && !patternsNeedInterpolate.isEmpty()) { for (String patternNeedItp : patternsNeedInterpolate) { if ...
### Question: 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 Par...
### Question: 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 ...
### Question: 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 = ...
### Question: 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 nam...
### Question: 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 ...
### Question: 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)) {...
### Question: 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.equa...
### Question: 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);...
### Question: 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 (...
### Question: 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.getM...
### Question: 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 = Rpc...
### Question: 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); ...
### Question: 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(...
### Question: 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 ...
### Question: ExplorerApiHelper { static HashCode parseSubmitTxResponse(String json) { SubmitTxResponse response = JSON.fromJson(json, SubmitTxResponse.class); return response.getTxHash(); } private ExplorerApiHelper(); }### Answer: @Test void parseSubmitTxResponse() { String expected = "f128c720e04b8243"; String js...
### Question: 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 i...
### Question: 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(); ...
### Question: 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> i...
### Question: 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); }### Answer: @Test void getCo...
### Question: 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<...
### Question: 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(); sta...
### Question: 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 Funne...
### Question: 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(Ch...
### Question: 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> inte...
### Question: 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 .a...
### Question: 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); }### Answer: @Test...
### Question: 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; }### Answer: @Test void close() { nativeHandle = new NativeH...
### Question: 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 l...
### Question: AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, ...
### Question: AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override protected final long getNativeHandle() { checkAllRefsValid(); return super.getNativeHandle(); } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNati...
### Question: ApiController { private void getTime(RoutingContext rc) { Optional<TimeDto> time = service.getTime().map(TimeDto::new); respondWithJson(rc, time); } ApiController(QaService service); }### Answer: @Test void getTime(VertxTestContext context) { ZonedDateTime time = ZonedDateTime.of(2018, 1, 1, 0, 0, 0, 0,...
### Question: ProxyDestructor implements CancellableCleanAction<Class<?>> { @CanIgnoreReturnValue public static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction) { ProxyDestructor d = new ProxyDestructor(nativeHandle, proxyClass, destructorFu...
### Question: 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(NativeHan...
### Question: ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public Optional<Class<?>> resourceType() { return Optional.of(proxyClass); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @CanIgnoreReturnValue static Proxy...
### Question: 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().s...
### Question: ApiController { private void getValidatorsTimes(RoutingContext rc) { Map<PublicKey, ZonedDateTime> validatorsTimes = service.getValidatorsTimes(); respondWithJson(rc, validatorsTimes); } ApiController(QaService service); }### Answer: @Test void getValidatorsTimes(VertxTestContext context) { Map<PublicKe...
### Question: AbstractService implements Service { protected final String getName() { return instanceSpec.getName(); } protected AbstractService(ServiceInstanceSpec instanceSpec); }### Answer: @Test void getName() { AbstractService service = new ServiceUnderTest(INSTANCE_SPEC); assertThat(service.getName()).isEqualT...
### Question: AbstractService implements Service { protected final int getId() { return instanceSpec.getId(); } protected AbstractService(ServiceInstanceSpec instanceSpec); }### Answer: @Test void getId() { AbstractService service = new ServiceUnderTest(INSTANCE_SPEC); assertThat(service.getId()).isEqualTo(ID); }
### Question: GuiceServicesFactory implements ServicesFactory { @Override public ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node) { Supplier<ServiceModule> serviceModuleSupplier = definition.getModuleSupplier(); Module serviceModule = serviceModuleSupplier.ge...
### Question: 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 ...
### Question: 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) .for...
### Question: RuntimeTransport implements AutoCloseable { void connectServiceApi(ServiceWrapper service) { Router router = server.createRouter(); service.createPublicApiHandlers(router); String serviceApiPath = createServiceApiPath(service); server.mountSubRouter(serviceApiPath, router); logApiMountEvent(service, servi...
### Question: 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, ...
### Question: 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); @Overri...
### Question: ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } ReflectiveModuleSupplier(Class<? extends ServiceModule> moduleClass); @Override ServiceModule get(); @Override String toString(); }### Answer: @Test void get() throws NoSuchMe...
### Question: 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[] ...
### Question: 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 ge...
### Question: 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(...
### Question: ServiceConfiguration implements Configuration { @Override public Properties getAsProperties() { String configuration = getServiceConfigurationInFormat(Format.PROPERTIES); Properties properties = new Properties(); try { properties.load(new StringReader(configuration)); } catch (IOException e) { throw new I...
### Question: TransactionExtractor { @VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMetho...
### Question: TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .pe...
### Question: TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); trans...
### Question: Fork extends AbstractAccess { public static Fork newInstance(long nativeHandle, Cleaner cleaner) { return newInstance(nativeHandle, true, cleaner); } private Fork(NativeHandle nativeHandle, ProxyDestructor destructor, Cleaner parentCleaner); static Fork newInstance(long nativeHandle, Cleaner cleaner); st...
### Question: OpenIndexRegistry { Optional<StorageIndex> findIndex(Long id) { return Optional.ofNullable(indexes.get(id)); } }### Answer: @Test void findUnknownIndex() { long unknownId = 1024L; Optional<StorageIndex> index = registry.findIndex(unknownId); assertThat(index).isEmpty(); }
### Question: Snapshot extends AbstractAccess { public static Snapshot newInstance(long nativeHandle, Cleaner cleaner) { return newInstance(nativeHandle, true, cleaner); } private Snapshot(NativeHandle nativeHandle, Cleaner cleaner); static Snapshot newInstance(long nativeHandle, Cleaner cleaner); static Snapshot newI...
### Question: ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } ConfigurableRustIter(NativeHandle nativeHandle, LongFunction<E> nextFunction, ...
### Question: QaServiceImpl extends AbstractService implements QaService { @Override public void beforeTransactions(ExecutionContext context) { incrementCounter(BEFORE_TXS_COUNTER_NAME, context); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuratio...
### Question: AbstractIndexProxy extends AbstractNativeProxy implements StorageIndex { void notifyModified() { checkCanModify(); modCounter.notifyModified(); } AbstractIndexProxy(NativeHandle nativeHandle, IndexAddress address, AbstractAccess access); @Override IndexAddress getAddress(); @Override String toString(); }...
### Question: RustIterAdapter implements Iterator<E> { @Override public E next() { E element = nextItem.orElseThrow( () -> new NoSuchElementException("Reached the end of the underlying collection. " + "Use #hasNext to check if you have reached the end of the collection.")); nextItem = rustIter.next(); return element; }...
### Question: StoragePreconditions { @CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; } private StoragePreconditions(); }### Answer: @Test void checkIndexNameAcceptsNonEmpty() { String name = "table1"; assertThat(name, sameInstance(Storag...
### Question: StoragePreconditions { @CanIgnoreReturnValue static byte[] checkIdInGroup(byte[] indexId) { checkArgument(indexId.length > 0, "index identifier must not be empty"); return indexId; } private StoragePreconditions(); }### Answer: @Test void checkIdInGroup() { byte[] validId = bytes("id1"); assertThat(Sto...
### Question: QaServiceImpl extends AbstractService implements QaService { @Override public void afterTransactions(ExecutionContext context) { incrementCounter(AFTER_TXS_COUNTER_NAME, context); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuration ...
### Question: StoragePreconditions { @CanIgnoreReturnValue static byte[] checkStorageKey(byte[] key) { return checkNotNull(key, "Storage key is null"); } private StoragePreconditions(); }### Answer: @Test void checkStorageKeyAcceptsEmpty() { byte[] key = new byte[]{}; assertThat(key, sameInstance(StoragePrecondition...