method2testcases
stringlengths
118
3.08k
### Question: ResourceFactory { public static Resource newResource(String path, ClassLoader classLoader) { if (path.startsWith(CLASSPATH_SCHEME)) { return new ClasspathResource(path, classLoader); } return new FileResource(path); } static Resource newResource(String path, ClassLoader classLoader); static Resource newResource(String path); }### Answer: @Test public void canAcquireClasspathResources() { Resource resource = ResourceFactory.newResource("classpath:com/hotels/styx/common/io/resource.txt"); assertThat(resource, contains("This is an example resource.\nIt has content to use in automated tests.")); } @Test public void canAcquireFileResources() { String filePath = ResourceFactoryTest.class.getResource("/com/hotels/styx/common/io/resource.txt").getPath(); Resource resource = ResourceFactory.newResource(filePath); assertThat(resource, contains("This is an example resource.\nIt has content to use in automated tests.")); }
### Question: ClassFactories { public static <T> T newInstance(String className, Class<T> type) { try { Object instance = classForName(className).newInstance(); return type.cast(instance); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(format("No such class '%s'", className)); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } private ClassFactories(); static T newInstance(String className, Class<T> type); }### Answer: @Test public void instantiatesClassWithZeroArgumentConstructor() { MyInterface instance = ClassFactories.newInstance(MyClass.class.getName(), MyInterface.class); assertThat(instance, is(instanceOf(MyClass.class))); } @Test public void throwsExceptionIfThereIsNoZeroArgumentConstructor() { Exception e = assertThrows(RuntimeException.class, () -> ClassFactories.newInstance(MyInvalidClass.class.getName(), MyInterface.class)); assertEquals("java.lang.InstantiationException: com.hotels.styx.proxy.ClassFactoriesTest$MyInvalidClass", e.getMessage()); } @Test public void throwsExceptionIfClassDoesNotExtendType() { Exception e = assertThrows(ClassCastException.class, () -> ClassFactories.newInstance(MyClass.class.getName(), Runnable.class)); assertEquals("Cannot cast com.hotels.styx.proxy.ClassFactoriesTest$MyClass to java.lang.Runnable", e.getMessage()); } @Test public void throwsExceptionIfClassDoesNotExist() { Exception e = assertThrows(IllegalArgumentException.class, () -> ClassFactories.newInstance(MyClass.class.getName() + "NonExistent", Runnable.class)); assertEquals("No such class 'com.hotels.styx.proxy.ClassFactoriesTest$MyClassNonExistent'", e.getMessage()); }
### Question: Preconditions { public static String checkNotEmpty(String value) { if (value == null || value.length() == 0) { throw new IllegalArgumentException(); } return value; } private Preconditions(); static String checkNotEmpty(String value); static T checkArgument(T reference, boolean expression); static void checkArgument(boolean expression); static void checkArgument(boolean expression, Object errorMessage); static void checkArgument(boolean expression, String errorMessageTemplate, Object... errorMessageArgs); }### Answer: @Test public void isNotEmptyString() { assertThat(checkNotEmpty(" "), is(" ") ); } @Test public void isEmptyString() { assertThrows(IllegalArgumentException.class, () -> checkNotEmpty(null)); }
### Question: Preconditions { public static <T> T checkArgument(T reference, boolean expression) { if (!expression) { throw new IllegalArgumentException(); } return reference; } private Preconditions(); static String checkNotEmpty(String value); static T checkArgument(T reference, boolean expression); static void checkArgument(boolean expression); static void checkArgument(boolean expression, Object errorMessage); static void checkArgument(boolean expression, String errorMessageTemplate, Object... errorMessageArgs); }### Answer: @Test public void checkArgumentFailure() { assertThrows(IllegalArgumentException.class, () -> checkArgument(0, false)); } @Test public void checkArgumentSuccess() { assertThat(checkArgument(0, true), is(0)); }
### Question: SanitisedHttpMessageFormatter implements HttpMessageFormatter { @Override public String formatRequest(HttpRequest request) { return request == null ? NULL : formatRequest( request.version(), request.method(), request.url(), request.id(), request.headers()); } SanitisedHttpMessageFormatter(SanitisedHttpHeaderFormatter sanitisedHttpHeaderFormatter); @Override String formatRequest(HttpRequest request); @Override String formatRequest(LiveHttpRequest request); @Override String formatResponse(HttpResponse response); @Override String formatResponse(LiveHttpResponse response); @Override String formatNettyMessage(HttpObject message); @Override Throwable wrap(Throwable t); }### Answer: @Test public void shouldFormatHttpRequest() { String formattedRequest = sanitisedHttpMessageFormatter.formatRequest(httpRequest); assertThat(formattedRequest, matchesPattern(HTTP_REQUEST_PATTERN)); } @Test public void shouldFormatLiveHttpRequest() { String formattedRequest = sanitisedHttpMessageFormatter.formatRequest(httpRequest.stream()); assertThat(formattedRequest, matchesPattern(HTTP_REQUEST_PATTERN)); }
### Question: SanitisedHttpMessageFormatter implements HttpMessageFormatter { @Override public String formatResponse(HttpResponse response) { return response == null ? NULL : formatResponse( response.version(), response.status(), response.headers()); } SanitisedHttpMessageFormatter(SanitisedHttpHeaderFormatter sanitisedHttpHeaderFormatter); @Override String formatRequest(HttpRequest request); @Override String formatRequest(LiveHttpRequest request); @Override String formatResponse(HttpResponse response); @Override String formatResponse(LiveHttpResponse response); @Override String formatNettyMessage(HttpObject message); @Override Throwable wrap(Throwable t); }### Answer: @Test public void shouldFormatHttpResponse() { String formattedResponse = sanitisedHttpMessageFormatter.formatResponse(httpResponse); assertThat(formattedResponse, matchesPattern(HTTP_RESPONSE_PATTERN)); } @Test public void shouldFormatLiveHttpResponse() { String formattedResponse = sanitisedHttpMessageFormatter.formatResponse(httpResponse.stream()); assertThat(formattedResponse, matchesPattern(HTTP_RESPONSE_PATTERN)); }
### Question: SanitisedHttpHeaderFormatter { public String format(HttpHeaders headers) { return StreamSupport.stream(headers.spliterator(), false) .map(this::hideOrFormatHeader) .collect(joining(", ")); } SanitisedHttpHeaderFormatter(List<String> headersToHide, List<String> cookiesToHide); List<String> cookiesToHide(); String format(HttpHeaders headers); }### Answer: @Test public void formatShouldFormatRequest() { HttpHeaders headers = new HttpHeaders.Builder() .add("header1", "a") .add("header2", "b") .add("header3", "c") .add("header4", "d") .add("COOKIE", "cookie1=e;cookie2=f;") .add("SET-COOKIE", "cookie3=g;cookie4=h;") .build(); List<String> headersToHide = Arrays.asList("HEADER1", "HEADER3"); List<String> cookiesToHide = Arrays.asList("cookie2", "cookie4"); String formattedHeaders = new SanitisedHttpHeaderFormatter(headersToHide, cookiesToHide).format(headers); assertThat(formattedHeaders, is("header1=****, header2=b, header3=****, header4=d, COOKIE=cookie1=e;cookie2=****, SET-COOKIE=cookie3=g;cookie4=****")); }
### Question: StateMachine { public S currentState() { return currentState; } private StateMachine(S initialState, Map<Key<S>, Function<Object, S>> transitions, BiFunction<S, Object, S> inappropriateEventHandler, StateChangeListener<S> stateChangeListener); S currentState(); void handle(Object event, String loggingPrefix); void handle(Object event); }### Answer: @Test public void startsInInitialState() { StateMachine<State> stateMachine = stateMachineBuilder.build(); assertThat(stateMachine.currentState(), Matchers.is(STARTED)); }
### Question: FlowControllingHttpContentProducer { public void newChunk(ByteBuf content) { stateMachine.handle(new ContentChunkEvent(content)); } FlowControllingHttpContentProducer( Runnable askForMore, Runnable onCompleteAction, Consumer<Throwable> onTerminateAction, String loggingPrefix, long inactivityTimeoutMs, EventLoop eventLoop); void newChunk(ByteBuf content); void lastHttpContent(); void channelException(Throwable cause); void channelInactive(Throwable cause); void tearDownResources(Throwable cause); void request(long n); void onSubscribed(Subscriber<? super ByteBuf> subscriber); void unsubscribe(); long emittedBytes(); long emittedChunks(); long receivedBytes(); long receivedChunks(); }### Answer: @Test public void contentEventInBufferingState() { setUpAndRequest(5); verify(askForMore).run(); producer.newChunk(contentChunk1); verify(askForMore, times(1)).run(); producer.newChunk(contentChunk2); verify(askForMore, times(1)).run(); }
### Question: Logging { public static String sanitise(String input) { return input.replaceAll("\\n", "\\\\n"); } private Logging(); static String sanitise(String input); }### Answer: @Test public void sanitiseRemovesNewlines() throws Exception { assertThat(Logging.sanitise("first line\nsecond line"), is("first line\\nsecond line")); }
### Question: ChannelStatisticsHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof ByteBuf) { receivedBytesCount.inc(((ByteBuf) msg).readableBytes()); } else if (msg instanceof ByteBufHolder) { receivedBytesCount.inc(((ByteBufHolder) msg).content().readableBytes()); } else { LOGGER.warn(format("channelRead(): Expected byte buffers, but got [%s]", msg)); } super.channelRead(ctx, msg); } ChannelStatisticsHandler(MetricRegistry metricRegistry); @Override void channelRegistered(ChannelHandlerContext ctx); @Override void channelUnregistered(ChannelHandlerContext ctx); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelInactive(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); @Override void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise); }### Answer: @Test public void countsReceivedBytes() throws Exception { ByteBuf buf = httpRequestAsBuf(POST, "/foo/bar", "Hello, world"); this.handler.channelRead(mock(ChannelHandlerContext.class), buf); assertThat(countOf("connections.bytes-received"), is((long) buf.readableBytes())); }
### Question: ChannelStatisticsHandler extends ChannelDuplexHandler { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof ByteBuf) { sentBytesCount.inc(((ByteBuf) msg).readableBytes()); } else if (msg instanceof ByteBufHolder) { sentBytesCount.inc(((ByteBufHolder) msg).content().readableBytes()); } super.write(ctx, msg, promise); } ChannelStatisticsHandler(MetricRegistry metricRegistry); @Override void channelRegistered(ChannelHandlerContext ctx); @Override void channelUnregistered(ChannelHandlerContext ctx); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelInactive(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); @Override void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise); }### Answer: @Test public void countsSentBytes() throws Exception { ByteBuf buf = httpResponseAsBuf(OK, "Response from server"); this.handler.write(mock(ChannelHandlerContext.class), buf, mock(ChannelPromise.class)); assertThat(countOf("connections.bytes-sent"), is((long) buf.readableBytes())); }
### Question: HttpPipelineHandler extends SimpleChannelInboundHandler<LiveHttpRequest> { private static HttpResponseStatus status(Throwable exception) { return EXCEPTION_STATUSES.statusFor(exception) .orElseGet(() -> { if (exception instanceof DecoderException) { Throwable cause = exception.getCause(); if (cause instanceof BadRequestException) { if (cause.getCause() instanceof TooLongFrameException) { return REQUEST_ENTITY_TOO_LARGE; } return BAD_REQUEST; } } else if (exception instanceof TransportLostException) { return BAD_GATEWAY; } return INTERNAL_SERVER_ERROR; }); } private HttpPipelineHandler(Builder builder, RequestTracker tracker); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelInactive(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); }### Answer: @Test public void mapsUnrecoverableInternalErrorsToInternalServerError500ResponseCode() { HttpHandler handler = (request, context) -> { throw new RuntimeException("Forced exception for testing"); }; EmbeddedChannel channel = buildEmbeddedChannel(handlerWithMocks(handler)); channel.writeInbound(httpRequestAsBuf(GET, "http: DefaultHttpResponse response = (DefaultHttpResponse) channel.readOutbound(); assertThat(response.status(), is(io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR)); verify(responseEnhancer).enhance(any(LiveHttpResponse.Transformer.class), any(LiveHttpRequest.class)); verify(errorListener, only()).proxyErrorOccurred(any(LiveHttpRequest.class), any(InetSocketAddress.class), eq(INTERNAL_SERVER_ERROR), any(RuntimeException.class)); }
### Question: HttpPipelineHandler extends SimpleChannelInboundHandler<LiveHttpRequest> { @VisibleForTesting State state() { return this.stateMachine.currentState(); } private HttpPipelineHandler(Builder builder, RequestTracker tracker); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelInactive(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); }### Answer: @Test public void responseObservableEmitsErrorInWaitingForResponseState() throws Exception { setupHandlerTo(WAITING_FOR_RESPONSE); responseObservable.onError(new RuntimeException("Request Send Error")); assertThat(responseUnsubscribed.get(), is(true)); writerFuture.complete(null); verify(statsCollector).onComplete(request.id(), 500); assertThat(handler.state(), is(TERMINATED)); } @Test public void responseObservableEmitsErrorInSendingResponseState() throws Exception { setupHandlerTo(SENDING_RESPONSE); responseObservable.onError(new RuntimeException("Spurious error occurred")); assertThat(handler.state(), is(SENDING_RESPONSE)); verify(errorListener).proxyingFailure(any(LiveHttpRequest.class), any(LiveHttpResponse.class), any(Throwable.class)); } @Test public void responseWriteFailsInSendingResponseState() throws Exception { RuntimeException cause = new RuntimeException("Response write failed"); setupHandlerTo(SENDING_RESPONSE); writerFuture.completeExceptionally(cause); assertThat(responseUnsubscribed.get(), is(true)); verify(statsCollector).onTerminate(request.id()); verify(errorListener).proxyWriteFailure(any(LiveHttpRequest.class), eq(response(OK).build()), any(RuntimeException.class)); assertThat(handler.state(), is(TERMINATED)); }
### Question: ExceptionStatusMapper { Optional<HttpResponseStatus> statusFor(Throwable throwable) { List<HttpResponseStatus> matchingStatuses = this.multimap.entries().stream() .filter(entry -> entry.getValue().isInstance(throwable)) .sorted(comparing(entry -> entry.getKey().code())) .map(Map.Entry::getKey) .collect(toList()); if (matchingStatuses.size() > 1) { LOG.error("Multiple matching statuses for throwable={} statuses={}", throwable, matchingStatuses); return Optional.empty(); } return matchingStatuses.stream().findFirst(); } private ExceptionStatusMapper(Builder builder); }### Answer: @Test public void returnsEmptyIfNoStatusMatches() { assertThat(mapper.statusFor(new UnmappedException()), isAbsent()); } @Test public void retrievesStatus() { assertThat(mapper.statusFor(new Exception1()), isValue(REQUEST_TIMEOUT)); } @Test public void exceptionMayNotBeMappedToMultipleExceptions() { ExceptionStatusMapper mapper = new ExceptionStatusMapper.Builder() .add(BAD_GATEWAY, Exception1.class) .add(GATEWAY_TIMEOUT, DoubleMappedException.class) .build(); LoggingTestSupport support = new LoggingTestSupport(ExceptionStatusMapper.class); Optional<HttpResponseStatus> status; try { status = mapper.statusFor(new DoubleMappedException()); } finally { assertThat(support.lastMessage(), is(loggingEvent(ERROR, "Multiple matching statuses for throwable=" + quote(DoubleMappedException.class.getName()) + " statuses=\\[502 Bad Gateway, 504 Gateway Timeout\\]" ))); } assertThat(status, isAbsent()); }
### Question: CurrentRequestTracker implements RequestTracker { public void trackRequest(LiveHttpRequest request, Supplier<String> state) { if (currentRequests.containsKey(request.id())) { currentRequests.get(request.id()).setCurrentThread(Thread.currentThread()); } else { currentRequests.put(request.id(), new CurrentRequest(request, state)); } } void trackRequest(LiveHttpRequest request, Supplier<String> state); void trackRequest(LiveHttpRequest request); void markRequestAsSent(LiveHttpRequest request); void endTrack(LiveHttpRequest request); Collection<CurrentRequest> currentRequests(); static final CurrentRequestTracker INSTANCE; }### Answer: @Test public void testTrackRequest() { tracker.trackRequest(req1); assertThat(tracker.currentRequests().iterator().next().request(), is(req1.toString())); }
### Question: CurrentRequestTracker implements RequestTracker { public void endTrack(LiveHttpRequest request) { currentRequests.remove(request.id()); } void trackRequest(LiveHttpRequest request, Supplier<String> state); void trackRequest(LiveHttpRequest request); void markRequestAsSent(LiveHttpRequest request); void endTrack(LiveHttpRequest request); Collection<CurrentRequest> currentRequests(); static final CurrentRequestTracker INSTANCE; }### Answer: @Test public void testEndTrack() { tracker.trackRequest(req1); assertThat(tracker.currentRequests().size(), is(1)); assertThat(tracker.currentRequests().iterator().next().request(), is(req1.toString())); tracker.endTrack(req1); assertThat(tracker.currentRequests().size(), is(0)); }
### Question: RequestStatsCollector implements RequestProgressListener { @Override public void onRequest(Object requestId) { Long previous = this.ongoingRequests.putIfAbsent(requestId, nanoClock.nanoTime()); if (previous == null) { this.outstandingRequests.inc(); this.requestsIncoming.mark(); } } RequestStatsCollector(MetricRegistry metrics); RequestStatsCollector(MetricRegistry metrics, NanoClock nanoClock); @Override void onRequest(Object requestId); @Override void onComplete(Object requestId, int responseStatus); @Override void onTerminate(Object requestId); }### Answer: @Test public void ignoresAdditionalCallsToOnRequestWithSameRequestId() { sink.onRequest(requestId); assertThat(metrics.counter("outstanding").getCount(), is(1L)); sink.onRequest(requestId); assertThat(metrics.counter("outstanding").getCount(), is(1L)); }
### Question: CompositeHttpErrorStatusListener implements HttpErrorStatusListener { @Override public void proxyWriteFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause) { listeners.forEach(listener -> listener.proxyWriteFailure(request, response, cause)); } CompositeHttpErrorStatusListener(List<HttpErrorStatusListener> listeners); @Override void proxyErrorOccurred(Throwable cause); @Override void proxyWriteFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); @Override void proxyingFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); @Override void proxyErrorOccurred(HttpResponseStatus status, Throwable cause); @Override void proxyErrorOccurred(LiveHttpRequest request, InetSocketAddress clientAddress, HttpResponseStatus status, Throwable cause); }### Answer: @Test public void propagatesProxyWriteFailures() { IOException cause = new IOException(); listener.proxyWriteFailure(request, response, cause); verify(delegate1).proxyWriteFailure(request, response, cause); verify(delegate2).proxyWriteFailure(request, response, cause); verify(delegate3).proxyWriteFailure(request, response, cause); }
### Question: CompositeHttpErrorStatusListener implements HttpErrorStatusListener { @Override public void proxyingFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause) { listeners.forEach(listener -> listener.proxyingFailure(request, response, cause)); } CompositeHttpErrorStatusListener(List<HttpErrorStatusListener> listeners); @Override void proxyErrorOccurred(Throwable cause); @Override void proxyWriteFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); @Override void proxyingFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); @Override void proxyErrorOccurred(HttpResponseStatus status, Throwable cause); @Override void proxyErrorOccurred(LiveHttpRequest request, InetSocketAddress clientAddress, HttpResponseStatus status, Throwable cause); }### Answer: @Test public void propagatesProxyingFailures() { IOException cause = new IOException(); listener.proxyingFailure(request, response, cause); verify(delegate1).proxyingFailure(request, response, cause); verify(delegate2).proxyingFailure(request, response, cause); verify(delegate3).proxyingFailure(request, response, cause); }
### Question: AggregateRequestBodyExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return request.aggregate(10000) .map(fullRequest -> { String body = fullRequest.bodyAs(UTF_8); return fullRequest.newBuilder() .body(body + config.extraText(), UTF_8) .build().stream(); }).flatMap(chain::proceed); } AggregateRequestBodyExamplePlugin(Config config); @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer: @Test public void contentIsModified() { Config config = new Config("MyExtraText"); String originalBody = "OriginalBody"; AggregateRequestBodyExamplePlugin plugin = new AggregateRequestBodyExamplePlugin(config); LiveHttpRequest request = LiveHttpRequest.post("/", ByteStream.from(originalBody, UTF_8)).build(); HttpInterceptor.Chain chain = intRequest -> { String requestBody = Mono.from(intRequest.aggregate(100)).block().bodyAs(UTF_8); assertThat(requestBody, is(originalBody + config.extraText())); return Eventual.of(LiveHttpResponse.response().build()); }; Mono.from(plugin.intercept(request, chain)).block(); }
### Question: ReplaceLiveContentExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return chain.proceed(request) .map(response -> response.newBuilder() .body(body -> body.replaceWith(ByteStream.from(config.replacement(), UTF_8))) .build()); } ReplaceLiveContentExamplePlugin(ReplaceLiveContentExampleConfig config); @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer: @Test public void replacesLiveContent() { ReplaceLiveContentExampleConfig config = new ReplaceLiveContentExampleConfig("myNewContent"); ReplaceLiveContentExamplePlugin plugin = new ReplaceLiveContentExamplePlugin(config); LiveHttpRequest request = get("/").build(); HttpInterceptor.Chain chain = request1 -> Eventual.of(LiveHttpResponse.response().build()); HttpResponse response = Mono.from(plugin.intercept(request, chain) .flatMap(liveResponse -> liveResponse.aggregate(100))) .block(); assertThat(response.bodyAs(UTF_8), is("myNewContent")); }
### Question: ModifyHeadersExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { LiveHttpRequest newRequest = request.newBuilder() .header("myRequestHeader", config.requestHeaderValue()) .build(); return chain.proceed(newRequest).map(response -> response.newBuilder() .header("myResponseHeader", config.responseHeaderValue()) .build() ); } ModifyHeadersExamplePlugin(ModifyHeadersExamplePluginConfig config); @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); @Override Map<String, HttpHandler> adminInterfaceHandlers(); }### Answer: @Test public void addsExtraHeaders() { HttpInterceptor.Chain chain = request -> { assertThat(request.header("myRequestHeader").orElse(null), is("foo")); return Eventual.of(response(OK).build()); }; LiveHttpRequest request = get("/foo") .build(); LiveHttpResponse response = Mono.from(plugin.intercept(request, chain)).block(); assertThat(response.header("myResponseHeader").orElse(null), is("bar")); }
### Question: ModifyContentByAggregationExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return chain.proceed(request) .flatMap(response -> response.aggregate(10000)) .map(response -> { String body = response.bodyAs(UTF_8); return response.newBuilder() .body(body + config.extraText(), UTF_8) .build(); }) .map(HttpResponse::stream); } ModifyContentByAggregationExamplePlugin(Config config); @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer: @Test public void modifiesContent() { Config config = new Config("MyExtraText"); ModifyContentByAggregationExamplePlugin plugin = new ModifyContentByAggregationExamplePlugin(config); LiveHttpRequest request = get("/").build(); HttpInterceptor.Chain chain = anyRequest -> Eventual.of(response() .body("OriginalBody", UTF_8) .build() .stream()); HttpResponse response = Mono.from(plugin.intercept(request, chain) .flatMap(liveResponse -> liveResponse.aggregate(100))) .block(); assertThat(response.bodyAs(UTF_8), is("OriginalBodyMyExtraText")); }
### Question: EarlyReturnExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { if (request.header("X-Respond").isPresent()) { return Eventual.of(HttpResponse.response(OK) .header(CONTENT_TYPE, "text/plain; charset=utf-8") .body("Responding from plugin", UTF_8) .build() .stream()); } else { return chain.proceed(request); } } @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer: @Test public void returnsEarlyWhenHeaderIsPresent() { EarlyReturnExamplePlugin plugin = new EarlyReturnExamplePlugin(); LiveHttpRequest request = LiveHttpRequest.get("/") .header("X-Respond", "foo") .build(); HttpInterceptor.Chain chain = request1 -> Eventual.of(LiveHttpResponse.response().build()); Eventual<LiveHttpResponse> eventualLive = plugin.intercept(request, chain); Eventual<HttpResponse> eventual = eventualLive.flatMap(response -> response.aggregate(100)); HttpResponse response = Mono.from(eventual).block(); assertThat(response.bodyAs(UTF_8), is("Responding from plugin")); }
### Question: InterceptorPipelineBuilder { public RoutingObject build() { List<HttpInterceptor> interceptors = ImmutableList.copyOf(instrument(plugins, environment)); return new HttpInterceptorPipeline(interceptors, handler, trackRequests); } InterceptorPipelineBuilder(Environment environment, Iterable<NamedPlugin> plugins, RoutingObject handler, boolean trackRequests); RoutingObject build(); }### Answer: @Test public void buildsPipelineWithInterceptors() throws Exception { HttpHandler pipeline = new InterceptorPipelineBuilder(environment, plugins, handler, false).build(); LiveHttpResponse response = Mono.from(pipeline.handle(get("/foo").build(), requestContext())).block(); assertThat(response.header("plug1"), isValue("1")); assertThat(response.header("plug2"), isValue("1")); assertThat(response.status(), is(OK)); }
### Question: HttpErrorStatusMetrics implements HttpErrorStatusListener { @Override public void proxyErrorOccurred(HttpResponseStatus status, Throwable cause) { record(status); if (isError(status)) { incrementExceptionCounter(cause, status); } } HttpErrorStatusMetrics(MetricRegistry metricRegistry); @Override void proxyErrorOccurred(HttpResponseStatus status, Throwable cause); @Override void proxyErrorOccurred(Throwable cause); @Override void proxyErrorOccurred(LiveHttpRequest request, InetSocketAddress clientAddress, HttpResponseStatus status, Throwable cause); @Override void proxyWriteFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); @Override void proxyingFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); }### Answer: @Test public void pluginExceptionsAreNotRecordedAsStyxUnexpectedErrors() { errorListener.proxyErrorOccurred(INTERNAL_SERVER_ERROR, new PluginException("bad")); assertThat(count("styx.response.status.500"), is(1)); assertThat(statusCountsExcluding("styx.response.status.500"), everyItem(is(0))); assertThat(meterCount("styx.errors"), is(0)); } @Test public void nonErrorStatusesIsNotRecordedForProxyEvenIfExceptionIsSupplied() { MetricRegistry registry = mock(MetricRegistry.class); HttpErrorStatusMetrics reporter = new HttpErrorStatusMetrics(registry); reset(registry); reporter.proxyErrorOccurred(OK, new RuntimeException("This shouldn't happen")); verifyZeroInteractions(registry); }
### Question: ViaHeaderAppendingInterceptor implements HttpInterceptor { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { LiveHttpRequest newRequest = request.newBuilder() .header(VIA, viaHeader(request)) .build(); return chain.proceed(newRequest) .map(response -> response.newBuilder() .header(VIA, viaHeader(response)) .build()); } ViaHeaderAppendingInterceptor(); ViaHeaderAppendingInterceptor(final String via); @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer: @Test public void appendsHttp10RequestVersionInResponseViaHeader() throws Exception { LiveHttpResponse response = Mono.from(interceptor.intercept(get("/foo").build(), ANY_RESPONSE_HANDLER)).block(); assertThat(response.headers().get(VIA), isValue("1.1 styx")); } @Test public void appendsViaHeaderValueAtEndOfListInResponse() throws Exception { LiveHttpResponse response = Mono.from(interceptor.intercept(get("/foo").build(), returnsResponse(response() .header(VIA, "1.0 ricky, 1.1 mertz, 1.0 lucy") .build()))).block(); assertThat(response.headers().get(VIA), isValue("1.0 ricky, 1.1 mertz, 1.0 lucy, 1.1 styx")); }
### Question: ConfigurationContextResolverInterceptor implements HttpInterceptor { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { Configuration.Context context = configurationContextResolver.resolve(request); chain.context().add("config.context", context); return chain.proceed(request); } ConfigurationContextResolverInterceptor(ConfigurationContextResolver configurationContextResolver); @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer: @Test public void resolvesConfigurationContext() { LiveHttpRequest request = get("/").build(); Configuration.Context context = context(ImmutableMap.of("key1", "value1", "key2", "value2")); ConfigurationContextResolver configurationContextResolver = configurationContextResolver(request, context); ConfigurationContextResolverInterceptor interceptor = new ConfigurationContextResolverInterceptor(configurationContextResolver); TestChain chain = new TestChain(); Eventual<LiveHttpResponse> responseObservable = interceptor.intercept(request, chain); assertThat(Mono.from(responseObservable).block(), hasStatus(OK)); assertThat(chain.proceedWasCalled, is(true)); assertThat(chain.context().get("config.context", Configuration.Context.class), is(context)); }
### Question: HopByHopHeadersRemovingInterceptor implements HttpInterceptor { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return chain.proceed(removeHopByHopHeaders(request)) .map(HopByHopHeadersRemovingInterceptor::removeHopByHopHeaders); } @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer: @Test public void removesHopByHopHeadersFromResponse() throws Exception { LiveHttpResponse response = Mono.from(interceptor.intercept(get("/foo").build(), returnsResponse(response() .header(TE, "foo") .header(PROXY_AUTHENTICATE, "foo") .header(PROXY_AUTHORIZATION, "bar") .build()))).block(); assertThat(response.header(TE), isAbsent()); assertThat(response.header(PROXY_AUTHENTICATE), isAbsent()); assertThat(response.header(PROXY_AUTHORIZATION), isAbsent()); } @Test public void removesConnectionHeadersFromResponse() throws Exception { LiveHttpResponse response = Mono.from(interceptor.intercept(get("/foo").build(), returnsResponse(response() .header(CONNECTION, "Foo, Bar, Baz") .header("Foo", "abc") .header("Foo", "def") .header("Bar", "one, two, three") .build()))).block(); assertThat(response.header(CONNECTION), isAbsent()); assertThat(response.header("Foo"), isAbsent()); assertThat(response.header("Bar"), isAbsent()); assertThat(response.header("Baz"), isAbsent()); }
### Question: FileBackedBackendServicesRegistry extends AbstractStyxService implements Registry<BackendService>, FileChangeMonitor.Listener { @Override public CompletableFuture<ReloadResult> reload() { return this.fileBackedRegistry.reload() .thenApply(outcome -> logReloadAttempt("Admin Interface", outcome)); } @VisibleForTesting FileBackedBackendServicesRegistry(FileBackedRegistry<BackendService> fileBackedRegistry, FileMonitor fileChangeMonitor); @VisibleForTesting FileBackedBackendServicesRegistry(Resource originsFile, FileMonitor fileChangeMonitor); static FileBackedBackendServicesRegistry create(String originsFile); @Override Registry<BackendService> addListener(ChangeListener<BackendService> changeListener); @Override Registry<BackendService> removeListener(ChangeListener<BackendService> changeListener); @Override CompletableFuture<ReloadResult> reload(); @Override Iterable<BackendService> get(); @Override CompletableFuture<Void> stop(); @Override void fileChanged(); @Override String toString(); }### Answer: @Test public void relaysReloadToRegistryDelegate() { FileBackedRegistry<BackendService> delegate = mock(FileBackedRegistry.class); when(delegate.reload()).thenReturn(CompletableFuture.completedFuture(ReloadResult.reloaded("relaod ok"))); registry = new FileBackedBackendServicesRegistry(delegate, FileMonitor.DISABLED); registry.reload(); verify(delegate).reload(); } @Test public void reloadsDelegateRegistryOnStart() { FileBackedRegistry<BackendService> delegate = mock(FileBackedRegistry.class); when(delegate.reload()).thenReturn(completedFuture(reloaded("Changes applied!"))); registry = new FileBackedBackendServicesRegistry(delegate, FileMonitor.DISABLED); await(registry.start()); verify(delegate).reload(); }
### Question: FileBackedBackendServicesRegistry extends AbstractStyxService implements Registry<BackendService>, FileChangeMonitor.Listener { @Override public Registry<BackendService> addListener(ChangeListener<BackendService> changeListener) { return this.fileBackedRegistry.addListener(changeListener); } @VisibleForTesting FileBackedBackendServicesRegistry(FileBackedRegistry<BackendService> fileBackedRegistry, FileMonitor fileChangeMonitor); @VisibleForTesting FileBackedBackendServicesRegistry(Resource originsFile, FileMonitor fileChangeMonitor); static FileBackedBackendServicesRegistry create(String originsFile); @Override Registry<BackendService> addListener(ChangeListener<BackendService> changeListener); @Override Registry<BackendService> removeListener(ChangeListener<BackendService> changeListener); @Override CompletableFuture<ReloadResult> reload(); @Override Iterable<BackendService> get(); @Override CompletableFuture<Void> stop(); @Override void fileChanged(); @Override String toString(); }### Answer: @Test public void relaysAddListenerToRegistryDelegate() { FileBackedRegistry<BackendService> delegate = mock(FileBackedRegistry.class); Registry.ChangeListener<BackendService> listener = mock(Registry.ChangeListener.class); registry = new FileBackedBackendServicesRegistry(delegate, FileMonitor.DISABLED); registry.addListener(listener); verify(delegate).addListener(eq(listener)); }
### Question: FileBackedBackendServicesRegistry extends AbstractStyxService implements Registry<BackendService>, FileChangeMonitor.Listener { @Override public Iterable<BackendService> get() { return this.fileBackedRegistry.get(); } @VisibleForTesting FileBackedBackendServicesRegistry(FileBackedRegistry<BackendService> fileBackedRegistry, FileMonitor fileChangeMonitor); @VisibleForTesting FileBackedBackendServicesRegistry(Resource originsFile, FileMonitor fileChangeMonitor); static FileBackedBackendServicesRegistry create(String originsFile); @Override Registry<BackendService> addListener(ChangeListener<BackendService> changeListener); @Override Registry<BackendService> removeListener(ChangeListener<BackendService> changeListener); @Override CompletableFuture<ReloadResult> reload(); @Override Iterable<BackendService> get(); @Override CompletableFuture<Void> stop(); @Override void fileChanged(); @Override String toString(); }### Answer: @Test public void relaysGetToRegistryDelegate() { FileBackedRegistry<BackendService> delegate = mock(FileBackedRegistry.class); registry = new FileBackedBackendServicesRegistry(delegate, FileMonitor.DISABLED); registry.get(); verify(delegate).get(); }
### Question: HealthCheckTimestamp extends HealthCheck { @Override protected Result check() { ZonedDateTime now = Instant.ofEpochMilli(clock.tickMillis()).atZone(UTC); return healthy(DATE_TIME_FORMATTER.format(now)); } HealthCheckTimestamp(); HealthCheckTimestamp(Clock clock); static final String NAME; }### Answer: @Test public void printsTheCurrentTime() throws Exception { assertThat(healthCheckTimestamp.check().toString(), matchesRegex( "Result\\{isHealthy=true, message=1970-01-01T00:00:00.001\\+0000, timestamp=.*\\}")); }
### Question: PathPrefixRouter implements RoutingObject { @Override public Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context) { String path = request.path(); for (PrefixRoute route : routes) { if (path.startsWith(route.prefix)) { return route.routingObject.handle(request, context); } } return Eventual.error(new NoServiceConfiguredException(path)); } PathPrefixRouter(PrefixRoute[] routes); @Override Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context); @Override CompletableFuture<Void> stop(); static final Schema.FieldType SCHEMA; }### Answer: @Test public void no_routes_always_throws_NoServiceConfiguredException() throws Exception { PathPrefixRouter router = buildRouter(emptyMap()); assertThrows(NoServiceConfiguredException.class, () -> Mono.from(router.handle(LiveHttpRequest.get("/").build(), null)).block() ); }
### Question: StandardHttpPipeline implements HttpHandler { @Override public Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context) { HttpInterceptorChain interceptorsChain = new HttpInterceptorChain(interceptors, 0, handler, context, requestTracker); return interceptorsChain.proceed(request); } StandardHttpPipeline(HttpHandler handler); StandardHttpPipeline(List<HttpInterceptor> interceptors, HttpHandler handler, RequestTracker requestTracker); @Override Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context); }### Answer: @Test public void sendsExceptionUponMultipleSubscription() { HttpHandler handler = (request, context) -> Eventual.of(response(OK).build()); StandardHttpPipeline pipeline = new StandardHttpPipeline(handler); Eventual<LiveHttpResponse> responseObservable = pipeline.handle(get("/").build(), requestContext()); LiveHttpResponse response = Mono.from(responseObservable).block(); assertThat(response.status(), is(OK)); assertThrows(IllegalStateException.class, () -> Mono.from(responseObservable).block()); }
### Question: StyxServerComponents { public List<NamedPlugin> plugins() { return plugins; } private StyxServerComponents(Builder builder); boolean showBanner(); Environment environment(); Map<String, StyxService> services(); List<NamedPlugin> plugins(); StyxObjectStore<RoutingObjectRecord> routeDatabase(); StyxObjectStore<StyxObjectRecord<StyxService>> servicesDatabase(); StyxObjectStore<StyxObjectRecord<NettyExecutor>> executors(); StyxObjectStore<StyxObjectRecord<InetServer>> serversDatabase(); RoutingObjectFactory.Context routingObjectFactoryContext(); NettyExecutor clientExecutor(); StartupConfig startupConfig(); }### Answer: @Test public void loadsPlugins() { ConfiguredPluginFactory f1 = new ConfiguredPluginFactory("plugin1", any -> stubPlugin("MyResponse1")); ConfiguredPluginFactory f2 = new ConfiguredPluginFactory("plugin2", any -> stubPlugin("MyResponse2")); StyxServerComponents components = new StyxServerComponents.Builder() .styxConfig(new StyxConfig()) .pluginFactories(ImmutableList.of(f1, f2)) .build(); List<NamedPlugin> plugins = components.plugins(); List<String> names = plugins.stream().map(NamedPlugin::name).collect(toList()); assertThat(names, contains("plugin1", "plugin2")); }
### Question: StyxServerComponents { public Map<String, StyxService> services() { return services; } private StyxServerComponents(Builder builder); boolean showBanner(); Environment environment(); Map<String, StyxService> services(); List<NamedPlugin> plugins(); StyxObjectStore<RoutingObjectRecord> routeDatabase(); StyxObjectStore<StyxObjectRecord<StyxService>> servicesDatabase(); StyxObjectStore<StyxObjectRecord<NettyExecutor>> executors(); StyxObjectStore<StyxObjectRecord<InetServer>> serversDatabase(); RoutingObjectFactory.Context routingObjectFactoryContext(); NettyExecutor clientExecutor(); StartupConfig startupConfig(); }### Answer: @Test public void loadsServices() { StyxServerComponents components = new StyxServerComponents.Builder() .styxConfig(new StyxConfig()) .services((env, routeDb) -> ImmutableMap.of( "service1", mock(StyxService.class), "service2", mock(StyxService.class))) .build(); Map<String, StyxService> services = components.services(); assertThat(services.keySet(), containsInAnyOrder("service1", "service2")); } @Test public void exposesAdditionalServices() { StyxServerComponents components = new StyxServerComponents.Builder() .styxConfig(new StyxConfig()) .additionalServices(ImmutableMap.of( "service1", mock(StyxService.class), "service2", mock(StyxService.class))) .build(); Map<String, StyxService> services = components.services(); assertThat(services.keySet(), containsInAnyOrder("service1", "service2")); }
### Question: StyxServerComponents { public Environment environment() { return environment; } private StyxServerComponents(Builder builder); boolean showBanner(); Environment environment(); Map<String, StyxService> services(); List<NamedPlugin> plugins(); StyxObjectStore<RoutingObjectRecord> routeDatabase(); StyxObjectStore<StyxObjectRecord<StyxService>> servicesDatabase(); StyxObjectStore<StyxObjectRecord<NettyExecutor>> executors(); StyxObjectStore<StyxObjectRecord<InetServer>> serversDatabase(); RoutingObjectFactory.Context routingObjectFactoryContext(); NettyExecutor clientExecutor(); StartupConfig startupConfig(); }### Answer: @Test public void createsEnvironment() { Configuration config = new Configuration.MapBackedConfiguration() .set("foo", "abc") .set("bar", "def"); StyxServerComponents components = new StyxServerComponents.Builder() .styxConfig(new StyxConfig(config)) .build(); Environment environment = components.environment(); assertThat(environment.configuration().get("foo", String.class), isValue("abc")); assertThat(environment.configuration().get("bar", String.class), isValue("def")); assertThat(environment.eventBus(), is(notNullValue())); assertThat(environment.metricRegistry(), is(notNullValue())); }
### Question: CoreMetrics { public static void registerCoreMetrics(Version buildInfo, MetricRegistry metrics) { registerVersionMetric(buildInfo, metrics); registerJvmMetrics(metrics); metrics.register("os", new OperatingSystemMetricSet()); } private CoreMetrics(); static void registerCoreMetrics(Version buildInfo, MetricRegistry metrics); }### Answer: @Test public void registersVersionMetric() { MetricRegistry metrics = new CodaHaleMetricRegistry(); CoreMetrics.registerCoreMetrics(version, metrics); Gauge gauge = metrics.getGauges().get("styx.version.buildnumber"); assertThat(gauge.getValue(), is(3)); } @Test public void registersJvmMetrics() { MetricRegistry metrics = new CodaHaleMetricRegistry(); CoreMetrics.registerCoreMetrics(version, metrics); Map<String, Gauge> gauges = metrics.getGauges(); assertThat(gauges.keySet(), hasItems( "jvm.thread.blocked.count", "jvm.thread.count", "jvm.thread.daemon.count", "jvm.thread.deadlock.count", "jvm.thread.deadlocks", "jvm.thread.new.count", "jvm.thread.runnable.count", "jvm.thread.terminated.count", "jvm.thread.timed_waiting.count", "jvm.thread.waiting.count", "jvm.uptime", "jvm.uptime.formatted" )); } @Test public void registersOperatingSystemMetrics() { MetricRegistry metrics = new CodaHaleMetricRegistry(); CoreMetrics.registerCoreMetrics(version, metrics); Map<String, Gauge> gauges = metrics.getGauges(); assertThat(gauges.keySet(), hasItems( "os.process.cpu.load", "os.process.cpu.time", "os.system.cpu.load", "os.memory.physical.free", "os.memory.physical.total", "os.memory.virtual.committed", "os.swapSpace.free", "os.swapSpace.total" )); }
### Question: ProcessStartedEventConverter extends BaseEventToEntityConverter { @Override protected ProcessStartedAuditEventEntity createEventEntity(CloudRuntimeEvent cloudRuntimeEvent) { return new ProcessStartedAuditEventEntity((CloudProcessStartedEvent) cloudRuntimeEvent); } ProcessStartedEventConverter(EventContextInfoAppender eventContextInfoAppender); @Override String getSupportedEvent(); }### Answer: @Test public void createEventEntityShouldSetAllNonProcessContextRelatedFields() { CloudProcessStartedEventImpl event = buildProcessStartedEvent(); ProcessStartedAuditEventEntity auditEventEntity = eventConverter.createEventEntity(event); assertThat(auditEventEntity).isNotNull(); assertThat(auditEventEntity.getEventId()).isEqualTo(event.getId()); assertThat(auditEventEntity.getTimestamp()).isEqualTo(event.getTimestamp()); assertThat(auditEventEntity.getAppName()).isEqualTo(event.getAppName()); assertThat(auditEventEntity.getAppVersion()).isEqualTo(event.getAppVersion()); assertThat(auditEventEntity.getServiceName()).isEqualTo(event.getServiceName()); assertThat(auditEventEntity.getServiceFullName()).isEqualTo(event.getServiceFullName()); assertThat(auditEventEntity.getServiceType()).isEqualTo(event.getServiceType()); assertThat(auditEventEntity.getServiceVersion()).isEqualTo(event.getServiceVersion()); assertThat(auditEventEntity.getMessageId()).isEqualTo(event.getMessageId()); assertThat(auditEventEntity.getSequenceNumber()).isEqualTo(event.getSequenceNumber()); assertThat(auditEventEntity.getProcessInstance()).isEqualTo(event.getEntity()); } @Test public void convertToEntityShouldReturnCreatedEntity() { ProcessStartedAuditEventEntity auditEventEntity = new ProcessStartedAuditEventEntity(); CloudProcessStartedEventImpl cloudRuntimeEvent = new CloudProcessStartedEventImpl(); doReturn(auditEventEntity).when(eventConverter).createEventEntity(cloudRuntimeEvent); AuditEventEntity convertedEntity = eventConverter.convertToEntity(cloudRuntimeEvent); assertThat(convertedEntity).isEqualTo(auditEventEntity); }
### Question: ProcessStartedEventConverter extends BaseEventToEntityConverter { @Override protected CloudRuntimeEventImpl<?, ?> createAPIEvent(AuditEventEntity auditEventEntity) { ProcessStartedAuditEventEntity processStartedAuditEventEntity = (ProcessStartedAuditEventEntity) auditEventEntity; return new CloudProcessStartedEventImpl(processStartedAuditEventEntity.getEventId(), processStartedAuditEventEntity.getTimestamp(), processStartedAuditEventEntity.getProcessInstance()); } ProcessStartedEventConverter(EventContextInfoAppender eventContextInfoAppender); @Override String getSupportedEvent(); }### Answer: @Test public void convertToAPIShouldCreateAPIEventAndCallEventContextInfoAppender() { ProcessStartedAuditEventEntity auditEventEntity = new ProcessStartedAuditEventEntity(); CloudProcessStartedEventImpl apiEvent = new CloudProcessStartedEventImpl(); doReturn(apiEvent).when(eventConverter).createAPIEvent(auditEventEntity); CloudProcessStartedEventImpl updatedApiEvent = new CloudProcessStartedEventImpl(); given(eventContextInfoAppender.addProcessContextInfoToApiEvent(apiEvent, auditEventEntity)).willReturn(updatedApiEvent); CloudRuntimeEvent convertedEvent = eventConverter.convertToAPI(auditEventEntity); assertThat(convertedEvent).isEqualTo(updatedApiEvent); verify(eventContextInfoAppender).addProcessContextInfoToApiEvent(apiEvent, auditEventEntity); }
### Question: McqBaseManager { public static String status() { StringBuilder sb = new StringBuilder(512); sb.append("\r\nreading_mcq(yangwm,true):\t"); sb.append(IS_ALL_READ.get()); return sb.toString(); } static void stopReadAll(); static void startReadAll(); static String status(); static AtomicBoolean IS_ALL_READ; }### Answer: @Test public void testStatus() { String result = McqBaseManager.status(); Assert.assertEquals("\r\nreading_mcq(yangwm,true):\ttrue", result); ApiLogger.debug("testStatus result:" + result); }
### Question: ShardingUtil { public static<T> Map<Integer, T> parseClients(Map<String, T> clientsConfig){ Map<Integer, T> shardingClients = new HashMap<Integer, T>(); for(Map.Entry<String, T> entry : clientsConfig.entrySet()){ List<Integer> dbIdxs = parseDbIdx(entry.getKey()); T client = entry.getValue(); for(Integer dbIdx : dbIdxs){ shardingClients.put(dbIdx, client); } } return shardingClients; } static Map<Integer, T> parseClients(Map<String, T> clientsConfig); }### Answer: @Test public void testParseClients() { Map<String, Integer> clientsConfig = new HashMap<String, Integer>(); clientsConfig.put("1", new Integer("11")); clientsConfig.put("2", new Integer("21")); clientsConfig.put("3", new Integer("31")); clientsConfig.put("4", new Integer("41")); Map<Integer, Integer> clients = ShardingUtil.parseClients(clientsConfig); ApiLogger.debug("testParseClients clients:" + clients); Assert.assertEquals(new Integer("11"), clients.get(new Integer("1"))); Assert.assertEquals(new Integer("21"), clients.get(new Integer("2"))); Assert.assertEquals(new Integer("31"), clients.get(new Integer("3"))); Assert.assertEquals(new Integer("41"), clients.get(new Integer("4"))); }
### Question: PageWrapperUtil { public static <T> String toJson(PageWrapper<T> pageWrapper, String name, long[] values) { JsonBuilder json = new JsonBuilder(); if (values == null) { json.append(name, "[]"); } else { json.appendStrArr(name, values); } appendJson(json, pageWrapper); json.flip(); return json.toString(); } static String toJson(PageWrapper<T> pageWrapper, String name, long[] values); static String toJson(PageWrapper<T> pageWrapper, String name, Jsonable[] values); static PageWrapper<long[]> wrap(long[] ids, int count); static int getPageOffset(int page, int count); static PageWrapper<long[]> paginationAndReverse(long[] ids, PaginationParam paginationParam); static PageWrapper<long[]> paginationAndReverse(long[] ids, int idsLen, long sinceId, long maxId, int count, int page); static int[] calculatePaginationByReverse(long[] ids, int idsLen, long sinceId, long maxId, int count, int page); static void calculateCursorByReverse(PageWrapper<T> wrapper, long[] ids, int offset, int limit, int count); }### Answer: @Test public void testToJson() { long[] items = new long[10]; for (int i = 0; i < items.length; i++) { items[i] = (2300000000000000L + 101) + (items.length - 1 - i); } ArrayUtil.reverse(items); ApiLogger.debug(Arrays.toString(items)); int count = 20; int page = 1; long[] expecteds = Arrays.copyOf(items, items.length); ArrayUtil.reverse(expecteds); PaginationParam paginationParam = new PaginationParam.Builder().count(count).page(page).build(); PageWrapper<long[]> pageWrapper = PageWrapperUtil.paginationAndReverse(items, paginationParam); ApiLogger.debug(paginationParam + ", " + PageWrapperUtil.toJson(pageWrapper, "ids", pageWrapper.result)); }
### Question: PageWrapperUtil { public static PageWrapper<long[]> wrap(long[] ids, int count) { PageWrapper<long[]> wrapper = new PageWrapper<long[]>(0, 0, ids); wrapper.totalNumber = ids.length; if (ids.length > 1) { wrapper.nextCursor = ids[ids.length - 1] + MAX_ID_ADJECT; } wrapper.result = Arrays.copyOf(ids, Math.min(ids.length, count)); return wrapper; } static String toJson(PageWrapper<T> pageWrapper, String name, long[] values); static String toJson(PageWrapper<T> pageWrapper, String name, Jsonable[] values); static PageWrapper<long[]> wrap(long[] ids, int count); static int getPageOffset(int page, int count); static PageWrapper<long[]> paginationAndReverse(long[] ids, PaginationParam paginationParam); static PageWrapper<long[]> paginationAndReverse(long[] ids, int idsLen, long sinceId, long maxId, int count, int page); static int[] calculatePaginationByReverse(long[] ids, int idsLen, long sinceId, long maxId, int count, int page); static void calculateCursorByReverse(PageWrapper<T> wrapper, long[] ids, int offset, int limit, int count); }### Answer: @Test public void testWrap() { long[] items = new long[10]; for (int i = 0; i < items.length; i++) { items[i] = (2300000000000000L + 101) + (items.length - 1 - i); } ApiLogger.debug(Arrays.toString(items)); int count = 20; long[] expecteds = Arrays.copyOf(items, items.length); PageWrapper<long[]> pageWrapper = PageWrapperUtil.wrap(items, count); ApiLogger.debug(PageWrapperUtil.toJson(pageWrapper, "ids", pageWrapper.result)); Assert.assertArrayEquals(expecteds, pageWrapper.result); }
### Question: DaoUtil { public static String createMutiGetSql(String sql, int paramsSize){ StringBuilder sqlBuf = new StringBuilder().append(sql).append("( ?"); for(int i = 1; i < paramsSize; i++){ sqlBuf.append(", ?"); } return sqlBuf.append(")").toString(); } static String createMutiGetEncodedSql(String sql, int paramsSize); static String createMutiGetSql(String sql, int paramsSize); static String expendMultiGetSql(String sql, Object[] params); static Object[] expendMultiGetParams(Object[] params); static String createMultiInsertSql(String sqlPrefix, String sqlSuffix, int valuesSize); static String buildSql(String rawSql, String db, String table); }### Answer: @Test public void testCreateMutiGetSql() { String sql = "select a,b from table where a in "; int paramsSize = 10; String result = DaoUtil.createMutiGetSql(sql, paramsSize); ApiLogger.debug("testCreateMutiGetSql result:" + result); int count = 0; char[] chs = result.toCharArray(); for (char ch : chs) { if (ch == '?') { count++; } } if (paramsSize <= 0) { Assert.assertEquals(1, count); } else { Assert.assertEquals(paramsSize, count); } }
### Question: DaoUtil { public static String createMultiInsertSql(String sqlPrefix, String sqlSuffix, int valuesSize) { StringBuilder sb = new StringBuilder(sqlPrefix).append(sqlSuffix); for (int i = 1; i < valuesSize; i++) { sb.append(", "); sb.append(sqlSuffix); } return sb.toString(); } static String createMutiGetEncodedSql(String sql, int paramsSize); static String createMutiGetSql(String sql, int paramsSize); static String expendMultiGetSql(String sql, Object[] params); static Object[] expendMultiGetParams(Object[] params); static String createMultiInsertSql(String sqlPrefix, String sqlSuffix, int valuesSize); static String buildSql(String rawSql, String db, String table); }### Answer: @Test public void testCreateMultiInsertSql() { int paramsSize = 1; String result = DaoUtil.createMultiInsertSql("insert into test values", "(?, ?, ?, now())", paramsSize); System.out.println("testCreateMultiInsertSql paramsSize:" + paramsSize + ", result:" + result); Assert.assertEquals("insert into test values(?, ?, ?, now())", result); paramsSize = 3; result = DaoUtil.createMultiInsertSql("insert ignore into test values", "(?, ?, ?, now())", paramsSize); System.out.println("testCreateMultiInsertSql paramsSize:" + paramsSize + ", result:" + result); Assert.assertEquals("insert ignore into test values(?, ?, ?, now()), (?, ?, ?, now()), (?, ?, ?, now())", result); }
### Question: IdCreator implements IdCreate { public long generateId(int bizFlagValue){ return getNextId(bizFlagValue); } long generateId(int bizFlagValue); NaiveMemcacheClient getIdGenerateClient(); void setIdGenerateClient(NaiveMemcacheClient idGenerateClient); }### Answer: @Test public void testGenerateIdForUuid() { IdCreator idCreator = createIdCreator("testuuid:5001,testuuid:5001"); long t1 = System.currentTimeMillis(); int count = 10; for(int i = 0; i < count; i++){ long id = idCreator.generateId(2); ApiLogger.debug("IdCreatorTest testGenerateIdForUuid id:" + id); } long t2 = System.currentTimeMillis(); ApiLogger.debug(String.format("count=%s,time=%sms", count, (t2 - t1))); } @Test public void testGenerateIdForUid() { IdCreator idCreator = createIdCreator("testuid:5101,testuid:5101"); long t1 = System.currentTimeMillis(); int count = 10; for(int i = 0; i < count; i++){ long id = idCreator.generateId(2); ApiLogger.debug("IdCreatorTest testGenerateIdForUid id:" + id); } long t2 = System.currentTimeMillis(); ApiLogger.debug(String.format("count=%s,time=%sms", count, (t2 - t1))); }
### Question: WebExceptionFormat { public static String formatException(WebApiException e, String path, String type) { if (path == null) { throw new IllegalArgumentException(" path argument is null"); } ExcepFactor factor = e.getFactor(); if (type == null) { } String result; if ("xml".equals(type)) { result = String.format(xmlMsg, path, factor.getErrorCode(), e.getMessage()); } else if ("str".equals(type)) { result = String.format(strMsg, path, factor.getErrorCode(), e.getMessage(), factor.getErrorMsgCn()); } else { result = String.format(jsonMsg, path, factor.getErrorCode(), e.getMessage()); } return result; } static String formatException(WebApiException e, String path, String type); }### Answer: @Test public void testFormatException(){ WebApiException e = new WebApiException(ExcepFactor.E_PARAM_INVALID_ERROR, "param error"); String result = WebExceptionFormat.formatException(e, "/user/test", "json"); ApiLogger.debug("testFormatException result:" + result); }
### Question: TopN { public static long[] top(Collection<? extends VectorInterface> vectorItems, int n) { VectorInterface[] vectors = getVectors(vectorItems); return top(vectors, n); } static long[] top(Collection<? extends VectorInterface> vectorItems, int n); }### Answer: @Test public void testTopN() { Map<String, ? extends VectorInterface> vectorMap = getAllVectorMap(); for (int column = -1; column >= 0; column--) { ApiLogger.debug(column); } long[] result = TopN.top(vectorMap.values(), 20); ApiLogger.debug("result length:" + result.length + ", result" + Arrays.toString(result)); result = TopN.top(vectorMap.values(), 30); ApiLogger.debug("result length:" + result.length + ", result" + Arrays.toString(result)); result = TopN.top(vectorMap.values(), CommonConst.TIMELINE_SIZE); ApiLogger.debug("result length:" + result.length + ", result" + Arrays.toString(result)); }
### Question: TopNObject { public static Object[] top(Collection<? extends VectorInterface> vectorItems, int n) { return top(vectorItems, n, CommonConst.EMPTY_OBJECT_ARRAY); } static Object[] top(Collection<? extends VectorInterface> vectorItems, int n); static Object[] top(Collection<? extends VectorInterface> vectorItems, int n, Object[] newObject); }### Answer: @Test public void testTopN() { Map<String, ? extends VectorInterface> vectorMap = getAllVectorMap(); for (int column = -1; column >= 0; column--) { ApiLogger.debug(column); } Object[] result = (Object[]) TopNObject.top(vectorMap.values(), 20); ApiLogger.debug("result length:" + result.length + ", result" + Arrays.toString(result)); result = TopNObject.top(vectorMap.values(), 30, CommonConst.EMPTY_LONG_OBJECT_ARRAY); ApiLogger.debug("result length:" + result.length + ", result" + Arrays.toString(result)); result = TopNObject.top(vectorMap.values(), CommonConst.TIMELINE_SIZE, CommonConst.EMPTY_LONG_OBJECT_ARRAY); ApiLogger.debug("result length:" + result.length + ", result" + Arrays.toString(result)); }
### Question: JsonUtil { public static String toJsonStr(String value) { if (value == null) return null; StringBuilder buf = new StringBuilder(value.length()); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); switch(c) { case '"': buf.append("\\\""); break; case '\\': buf.append("\\\\"); break; case '\n': buf.append("\\n"); break; case '\r': buf.append("\\r"); break; case '\t': buf.append("\\t"); break; case '\f': buf.append("\\f"); break; case '\b': buf.append("\\b"); break; default: if (c < 32 || c == 127) { buf.append(" "); } else { buf.append(c); } } } return buf.toString(); } static String toJsonStr(String value); static boolean isValidJsonObject(String json); static boolean isValidJsonObject(String json, boolean allowBlank); static boolean isValidJsonArray(String json); static boolean isValidJsonArray(String json, boolean allowBlank); static String toJson(long[] ids); static String toJson(Jsonable[] values); }### Answer: @Test public void testToJsonStr() { Assert.assertEquals("dal\\\"?[]}das\\\\aa\\n33\\r24\\tkkh\\r86gg\\f11\\b", JsonUtil.toJsonStr("dal\"?[]}das\\aa\n33\r24\tkkh\r86gg\f11\b")); }
### Question: JsonUtil { public static boolean isValidJsonObject(String json){ return isValidJsonObject(json, false); } static String toJsonStr(String value); static boolean isValidJsonObject(String json); static boolean isValidJsonObject(String json, boolean allowBlank); static boolean isValidJsonArray(String json); static boolean isValidJsonArray(String json, boolean allowBlank); static String toJson(long[] ids); static String toJson(Jsonable[] values); }### Answer: @Test public void testIsValidJsonObject() { Assert.assertEquals(true, JsonUtil.isValidJsonObject("{}")); Assert.assertEquals(false, JsonUtil.isValidJsonObject("")); Assert.assertEquals(false, JsonUtil.isValidJsonObject(null)); Assert.assertEquals(true, JsonUtil.isValidJsonObject("{\"uid\":1750715731}")); Assert.assertEquals(true, JsonUtil.isValidJsonObject("{\"id\":10001}")); Assert.assertEquals(true, JsonUtil.isValidJsonObject("{}", true)); Assert.assertEquals(true, JsonUtil.isValidJsonObject("", true)); Assert.assertEquals(true, JsonUtil.isValidJsonObject(null, true)); }
### Question: JsonUtil { public static boolean isValidJsonArray(String json){ return isValidJsonArray(json, false); } static String toJsonStr(String value); static boolean isValidJsonObject(String json); static boolean isValidJsonObject(String json, boolean allowBlank); static boolean isValidJsonArray(String json); static boolean isValidJsonArray(String json, boolean allowBlank); static String toJson(long[] ids); static String toJson(Jsonable[] values); }### Answer: @Test public void testIsValidJsonArray() { Assert.assertEquals(true, JsonUtil.isValidJsonArray("[]")); Assert.assertEquals(false, JsonUtil.isValidJsonArray("")); Assert.assertEquals(false, JsonUtil.isValidJsonArray(null)); Assert.assertEquals(true, JsonUtil.isValidJsonArray("[{\"uid\":1750715731},{\"uid\":1821155363}]")); Assert.assertEquals(true, JsonUtil.isValidJsonArray("[1750715731, 1821155363]")); Assert.assertEquals(true, JsonUtil.isValidJsonArray("[]", true)); Assert.assertEquals(true, JsonUtil.isValidJsonArray("", true)); Assert.assertEquals(true, JsonUtil.isValidJsonArray(null, true)); }
### Question: JsonUtil { public static String toJson(long[] ids) { StringBuilder sb = new StringBuilder(); sb.append("["); if (ids != null) { for (int i = 0; i < ids.length; i++) { if (i > 0) { sb.append(", "); } sb.append(ids[i]); } } sb.append("]"); return sb.toString(); } static String toJsonStr(String value); static boolean isValidJsonObject(String json); static boolean isValidJsonObject(String json, boolean allowBlank); static boolean isValidJsonArray(String json); static boolean isValidJsonArray(String json, boolean allowBlank); static String toJson(long[] ids); static String toJson(Jsonable[] values); }### Answer: @Test public void testToJson() { Assert.assertEquals("[1, 2, 3]", JsonUtil.toJson(new long[]{1, 2, 3})); }
### Question: MemCacheTemplate implements CacheAble<T> { @Override public boolean set(String key, T value) { return set(key, value, expireTime); } @Override T get(String key); @Override Map<String, T> getMulti(String[] keys); @Override boolean set(String key, T value); @Override boolean set(String key, T value, Date expdate); @SuppressWarnings("unchecked") @Override CasValue<T> getCas(String key); @Override boolean cas(String key, CasValue<T> casValue); @Override boolean cas(String key, CasValue<T> casValue, Date expdate); @Override boolean delete(String key); void setExpire(long expire); void setExpireL1(long expireL1); Date getExpireTime(); Date getExpireTimeL1(); MemcacheClient getMaster(); List<MemcacheClient> getMasterL1List(); MemcacheClient getSlave(); List<MemcacheClient> getSlaveL1List(); boolean isSetbackMaster(); void setMaster(MemcacheClient master); void setMasterL1List(List<MemcacheClient> masterL1List); void setSlave(MemcacheClient slave); void setSlaveL1List(List<MemcacheClient> slaveL1List); void setSetbackMaster(boolean setbackMaster); boolean isMasterAsOneL1(); void setMasterAsOneL1(boolean masterAsOneL1); String getWirtePolicy(); void setWirtePolicy(String wirtePolicy); }### Answer: @Test public void testSet() { String key = MemCacheUtil.toKey("123", "module.c"); MemCacheTemplate<String> memCacheTemplate = getMemCacheTemplate(); if (memCacheTemplate.set(key, "dsadsadsadsadas")) { String value = memCacheTemplate.get(key); Assert.assertEquals("dsadsadsadsadas", value); memCacheTemplate.delete(key); value = memCacheTemplate.get(key); Assert.assertEquals(null, value); } }
### Question: MD5Util { public static String md5(String src) { return md5(src.getBytes()); } static String md5(String src); static String md5(byte[] bytes); static String encodeHex(byte[] bytes); static String md5(long[] array); static byte[] long2Byte(long[] longArray); static void main(String[] args); }### Answer: @Test public void testMd5() { String strMd5 = MD5Util.md5("123456"); ApiLogger.debug("MD5UtilTest testMd5 strMd5:" + strMd5); Assert.assertEquals("e10adc3949ba59abbe56e057f20f883e", strMd5); }
### Question: Crc32Util { public static long getCrc32(byte[] b) { CRC32 crc = crc32Provider.get(); crc.reset(); crc.update(b); return crc.getValue(); } static long getCrc32(byte[] b); static long getCrc32(String str); static void main(String[] args); }### Answer: @Test public void testCrc32() { long h = Crc32Util.getCrc32(String.valueOf("256")); ApiLogger.debug("Crc32UtilTest testCrc32 h:" + h); }
### Question: ArrayUtil { public static int[] toRawIntArr(String strArr[]) { int[] intArr = new int[strArr.length]; for (int i = 0; i < strArr.length; i++) { intArr[i] = Integer.parseInt(strArr[i]); } return intArr; } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long[] toRawLongArr(String[] strArr); static int[] toRawIntArr(String strArr[]); static long[] toLongArr(Collection<Long> ids); static int[] toIntArr(Collection<Integer> ids); static String[] splitSimpleString(String str); static String toSimpleString(long a[]); static void reverse(long[] b); static void reverse(long[][] b); static long[] reverseCopy(long[] original, int newLength); static long[] reverseCopyRange(long[] original, int from, int to); static long[] removeAll(long[] sourceArray, long[] removeArray); static long[] removeAll(long[] sourceArray, Set<Long> removeSet); static long[] sort(long left[], long right[]); static void sortDesc(long[] a); static long[] intersectionOrder(long[] arr1, long[] arr2); static long[] addTo(long[] left, long[] right); static long[] addTo(long[] arr, long id); static long[] addTo(long[] arr, long id, int limit); static long[] getLimited(long[] arr, int limit); }### Answer: @Test public void testToRawIntArr(){ String[] inputArray1 = { "2", "2", "4", "6", "8", "15" }; int[] result = ArrayUtil.toRawIntArr(inputArray1); Assert.assertArrayEquals(new int[] { 2, 2, 4, 6, 8, 15 }, result); }
### Question: ArrayUtil { public static long[] reverseCopy(long[] original, int newLength) { long[] result = new long[newLength]; int originalLimit = original.length - newLength; for (int i = original.length - 1, resultIdx = 0; i >= originalLimit; i--) { result[resultIdx++] = original[i]; } return result; } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long[] toRawLongArr(String[] strArr); static int[] toRawIntArr(String strArr[]); static long[] toLongArr(Collection<Long> ids); static int[] toIntArr(Collection<Integer> ids); static String[] splitSimpleString(String str); static String toSimpleString(long a[]); static void reverse(long[] b); static void reverse(long[][] b); static long[] reverseCopy(long[] original, int newLength); static long[] reverseCopyRange(long[] original, int from, int to); static long[] removeAll(long[] sourceArray, long[] removeArray); static long[] removeAll(long[] sourceArray, Set<Long> removeSet); static long[] sort(long left[], long right[]); static void sortDesc(long[] a); static long[] intersectionOrder(long[] arr1, long[] arr2); static long[] addTo(long[] left, long[] right); static long[] addTo(long[] arr, long id); static long[] addTo(long[] arr, long id, int limit); static long[] getLimited(long[] arr, int limit); }### Answer: @Test public void testReverseCopy(){ long[] inputArray1 = { 2, 2, 4, 6, 8, 15 }; long[] result = ArrayUtil.reverseCopy(inputArray1, inputArray1.length); Assert.assertArrayEquals(new long[] { 15, 8, 6, 4, 2, 2 }, result); }
### Question: ArrayUtil { public static void sortDesc(long[] a) { Arrays.sort(a); reverse(a); } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long[] toRawLongArr(String[] strArr); static int[] toRawIntArr(String strArr[]); static long[] toLongArr(Collection<Long> ids); static int[] toIntArr(Collection<Integer> ids); static String[] splitSimpleString(String str); static String toSimpleString(long a[]); static void reverse(long[] b); static void reverse(long[][] b); static long[] reverseCopy(long[] original, int newLength); static long[] reverseCopyRange(long[] original, int from, int to); static long[] removeAll(long[] sourceArray, long[] removeArray); static long[] removeAll(long[] sourceArray, Set<Long> removeSet); static long[] sort(long left[], long right[]); static void sortDesc(long[] a); static long[] intersectionOrder(long[] arr1, long[] arr2); static long[] addTo(long[] left, long[] right); static long[] addTo(long[] arr, long id); static long[] addTo(long[] arr, long id, int limit); static long[] getLimited(long[] arr, int limit); }### Answer: @Test public void testSortDesc() { long[] inputArray1 = { 2, 2, 4, 6, 8, 15 }; ArrayUtil.sortDesc(inputArray1); System.out.println(Arrays.toString(inputArray1)); Assert.assertArrayEquals(new long[] { 15, 8, 6, 4, 2, 2 }, inputArray1); }
### Question: MemCacheTemplate implements CacheAble<T> { @Override public boolean delete(String key) { boolean rs = delete(key, master); if (rs == false) { return rs; } if(slave != null){ delete(key, slave); } delete(key, masterL1List); delete(key, slaveL1List); return rs; } @Override T get(String key); @Override Map<String, T> getMulti(String[] keys); @Override boolean set(String key, T value); @Override boolean set(String key, T value, Date expdate); @SuppressWarnings("unchecked") @Override CasValue<T> getCas(String key); @Override boolean cas(String key, CasValue<T> casValue); @Override boolean cas(String key, CasValue<T> casValue, Date expdate); @Override boolean delete(String key); void setExpire(long expire); void setExpireL1(long expireL1); Date getExpireTime(); Date getExpireTimeL1(); MemcacheClient getMaster(); List<MemcacheClient> getMasterL1List(); MemcacheClient getSlave(); List<MemcacheClient> getSlaveL1List(); boolean isSetbackMaster(); void setMaster(MemcacheClient master); void setMasterL1List(List<MemcacheClient> masterL1List); void setSlave(MemcacheClient slave); void setSlaveL1List(List<MemcacheClient> slaveL1List); void setSetbackMaster(boolean setbackMaster); boolean isMasterAsOneL1(); void setMasterAsOneL1(boolean masterAsOneL1); String getWirtePolicy(); void setWirtePolicy(String wirtePolicy); }### Answer: @Test public void testDelete() { String key = MemCacheUtil.toKey("123", "module.c"); MemCacheTemplate<String> memCacheTemplate = getMemCacheTemplate(); if (memCacheTemplate.set(key, "dsadsadsadsadas")) { String value = memCacheTemplate.get(key); Assert.assertEquals("dsadsadsadsadas", value); memCacheTemplate.delete(key); value = memCacheTemplate.get(key); Assert.assertEquals(null, value); } }
### Question: Util { public static int convertInt(Object obj) { return convertInt(obj, 0); } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object obj, int defaultValue); static long convertLong(String src); static long convertLong(String src, long defaultValue); static void trim(StringBuffer sb,char c); static String urlDecoder(String s, String charcoding); static String urlEncoder(String s, String charcoding); static String toEscChar(String s); static String htmlEscapeOnce(String s); static String htmlUnEscapeOnce(String s); static String getPicIdFromUrl(String url); static String getProfileImgUrl(long uid, int size, long iconver, byte gender); static long getVersionFromImgUrl(String imageUrl); static String toEscapeJson(String s); }### Answer: @Test public void testConvertInt() { assertEquals(0, Util.convertInt("")); assertEquals(0, Util.convertInt("-")); assertEquals(12443, Util.convertInt("12443")); assertEquals(-12443, Util.convertInt("-12443")); assertEquals(Integer.MAX_VALUE, Util.convertInt(String.valueOf(Integer.MAX_VALUE))); assertEquals(Integer.MIN_VALUE, Util.convertInt(String.valueOf(Integer.MIN_VALUE))); }
### Question: Util { public static long convertLong(String src) { return convertLong(src, 0); } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object obj, int defaultValue); static long convertLong(String src); static long convertLong(String src, long defaultValue); static void trim(StringBuffer sb,char c); static String urlDecoder(String s, String charcoding); static String urlEncoder(String s, String charcoding); static String toEscChar(String s); static String htmlEscapeOnce(String s); static String htmlUnEscapeOnce(String s); static String getPicIdFromUrl(String url); static String getProfileImgUrl(long uid, int size, long iconver, byte gender); static long getVersionFromImgUrl(String imageUrl); static String toEscapeJson(String s); }### Answer: @Test public void testConvertLong() { assertEquals(0L, Util.convertLong("")); assertEquals(0L, Util.convertLong("-")); assertEquals(12443, Util.convertLong("12443")); assertEquals(-12443, Util.convertLong("-12443")); assertEquals(Long.MAX_VALUE, Util.convertLong(String.valueOf(Long.MAX_VALUE))); assertEquals(Long.MIN_VALUE, Util.convertLong(String.valueOf(Long.MIN_VALUE))); } @Test public void testParseLong() { assertEquals(12443l,Util.convertLong("12443")); }
### Question: Util { public static String urlEncoder(String s, String charcoding) { if (s == null) return null; try { return URLEncoder.encode(s, charcoding); } catch (Exception e) { } return null; } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object obj, int defaultValue); static long convertLong(String src); static long convertLong(String src, long defaultValue); static void trim(StringBuffer sb,char c); static String urlDecoder(String s, String charcoding); static String urlEncoder(String s, String charcoding); static String toEscChar(String s); static String htmlEscapeOnce(String s); static String htmlUnEscapeOnce(String s); static String getPicIdFromUrl(String url); static String getProfileImgUrl(long uid, int size, long iconver, byte gender); static long getVersionFromImgUrl(String imageUrl); static String toEscapeJson(String s); }### Answer: @Test public void testUrlEncoder() { assertEquals("%2C",Util.urlEncoder(",", "UTF-8")); }
### Question: Util { public static String urlDecoder(String s, String charcoding) { if (s == null) return null; try { return URLDecoder.decode(s, charcoding); } catch (Exception e) { } return null; } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object obj, int defaultValue); static long convertLong(String src); static long convertLong(String src, long defaultValue); static void trim(StringBuffer sb,char c); static String urlDecoder(String s, String charcoding); static String urlEncoder(String s, String charcoding); static String toEscChar(String s); static String htmlEscapeOnce(String s); static String htmlUnEscapeOnce(String s); static String getPicIdFromUrl(String url); static String getProfileImgUrl(long uid, int size, long iconver, byte gender); static long getVersionFromImgUrl(String imageUrl); static String toEscapeJson(String s); }### Answer: @Test public void testUrlDecoder() { assertEquals(",",Util.urlDecoder("%2C", "UTF-8")); }
### Question: Util { public static String htmlEscapeOnce(String s) { if (StringUtils.isBlank(s)){ return s; } s = s.replaceAll("&", "&amp;"); s = s.replaceAll("<", "&lt;"); s = s.replaceAll(">", "&gt;"); s = s.replaceAll("\"", "&quot;"); return s; } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object obj, int defaultValue); static long convertLong(String src); static long convertLong(String src, long defaultValue); static void trim(StringBuffer sb,char c); static String urlDecoder(String s, String charcoding); static String urlEncoder(String s, String charcoding); static String toEscChar(String s); static String htmlEscapeOnce(String s); static String htmlUnEscapeOnce(String s); static String getPicIdFromUrl(String url); static String getProfileImgUrl(long uid, int size, long iconver, byte gender); static long getVersionFromImgUrl(String imageUrl); static String toEscapeJson(String s); }### Answer: @Test public void testHtmlEscapeOnce() { String src = "&amp;<span class=\"java\"/>"; String target = Util.htmlEscapeOnce(src); assertEquals("&amp;amp;&lt;span class=&quot;java&quot;/&gt;", target); }
### Question: Util { public static String htmlUnEscapeOnce(String s) { if (StringUtils.isBlank(s)){ return s; } s = s.replaceAll("&amp;", "&"); s = s.replaceAll("&lt;", "<"); s = s.replaceAll("&gt;", ">"); s = s.replaceAll("&quot;", "\""); return s; } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object obj, int defaultValue); static long convertLong(String src); static long convertLong(String src, long defaultValue); static void trim(StringBuffer sb,char c); static String urlDecoder(String s, String charcoding); static String urlEncoder(String s, String charcoding); static String toEscChar(String s); static String htmlEscapeOnce(String s); static String htmlUnEscapeOnce(String s); static String getPicIdFromUrl(String url); static String getProfileImgUrl(long uid, int size, long iconver, byte gender); static long getVersionFromImgUrl(String imageUrl); static String toEscapeJson(String s); }### Answer: @Test public void testHtmlUnEscapeOnce() { String src = "&amp;amp;&lt;span class=&quot;java&quot;/&gt;"; String target = Util.htmlUnEscapeOnce(src); assertEquals("&amp;<span class=\"java\"/>", target); }
### Question: IpUtil { public static boolean isIp(String in){ if(in==null){ return false; } return ipPattern.matcher(in).matches(); } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String addr); static String longToIp(long i); static boolean isIp(String in); static Map<String,String> getLocalIps(); static String getLocalIp(); static String getSingleLocalIp(); static int ramdomAvailablePort(); static boolean availablePort(int port); static void main(String[] args); }### Answer: @Test public void testIsIp(){ org.junit.Assert.assertTrue(IpUtil.isIp("127.0.0.1")); org.junit.Assert.assertTrue(IpUtil.isIp("10.75.0.60")); org.junit.Assert.assertTrue(IpUtil.isIp("192.168.1.1")); org.junit.Assert.assertTrue(IpUtil.isIp("175.41.9.194")); } @Test public void testIsIpFalse(){ org.junit.Assert.assertFalse(IpUtil.isIp("aaa")); org.junit.Assert.assertFalse(IpUtil.isIp("1000.75.0.60")); org.junit.Assert.assertFalse(IpUtil.isIp("192.168.1")); org.junit.Assert.assertFalse(IpUtil.isIp("175.41.9.a")); }
### Question: IpUtil { public static int ipToInt(final String addr) { final String[] addressBytes = addr.split("\\."); int ip = 0; for (int i = 0; i < 4; i++) { ip <<= 8; ip |= Integer.parseInt(addressBytes[i]); } return ip; } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String addr); static String longToIp(long i); static boolean isIp(String in); static Map<String,String> getLocalIps(); static String getLocalIp(); static String getSingleLocalIp(); static int ramdomAvailablePort(); static boolean availablePort(int port); static void main(String[] args); }### Answer: @Test public void testIPToInt(){ org.junit.Assert.assertEquals(2130706433,IpUtil.ipToInt("127.0.0.1")); org.junit.Assert.assertEquals(172687420,IpUtil.ipToInt("10.75.0.60")); org.junit.Assert.assertEquals(-1062731519,IpUtil.ipToInt("192.168.1.1")); org.junit.Assert.assertEquals(-1356265022,IpUtil.ipToInt("175.41.9.194")); }
### Question: IpUtil { public static String getLocalIp() { Map<String,String> ips = getLocalIps(); List<String> faceNames = new ArrayList<String>(ips.keySet()); Collections.sort(faceNames); for(String name:faceNames){ if("lo".equals(name)){ continue; } String ip = ips.get(name); if(!StringUtils.isBlank(ip)){ return ip; } } return "127.0.0.1"; } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String addr); static String longToIp(long i); static boolean isIp(String in); static Map<String,String> getLocalIps(); static String getLocalIp(); static String getSingleLocalIp(); static int ramdomAvailablePort(); static boolean availablePort(int port); static void main(String[] args); }### Answer: @Test public void testGetLocalIp(){ String localIp = IpUtil.getLocalIp(); System.out.println(localIp); org.junit.Assert.assertNotNull(localIp); }
### Question: IpUtil { public static int ramdomAvailablePort(){ int port = 0; do{ port = (int) ((MAX_USER_PORT_NUMBER-MIN_USER_PORT_NUMBER) * Math.random())+MIN_USER_PORT_NUMBER; }while(!availablePort(port)); return port; } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String addr); static String longToIp(long i); static boolean isIp(String in); static Map<String,String> getLocalIps(); static String getLocalIp(); static String getSingleLocalIp(); static int ramdomAvailablePort(); static boolean availablePort(int port); static void main(String[] args); }### Answer: @Test public void testGetRandomPort(){ int port = IpUtil.ramdomAvailablePort(); System.out.println(port); org.junit.Assert.assertTrue(port > 0 && port <65535); }
### Question: HashUtil { public static int getHash(long id, int splitCount, String hashAlg) { return getHash(id, splitCount, hashAlg, NoneHash.NEW); } static int getHash(long id, int splitCount, String hashAlg); static int getHash(long id, int splitCount, String hashAlg, String noneHash); }### Answer: @Test public void testGetHashCrc32() { int hash = HashUtil.getHash(1821155363, 32, HashAlg.CRC32); Assert.assertEquals(12, hash); hash = HashUtil.getHash(1821155363, 128, HashAlg.CRC32); Assert.assertEquals(51, hash); } @Test public void testGetHashNone() { int hash = HashUtil.getHash(1821155363, 32, HashAlg.NONE); Assert.assertEquals(1, hash); hash = HashUtil.getHash(1821155363, 128, HashAlg.NONE); Assert.assertEquals(64, hash); }
### Question: DateUtil { public static Date parseDateTime(String timeStr, Date defaultValue){ if(timeStr == null){ return defaultValue; } try { return dateTimeSdf.get().parse(timeStr); } catch (ParseException e) { return defaultValue; } } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(String timeStr, Date defaultValue); static final int getCurrentHour(); static final int getLastHour(); static final int getNextHour(); static Date getFirstDayOfCurMonth(); static Date getFirstDayInMonth(Date date); static Date getFirstDayInMonth(int month); static boolean isCurrentMonth(Date date); }### Answer: @Test public void testParseDateTime() { System.out.println(new Date(515483463000L)); System.out.println(new Date(1356969600000L)); assertEquals(new Date(1325390268000L), DateUtil.parseDateTime("2012-01-01 11:57:48", null)); }
### Question: DateUtil { public static String getYearMonth(Date date){ return yearMonthSdf.get().format(date); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(String timeStr, Date defaultValue); static final int getCurrentHour(); static final int getLastHour(); static final int getNextHour(); static Date getFirstDayOfCurMonth(); static Date getFirstDayInMonth(Date date); static Date getFirstDayInMonth(int month); static boolean isCurrentMonth(Date date); }### Answer: @Test public void testGetYearMonth() { Date date = DateUtil.parseDateTime("2012-01-01 11:57:48", null); assertEquals("12_01", DateUtil.getYearMonth(date)); date = DateUtil.parseDateTime("2012-12-01 00:00:00", null); ApiLogger.debug(date + ", " + date.getTime()); } @Test public void testGetYearMonthDay() { assertEquals("11_11", DateUtil.getYearMonth(new Date(1322197921282L))); }
### Question: DateUtil { public static String formateYearMonthDay(Date date){ return yearMonthDaySdf.get().format(date); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(String timeStr, Date defaultValue); static final int getCurrentHour(); static final int getLastHour(); static final int getNextHour(); static Date getFirstDayOfCurMonth(); static Date getFirstDayInMonth(Date date); static Date getFirstDayInMonth(int month); static boolean isCurrentMonth(Date date); }### Answer: @Test public void testFormateYearMonthDay() { assertEquals("2011-11-25", DateUtil.formateYearMonthDay(new Date(1322197921282L))); }
### Question: DateUtil { public static Date parseYearMonthDay(String timeStr, Date defaultValue){ if(timeStr == null){ return defaultValue; } try { return yearMonthDaySdf.get().parse(timeStr); } catch (ParseException e) { return defaultValue; } } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(String timeStr, Date defaultValue); static final int getCurrentHour(); static final int getLastHour(); static final int getNextHour(); static Date getFirstDayOfCurMonth(); static Date getFirstDayInMonth(Date date); static Date getFirstDayInMonth(int month); static boolean isCurrentMonth(Date date); }### Answer: @Test public void testParseYearMonthDay() { assertEquals(new Date(1325347200000L), DateUtil.parseYearMonthDay("2012-01-01", null)); Date date = DateUtil.parseYearMonthDay("2012-12-01", null); ApiLogger.debug(date + ", " + date.getTime()); ApiLogger.debug(new Date(1000000000000L) + ", " + new Date(1000000000000L).getTime()); ApiLogger.debug(new Date(1000L * 60 * 43200) + ", " + new Date(1000L * 60 * 43200).getTime() + ", " + (1000L * 60 * 43200)); }
### Question: DateUtil { public static Date getFirstDayInMonth(Date date){ Calendar calendar = Calendar.getInstance(); if(date != null){ calendar.setTime(date); } calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); return calendar.getTime(); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(String timeStr, Date defaultValue); static final int getCurrentHour(); static final int getLastHour(); static final int getNextHour(); static Date getFirstDayOfCurMonth(); static Date getFirstDayInMonth(Date date); static Date getFirstDayInMonth(int month); static boolean isCurrentMonth(Date date); }### Answer: @Test public void testGetFirstDayInMonth() { assertEquals(new Date(1320076800282L), DateUtil.getFirstDayInMonth(new Date(1322197921282L))); }
### Question: DateUtil { public static boolean isCurrentMonth(Date date){ if(date != null){ Calendar dest = Calendar.getInstance(); dest.setTime(date); Calendar now = Calendar.getInstance(); return now.get(Calendar.YEAR) == dest.get(Calendar.YEAR) && now.get(Calendar.MONTH) == dest.get(Calendar.MONTH); } return false; } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(String timeStr, Date defaultValue); static final int getCurrentHour(); static final int getLastHour(); static final int getNextHour(); static Date getFirstDayOfCurMonth(); static Date getFirstDayInMonth(Date date); static Date getFirstDayInMonth(int month); static boolean isCurrentMonth(Date date); }### Answer: @Test public void testGsCurrentMonth(){ assertEquals(true, DateUtil.isCurrentMonth(new Date())); assertEquals(false, DateUtil.isCurrentMonth(new Date(1322197921282L))); }
### Question: LoginViewModel extends BaseViewModel { public void login() { if (InputHelper.isEmpty(userName) || InputHelper.isEmpty(password)) { AlertUtils.showToastShortMessage(App.getInstance(), "Please input username and password!"); return; } String auth = StringUtils.getBasicAuth(userName, password); execute(true, RestHelper.createRemoteSourceMapper(githubService.login(auth), null), user -> { userManager.startUserSession(user, auth); navigatorHelper.navigateMainActivity(true); }); } @Inject LoginViewModel(GithubService githubService, UserManager userManager); void login(); public String userName; public String password; }### Answer: @Test public void loginSuccess() throws Exception { String pass = "abc"; User user = sampleUser(1L); String token = StringUtils.getBasicAuth(user.getLogin(), pass); when(githubService.login(any())).thenReturn(successResponse(user)); when(userManager.startUserSession(any(), any())).thenReturn(null); viewModel.setUserName(user.login); viewModel.setPassword(pass); viewModel.login(); verify(stateLiveData, times(1)).setValue(State.loading(null)); verify(stateLiveData, times(1)).setValue(State.success(null)); verify(userManager).startUserSession(user, token); verify(mNavigatorHelper).navigateMainActivity(true); } @Test public void loginError() throws Exception { when(githubService.login(any())).thenReturn(errorResponse(401, "blah blah")); viewModel.login(); verify(stateLiveData, times(1)).setValue(State.loading(null)); verify(stateLiveData, times(1)).setValue(State.error("blah blah")); verifyZeroInteractions(userManager); }
### Question: GirlService { public Girl findOne(Integer id) { return girlRepository.findOne(id); } @Transactional void insertTwo(); void getAge(Integer id); Girl findOne(Integer id); }### Answer: @Test public void findOne() throws Exception { Girl girl = girlService.findOne(19); Assert.assertEquals(new Integer(14), girl.getAge()); } @Test public void findOne() throws Exception { }
### Question: GirlController { @GetMapping(value = "/girls") public List<Girl> girlList() { logger.info("girlList"); return girlRepository.findAll(); } @GetMapping(value = "/girls") List<Girl> girlList(); @PostMapping(value = "/girls") Object girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping(value = "/girl/{id}") Girl girlFindOne(@PathVariable("id") Integer id); @PutMapping(value = "/girls/{id}") Girl girlUpdate(@PathVariable("id") Integer id, @RequestParam("name") String name, @RequestParam("age") Integer age); @DeleteMapping(value = "/girls/{id}") void girlDelete(@PathVariable("id") Integer id); @GetMapping(value = "/girls/age/{age}") List<Girl> girlListByAge(@PathVariable("age") Integer age); @PostMapping(value = "/girls/two") void girlTwo(); @GetMapping(value = "/girls/getAge/{id}") void getAge(@PathVariable("id") Integer id); }### Answer: @Test public void girlList() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/girls")) .andExpect(MockMvcResultMatchers.status().isOk()); }
### Question: RedisLockUtil { public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) { String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME_UNIT, expireTime); return LOCK_SUCCESS.equals(result); } static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime); static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId); }### Answer: @Test public void tryGetDistributedLockTest() throws Exception { String key = "testDistributedLockKey"; String requestId = UUID.randomUUID().toString(); boolean getDistributedLockResult = RedisLockUtil.tryGetDistributedLock(JEDIS, key, requestId, 60 * 1000 * 60); System.out.println("getDistributedLockResult=" + getDistributedLockResult); Assert.assertTrue(getDistributedLockResult); }
### Question: RedisLockUtil { public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) { String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId)); return RELEASE_SUCCESS.equals(result); } static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime); static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId); }### Answer: @Test public void releaseDistributedLockTest() throws Exception { String key = "testDistributedLockKey"; String requestId = UUID.randomUUID().toString(); boolean releaseDistributedLockResult = RedisLockUtil.releaseDistributedLock(JEDIS, key, requestId); System.out.println("releaseDistributedLockResult=" + releaseDistributedLockResult); Assert.assertTrue(releaseDistributedLockResult); }
### Question: HttpUtil { public static String get(String requestUrl) { HttpGet get = new HttpGet(requestUrl); return executeRequest(get, Charset.forName(DEFAULT_ENCODING)); } static String get(String requestUrl); static String post(String requestUrl, Object data, ContentType contentType); static String uploadFile(String requestUrl, Object data); }### Answer: @Test public void get() throws UnsupportedEncodingException { GetUserRequest request = new GetUserRequest("/user/getUserList"); request.setUserId(1L); request.setUsername("李白"); String result = HttpUtil.get(request.composeUrl(baseUrl, request.getQueryParameters())); AbstractResponse response = JacksonUtil.readValue(result, request.getResponseClass()); log.info(response.toString()); }
### Question: HttpUtil { public static String post(String requestUrl, Object data, ContentType contentType) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } if (contentType == null) { throw new RuntimeException("contentType cann't be null"); } HttpPost post = new HttpPost(requestUrl); if (data != null) { StringEntity entity = new StringEntity(data.toString(), contentType); post.setEntity(entity); } logger.info("HttpClient request uri -> " + requestUrl); logger.info("HttpClient request body -> " + data); return executeRequest(post, contentType.getCharset()); } static String get(String requestUrl); static String post(String requestUrl, Object data, ContentType contentType); static String uploadFile(String requestUrl, Object data); }### Answer: @Test public void postFormData() throws UnsupportedEncodingException { UpdateUserRequest request = new UpdateUserRequest("/user/updateUser"); request.setMethod(MethodTypeEnum.POST); request.setHttpContentType(ContentType.APPLICATION_FORM_URLENCODED); request.setUserId(1L); request.setUsername("李太白"); String result = HttpUtil.post(request.composeUrl(baseUrl, request.getQueryParameters()), null, request.getHttpContentType()); AbstractResponse response = JacksonUtil.readValue(result, request.getResponseClass()); log.info(response.toString()); } @Test public void postJsonObject() throws UnsupportedEncodingException { CreateUserRequest request = new CreateUserRequest("/user/createUser"); request.setMethod(MethodTypeEnum.POST); request.setHttpContentType(ContentType.APPLICATION_JSON); CreateUserRequest.CreateUserBody body = new CreateUserRequest.CreateUserBody(); body.setUsername("白居易"); request.setBody(body); String result = HttpUtil.post(request.composeUrl(baseUrl, request.getQueryParameters()), JacksonUtil.toJson(request.getBody()), request.getHttpContentType()); AbstractResponse response = JacksonUtil.readValue(result, request.getResponseClass()); log.info(response.toString()); }
### Question: ImageUtil { public static List<String> generateThumbnail2Directory(String path, String... files) throws IOException { return generateThumbnail2Directory(DEFAULT_SCALE, path, files); } static List<String> generateThumbnail2Directory(String path, String... files); static List<String> generateThumbnail2Directory(double scale, String pathname, String... files); static void generateDirectoryThumbnail(String pathname); static void generateDirectoryThumbnail(String pathname, double scale); static String appendSuffix(String fileName, String suffix); static boolean isImage(String extension); static String getFileExtention(String fileName); }### Answer: @Test public void testGenerateThumbnail2Directory() throws IOException { String path = "D:\\workspace\\idea\\individual\\springboot-learn\\springboot-thumbnail\\image"; String[] files = new String[]{ "image/1.jpg", "image/2.jpg" }; List<String> list = ImageUtil.generateThumbnail2Directory(path, files); System.out.println(list); }
### Question: ImageUtil { public static void generateDirectoryThumbnail(String pathname) throws IOException { generateDirectoryThumbnail(pathname, DEFAULT_SCALE); } static List<String> generateThumbnail2Directory(String path, String... files); static List<String> generateThumbnail2Directory(double scale, String pathname, String... files); static void generateDirectoryThumbnail(String pathname); static void generateDirectoryThumbnail(String pathname, double scale); static String appendSuffix(String fileName, String suffix); static boolean isImage(String extension); static String getFileExtention(String fileName); }### Answer: @Test public void testGenerateDirectoryThumbnail() throws IOException { String path = "D:\\workspace\\idea\\individual\\springboot-learn\\springboot-thumbnail\\image"; ImageUtil.generateDirectoryThumbnail(path); }
### Question: ReflectionUtil { public static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method) { if (args.size() == 0 && method.getParameterCount() == 0) { return Collections.emptyList(); } List<String> argsOut = new ArrayList<>(); if (args.size() < method.getParameterCount()) { argsOut.addAll(args); } else { for (int i = 0; i < method.getParameterCount(); i++) { argsOut.add(args.get(i)); } } return argsOut; } static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method); static @NotNull String getFormattedMethodSignature(Method method); static @NotNull String getMethodId(Method method); static @NotNull String getArgMismatchString(Method method); }### Answer: @Test public void ensureArgsForMethodAccurate() throws NoSuchMethodException { List<String> inputStr = Arrays.asList("1", "nextMethod", "param", "param2"); Method testClass1234 = ReflTestClass.ReflSubClass.class.getMethod("get1234", int.class); List<String> out = ReflectionUtil.getArgsForMethod(inputStr, testClass1234); assertEquals(1, out.size()); assertEquals("1", out.get(0)); inputStr = Arrays.asList("1", "2", "3"); Method lotsOfParams = ReflTestClass.class.getMethod("methodWithLotsOfParams", int.class, int.class, int.class, int.class, int.class, int.class, int.class); out = ReflectionUtil.getArgsForMethod(inputStr, lotsOfParams); assertEquals(inputStr.size(), out.size()); for (int i = 0; i < inputStr.size(); i++) { assertEquals(inputStr.get(i), out.get(i)); } inputStr = new ArrayList<>(); Method noParams = ReflTestClass.class.getMethod("getSomeNumbers"); out = ReflectionUtil.getArgsForMethod(inputStr, noParams); assertEquals(0, out.size()); }
### Question: TypeHandler { public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } TypeHandler(Logger logger); @Nullable String getOutputFor(@Nullable Object object); @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input); @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input, @Nullable PlatformSender<?> sender); boolean registerHandler(Handler handler); @Nullable IHandler getIHandlerForClass(Class<?> clazz); @NotNull Collection<IHandler> getAllInputHandlers(); @NotNull Collection<OHandler> getAllOutputHandlers(); }### Answer: @Test public void ensurePolymorphicInput() throws InputException { Class[] requestedTypes = {AnEnum.class, AnEnum.class}; String[] inputArgs = {"VAL_1", "VAL_5"}; Object[] output = typeHandler.instantiateTypes(requestedTypes, Arrays.asList(inputArgs)); assertTrue(output[0] instanceof AnEnum); assertTrue(output[1] instanceof AnEnum); Assertions.assertEquals(AnEnum.VAL_1, output[0]); Assertions.assertEquals(AnEnum.VAL_5, output[1]); } @Test public void ensureThrowsOnNoSuchIHandler() { Assertions.assertThrows(InputException.class, () -> { Class[] requestedType = {CASE_NEVER_WILL_BE_REGISTERED}; typeHandler.instantiateTypes(requestedType, Collections.singletonList("blah")); }); } @Test public void ensureNullAlwaysAvailable() throws InputException { Object[] array = typeHandler.instantiateTypes(new Class[]{Object.class}, Collections.singletonList(TypeHandler.NULL_INSTANCE_KEYWORD)); Object instance = array[0]; assertNull(instance); }
### Question: TypeHandler { public @Nullable String getOutputFor(@Nullable Object object) { if (object == null) { return null; } OHandler handler = getOHandlerForClass(object.getClass()); if (handler != null) { return handler.getFormattedOutput(object); } else { return String.valueOf(object); } } TypeHandler(Logger logger); @Nullable String getOutputFor(@Nullable Object object); @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input); @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input, @Nullable PlatformSender<?> sender); boolean registerHandler(Handler handler); @Nullable IHandler getIHandlerForClass(Class<?> clazz); @NotNull Collection<IHandler> getAllInputHandlers(); @NotNull Collection<OHandler> getAllOutputHandlers(); }### Answer: @Test public void ensureNullInputGivesNullOutput() { String output = typeHandler.getOutputFor(null); assertNull(output); }
### Question: ReflectionUtil { public static @NotNull String getMethodId(Method method) { return getFormattedMethodSignature(method).replaceAll(" ", ""); } static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method); static @NotNull String getFormattedMethodSignature(Method method); static @NotNull String getMethodId(Method method); static @NotNull String getArgMismatchString(Method method); }### Answer: @Test public void ensureNoWhitespaceInMethodIds() throws NoSuchMethodException { Method method = ReflTestClass.class.getMethod("getSomeNumbers"); String id = ReflectionUtil.getMethodId(method); long whitespaceCount = id.chars() .filter(Character::isWhitespace) .count(); if (whitespaceCount != 0) { System.out.println("Illegal whitespace chars found in id: " + id); } assertEquals(0, whitespaceCount); }
### Question: MethodMap { public @NotNull Set<Method> getAllMethods() { return new HashSet<>(backingMap.values()); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); @Nullable Method getById(String identifier); boolean containsId(String identifier); @NotNull Set<Method> getAllMethods(); @NotNull Set<String> getAllIds(); @NotNull Class<?> getMappedClass(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static final MethodMap EMPTY; }### Answer: @Test public void testContainsMethods() { MethodMap methodmap = new MethodMap(TESTER); Set<Method> mappedMethods = methodmap.getAllMethods(); long missing = Arrays.stream(TESTER.getMethods()) .filter(m -> Modifier.isPublic(m.getModifiers())) .filter(m -> !mappedMethods.contains(m)) .peek(m -> System.out.println(m.getName() + " MISSING!")) .count(); assertEquals(0, missing); }
### Question: MethodMap { public @NotNull Set<String> getAllIds() { return new HashSet<>(backingMap.keySet()); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); @Nullable Method getById(String identifier); boolean containsId(String identifier); @NotNull Set<Method> getAllMethods(); @NotNull Set<String> getAllIds(); @NotNull Class<?> getMappedClass(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static final MethodMap EMPTY; }### Answer: @Test public void testContainsIds() { MethodMap methodMap = new MethodMap(TESTER); Set<String> identifiers = methodMap.getAllIds(); long missing = Arrays.stream(TESTER.getMethods()) .filter(m -> Modifier.isPublic(m.getModifiers())) .map(ReflectionUtil::getMethodId) .filter(s -> !identifiers.contains(s)) .peek(s -> System.out.println("Method map does not contain expected: " + s)) .count(); assertEquals(0, missing); }
### Question: MethodMap { @Override public int hashCode() { return 67 * backingMap.hashCode(); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); @Nullable Method getById(String identifier); boolean containsId(String identifier); @NotNull Set<Method> getAllMethods(); @NotNull Set<String> getAllIds(); @NotNull Class<?> getMappedClass(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static final MethodMap EMPTY; }### Answer: @Test public void ensureHashcodes() { MethodMap map1 = new MethodMap(TESTER); MethodMap map2 = new MethodMap(TESTER); assertEquals(map1.hashCode(), map2.hashCode()); }
### Question: ErrorParser { @NonNull static StripeError parseError(String rawError) { StripeError stripeError = new StripeError(); try { JSONObject jsonError = new JSONObject(rawError); JSONObject errorObject = jsonError.getJSONObject(FIELD_ERROR); stripeError.charge = errorObject.optString(FIELD_CHARGE); stripeError.code = errorObject.optString(FIELD_CODE); stripeError.decline_code = errorObject.optString(FIELD_DECLINE_CODE); stripeError.message = errorObject.optString(FIELD_MESSAGE); stripeError.param = errorObject.optString(FIELD_PARAM); stripeError.type = errorObject.optString(FIELD_TYPE); } catch (JSONException jsonException) { stripeError.message = MALFORMED_RESPONSE_MESSAGE; } return stripeError; } }### Answer: @Test public void parseError_withInvalidRequestError_createsCorrectObject() { ErrorParser.StripeError parsedStripeError = ErrorParser.parseError(RAW_INVALID_REQUEST_ERROR); String errorMessage = "The Stripe API is only accessible over HTTPS. " + "Please see <https: assertEquals(errorMessage, parsedStripeError.message); assertEquals("invalid_request_error", parsedStripeError.type); assertEquals("", parsedStripeError.param); } @Test public void parseError_withNoErrorMessage_addsInvalidResponseMessage() { ErrorParser.StripeError badStripeError = ErrorParser.parseError(RAW_INCORRECT_FORMAT_ERROR); assertEquals(ErrorParser.MALFORMED_RESPONSE_MESSAGE, badStripeError.message); assertNull(badStripeError.type); }
### Question: ModelUtils { static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } }### Answer: @Test public void wholePositiveNumberShouldPassWithLeadingZero() { assertTrue(ModelUtils.isWholePositiveNumber("000")); } @Test public void wholePositiveNumberShouldFailIfNegative() { assertFalse(ModelUtils.isWholePositiveNumber("-1")); } @Test public void wholePositiveNumberShouldFailIfLetters() { assertFalse(ModelUtils.isWholePositiveNumber("1a")); } @Test public void wholePositiveNumberShouldFailNull() { assertFalse(ModelUtils.isWholePositiveNumber(null)); } @Test public void wholePositiveNumberShouldPassIfEmpty() { assertTrue(ModelUtils.isWholePositiveNumber("")); } @Test public void wholePositiveNumberShouldPass() { assertTrue(ModelUtils.isWholePositiveNumber("123")); }
### Question: ModelUtils { static int normalizeYear(int year, Calendar now) { if (year < 100 && year >= 0) { String currentYear = String.valueOf(now.get(Calendar.YEAR)); String prefix = currentYear.substring(0, currentYear.length() - 2); year = Integer.parseInt(String.format(Locale.US, "%s%02d", prefix, year)); } return year; } }### Answer: @Test public void normalizeSameCenturyShouldPass() { Calendar now = Calendar.getInstance(); int year = 1997; now.set(Calendar.YEAR, year); assertEquals(ModelUtils.normalizeYear(97, now), year); } @Test public void normalizeDifferentCenturyShouldFail() { Calendar now = Calendar.getInstance(); int year = 1997; now.set(Calendar.YEAR, year); assertNotEquals(ModelUtils.normalizeYear(97, now), 2097); }
### Question: SourceCodeVerification extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); try{ jsonObject.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_STATUS, mStatus); } catch (JSONException ignored) { } return jsonObject; } SourceCodeVerification(int attemptsRemaining, @Status String status); int getAttemptsRemaining(); @Status String getStatus(); @NonNull @Override Map<String, Object> toMap(); @NonNull @Override JSONObject toJson(); @Nullable static SourceCodeVerification fromString(@Nullable String jsonString); @Nullable static SourceCodeVerification fromJson(@Nullable JSONObject jsonObject); }### Answer: @Test public void fromJsonString_backToJson_createsIdenticalElement() { try { JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_CODE_VERIFICATION); assertJsonEquals(rawConversion, mCodeVerification.toJson()); } catch (JSONException jsonException) { fail("Test Data failure: " + jsonException.getLocalizedMessage()); } }