method2testcases
stringlengths
118
6.63k
### Question: BookResource { @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) public Response findById(@PathParam("id") final Long id) { log.info("Getting the book " + id); return ofNullable(bookRepository.findById(id)) .map(Response::ok) .orElse(status(NOT_FOUND)) .build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // tag::adocSnippet[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); @GET @Path("number") @ApiOperation(value = "Wraps the Number API to retrive a Book Number", response = String.class) Response number(); }### Answer: @Test @InSequence(1) public void findById() throws Exception { final Response response = webTarget.path("{id}").resolveTemplate("id", 0).request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
### Question: BookResource { @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) public Response findAll() { log.info("Getting all the books"); return ok(bookRepository.findAll()).build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // tag::adocSnippet[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); @GET @Path("number") @ApiOperation(value = "Wraps the Number API to retrive a Book Number", response = String.class) Response number(); }### Answer: @Test @InSequence(2) public void findAll() throws Exception { final Response response = webTarget.request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
### Question: BookResource { @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) public Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo) { log.info("Creating the book " + book); log.info("Invoking the number-api"); String isbn = numbersApi.generateBookNumber(); book.setIsbn(isbn); log.info("Creating the book with ISBN " + book); final Book created = bookRepository.create(book); URI createdURI = uriInfo.getBaseUriBuilder().path(String.valueOf(created.getId())).build(); return Response.created(createdURI).build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // tag::adocSnippet[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); @GET @Path("number") @ApiOperation(value = "Wraps the Number API to retrive a Book Number", response = String.class) Response number(); }### Answer: @Test @InSequence(3) public void create() throws Exception { final Book book = new Book("Joshua Bloch", "Effective Java (2nd Edition)", 2001, "Tech", " 978-0-3213-5668-0"); final Response response = webTarget.request().post(entity(book, APPLICATION_JSON_TYPE)); assertEquals(CREATED.getStatusCode(), response.getStatus()); }
### Question: BookResource { @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) public Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book) { log.info("Updating the book " + book); return ok(bookRepository.update(book)).build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // tag::adocSnippet[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); @GET @Path("number") @ApiOperation(value = "Wraps the Number API to retrive a Book Number", response = String.class) Response number(); }### Answer: @Test @InSequence(4) public void update() throws Exception { final Book book = new Book("Joshua Bloch", "Effective Java (3rd Edition)", 2018, "Tech", " 978-0-1346-8599-1"); final Response response = webTarget.path("{id}") .resolveTemplate("id", 1) .request() .put(entity(book, APPLICATION_JSON_TYPE)); assertEquals(OK.getStatusCode(), response.getStatus()); }
### Question: AlbumService implements PaginatedService { public ResourceDto<AlbumDto> getAlbumsPage() { return getAlbumsPage(FIRST_PAGE_NUM); } @Inject AlbumService(@Named("albumDao") AlbumDao albumDao, @Named("artistDao") MaprDbDao<Artist> artistDao, LanguageDao languageDao, SlugService slugService, StatisticService statisticService, AlbumRateDao albumRateDao); @Override long getTotalNum(); ResourceDto<AlbumDto> getAlbumsPage(); ResourceDto<AlbumDto> getAlbumsPage(String order, List<String> orderFields); ResourceDto<AlbumDto> getAlbumsPage(Long page); ResourceDto<AlbumDto> getAlbumsPage(Long perPage, Long page, String order, List<String> orderFields); ResourceDto<AlbumDto> getAlbumsPage(Long perPage, Long page, List<SortOption> sortOptions); ResourceDto<AlbumDto> getAlbumsPageByLanguage(Long perPage, Long page, List<SortOption> sortOptions, String lang); AlbumDto getAlbumById(String id); AlbumDto getAlbumBySlugName(String slugName); void deleteAlbumById(String id); AlbumDto createAlbum(AlbumDto albumDto); AlbumDto updateAlbum(AlbumDto albumDto); @SuppressWarnings("unchecked") AlbumDto updateAlbum(String id, AlbumDto albumDto); TrackDto getTrackById(String id, String trackId); List<TrackDto> getAlbumTracksList(String id); TrackDto addTrackToAlbumTrackList(String id, TrackDto track); List<TrackDto> addTracksToAlbumTrackList(String id, List<TrackDto> tracks); TrackDto updateAlbumTrack(String id, String trackId, TrackDto track); List<TrackDto> setAlbumTrackList(String id, List<TrackDto> trackList); void deleteAlbumTrack(String id, String trackId); List<Language> getSupportedAlbumsLanguages(); List<AlbumDto> searchAlbums(String nameEntry, Long limit); }### Answer: @Test public void getNegativePageTest() { thrown.expect(IllegalArgumentException.class); AlbumDao albumDao = mock(AlbumDao.class); LanguageDao languageDao = mock(LanguageDao.class); SlugService slugService = mock(SlugService.class); StatisticService statisticService = mock(StatisticService.class); MaprDbDao<Artist> artistDao = mock(MaprDbDao.class); AlbumRateDao albumRateDao = mock(AlbumRateDao.class); AlbumService albumService = new AlbumService(albumDao, artistDao, languageDao, slugService, statisticService, albumRateDao); albumService.getAlbumsPage(-1L); }
### Question: AlbumService implements PaginatedService { public AlbumDto getAlbumById(String id) { if (id == null || id.isEmpty()) { throw new IllegalArgumentException("Album's identifier can not be empty"); } Album album = albumDao.getById(id); if (album == null) { throw new ResourceNotFoundException("Album with id '" + id + "' not found"); } return albumToDto(album); } @Inject AlbumService(@Named("albumDao") AlbumDao albumDao, @Named("artistDao") MaprDbDao<Artist> artistDao, LanguageDao languageDao, SlugService slugService, StatisticService statisticService, AlbumRateDao albumRateDao); @Override long getTotalNum(); ResourceDto<AlbumDto> getAlbumsPage(); ResourceDto<AlbumDto> getAlbumsPage(String order, List<String> orderFields); ResourceDto<AlbumDto> getAlbumsPage(Long page); ResourceDto<AlbumDto> getAlbumsPage(Long perPage, Long page, String order, List<String> orderFields); ResourceDto<AlbumDto> getAlbumsPage(Long perPage, Long page, List<SortOption> sortOptions); ResourceDto<AlbumDto> getAlbumsPageByLanguage(Long perPage, Long page, List<SortOption> sortOptions, String lang); AlbumDto getAlbumById(String id); AlbumDto getAlbumBySlugName(String slugName); void deleteAlbumById(String id); AlbumDto createAlbum(AlbumDto albumDto); AlbumDto updateAlbum(AlbumDto albumDto); @SuppressWarnings("unchecked") AlbumDto updateAlbum(String id, AlbumDto albumDto); TrackDto getTrackById(String id, String trackId); List<TrackDto> getAlbumTracksList(String id); TrackDto addTrackToAlbumTrackList(String id, TrackDto track); List<TrackDto> addTracksToAlbumTrackList(String id, List<TrackDto> tracks); TrackDto updateAlbumTrack(String id, String trackId, TrackDto track); List<TrackDto> setAlbumTrackList(String id, List<TrackDto> trackList); void deleteAlbumTrack(String id, String trackId); List<Language> getSupportedAlbumsLanguages(); List<AlbumDto> searchAlbums(String nameEntry, Long limit); }### Answer: @Test public void getByNullId() { thrown.expect(IllegalArgumentException.class); AlbumDao albumDao = mock(AlbumDao.class); LanguageDao languageDao = mock(LanguageDao.class); SlugService slugService = mock(SlugService.class); StatisticService statisticService = mock(StatisticService.class); MaprDbDao<Artist> artistDao = mock(MaprDbDao.class); AlbumRateDao albumRateDao = mock(AlbumRateDao.class); AlbumService albumService = new AlbumService(albumDao, artistDao, languageDao, slugService, statisticService, albumRateDao); albumService.getAlbumById(""); }
### Question: SecKillCommandService { public SecKillGrabResult addCouponTo(T customerId) { if (recoveryInfo.getClaimedCustomers().add(customerId)) { if (claimedCoupons.getAndIncrement() < recoveryInfo.remainingCoupons()) { return couponQueue.offer(customerId) ? SecKillGrabResult.Success : SecKillGrabResult.Failed; } return SecKillGrabResult.Failed; } return SecKillGrabResult.Duplicate; } SecKillCommandService(Queue<T> couponQueue, AtomicInteger claimedCoupons, SecKillRecoveryCheckResult<T> recoveryInfo); SecKillGrabResult addCouponTo(T customerId); }### Answer: @Test public void putsAllCustomersInQueue() { for (int i = 0; i < 5; i++) { SecKillGrabResult success = commandService.addCouponTo(i); assertThat(success, is(SecKillGrabResult.Success)); } assertThat(coupons, contains(0, 1, 2, 3, 4)); } @Test public void noMoreItemAddedToQueueOnceFull() { keepConsumingCoupons(); int threads = 200; CyclicBarrier barrier = new CyclicBarrier(threads); addCouponsAsync(threads , () -> { try { barrier.await(); return commandService.addCouponTo(customerIdGenerator.incrementAndGet()) == SecKillGrabResult.Success; } catch (InterruptedException | BrokenBarrierException e) { throw new RuntimeException(e); } }, success -> { if (success) { numberOfSuccess.incrementAndGet(); } }); assertThat(numberOfSuccess.get(), is(10)); } @Test public void failsToAddCustomerIfQueueIsFull() { for (int i = 0; i < numberOfCoupons; i++) { SecKillGrabResult success = commandService.addCouponTo(i); assertThat(success, is(SecKillGrabResult.Success)); } assertThat(coupons.size(), is(numberOfCoupons)); SecKillGrabResult success = commandService.addCouponTo(100); assertThat(success, is(SecKillGrabResult.Failed)); assertThat(coupons, contains(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); } @Test public void failsDuplicateAddCustomer() { SecKillGrabResult success = commandService.addCouponTo(1); assertThat(success, is(SecKillGrabResult.Success)); success = commandService.addCouponTo(1); assertThat(success, is(SecKillGrabResult.Duplicate)); }
### Question: SecKillRecoveryService { public SecKillRecoveryCheckResult<T> check(PromotionEntity promotion) { List<EventEntity> entities = this.repository.findByPromotionId(promotion.getPromotionId()); if (!entities.isEmpty()) { long count = entities.stream() .filter(event -> SecKillEventType.CouponGrabbedEvent.equals(event.getType())) .count(); Set<T> claimedCustomers = ConcurrentHashMap.newKeySet(); claimedCustomers.addAll(entities.stream() .filter(entity -> SecKillEventType.CouponGrabbedEvent.equals(entity.getType())) .map(entity -> ((CouponGrabbedEvent<T>) eventFormat.fromEntity(entity)).getCoupon().getCustomerId()) .collect(Collectors.toSet())); boolean isFinished = entities.stream() .anyMatch(event -> SecKillEventType.PromotionFinishEvent.equals(event.getType())); return new SecKillRecoveryCheckResult<>(true, isFinished, promotion.getNumberOfCoupons() - (int) count, claimedCustomers); } return new SecKillRecoveryCheckResult<>(promotion.getNumberOfCoupons()); } SecKillRecoveryService(SpringSecKillEventRepository repository, SecKillEventFormat eventFormat); SecKillRecoveryCheckResult<T> check(PromotionEntity promotion); }### Answer: @Test public void unstartPromotionCheck() { SecKillRecoveryCheckResult<String> result = recoveryService.check(unpublishedPromotion); assertThat(result.isStarted(), is(false)); assertThat(result.isFinished(), is(false)); assertThat(result.remainingCoupons(), is(unpublishedPromotion.getNumberOfCoupons())); assertThat(result.getClaimedCustomers().isEmpty(), is(true)); } @Test public void recoverPromotionCheck() { SecKillRecoveryCheckResult<String> result = recoveryService.check(runningPromotion); assertThat(result.isStarted(), is(true)); assertThat(result.isFinished(), is(false)); assertThat(result.remainingCoupons(), is(runningPromotion.getNumberOfCoupons() - 1)); assertThat(result.getClaimedCustomers(), contains("zyy")); } @Test public void finishPromotionCheck() { SecKillRecoveryCheckResult<String> result = recoveryService.check(endedPromotion); assertThat(result.isStarted(), is(true)); assertThat(result.isFinished(), is(true)); assertThat(result.remainingCoupons(), is(0)); assertThat(result.getClaimedCustomers(), contains("0", "1", "2", "3", "4")); }
### Question: SpanTemplate implements SpanOperations { @Override public ActiveSpan startActive(String name) { return tracer.buildSpan(name) .startActive(); } SpanTemplate(Tracer tracer); @Override void doInTracer(SpanCallback callback); @Override Span start(String name); @Override ActiveSpan startActive(String name); @Override ActiveSpan startActive(String name, ActiveSpan parent); @Override ActiveSpan startActive(String name, SpanContext parent); @Override void inject(SpanContext ctx, HttpHeaders headers); @Override SpanContext extract(Map<String, Object> map); }### Answer: @Test public void testStartActive() throws InterruptedException { try (ActiveSpan span = spanOps.startActive("hello sematextains")) { span.setTag("app", "console"); } Thread.sleep(2000); } @Test public void testStartActiveWithParent() throws InterruptedException { try (ActiveSpan parent = spanOps.startActive("parent")) { parent.setTag("app", "console"); Thread.sleep(500); try (ActiveSpan child = spanOps.startActive("child", parent)) { child.setTag("encoding", "utf-8"); } } Thread.sleep(2000); }
### Question: SpanTemplate implements SpanOperations { @Override public void inject(SpanContext ctx, HttpHeaders headers) { HttpHeadersInjectAdapter injectAdapter = new HttpHeadersInjectAdapter(headers); tracer.inject(ctx, Format.Builtin.HTTP_HEADERS, injectAdapter); } SpanTemplate(Tracer tracer); @Override void doInTracer(SpanCallback callback); @Override Span start(String name); @Override ActiveSpan startActive(String name); @Override ActiveSpan startActive(String name, ActiveSpan parent); @Override ActiveSpan startActive(String name, SpanContext parent); @Override void inject(SpanContext ctx, HttpHeaders headers); @Override SpanContext extract(Map<String, Object> map); }### Answer: @Test public void testInject() { try (ActiveSpan span = spanOps.startActive("parent")) { Map<String, Object> map = new HashMap<>(); map.put("app", "console"); HttpHeaders headers = new HttpHeaders(); spanOps.inject(span.context(), headers); } }
### Question: StateCapture { public static Executor capturingDecorator(final Executor executor) { if (stateCaptors.isEmpty() || executor instanceof CapturingExecutor) { return executor; } else { return new CapturingExecutor(executor); } } private StateCapture(); static Executor capturingDecorator(final Executor executor); static ExecutorService capturingDecorator(final ExecutorService executorService); static ScheduledExecutorService capturingDecorator(final ScheduledExecutorService executorService); static CompletionService<T> capturingDecorator(final CompletionService<T> completionService); static Runnable capturingDecorator(Runnable delegate); static Callable<V> capturingDecorator(Callable<V> delegate); }### Answer: @Test public void testExecutorCaptures() throws InterruptedException { ExecutorService e = Executors.newCachedThreadPool(); Executor f = StateCapture.capturingDecorator(e); CapturedState mockCapturedState = mock(CapturedState.class); Runnable mockRunnable = mock(Runnable.class); ThreadLocalStateCaptor.THREAD_LOCAL.set(mockCapturedState); f.execute(mockRunnable); e.shutdown(); e.awaitTermination(10, TimeUnit.HOURS); verifyStandardCaptures(mockCapturedState, mockRunnable); } @Test public void testScheduledExecutorServiceCaptures() throws InterruptedException { ScheduledExecutorService e = Executors.newScheduledThreadPool(10); ScheduledExecutorService f = StateCapture.capturingDecorator(e); CapturedState mockCapturedState = mock(CapturedState.class); Runnable mockRunnable = mock(Runnable.class); ThreadLocalStateCaptor.THREAD_LOCAL.set(mockCapturedState); f.execute(mockRunnable); e.shutdown(); e.awaitTermination(10, TimeUnit.HOURS); verifyStandardCaptures(mockCapturedState, mockRunnable); } @Test public void testCompletionServiceRunnableCaptures() throws InterruptedException, Exception { ExecutorService executor = Executors.newCachedThreadPool(); CompletionService<Object> delegate = new ExecutorCompletionService<>(executor); CompletionService<Object> cs = StateCapture.capturingDecorator(delegate); CapturedState mockCapturedState = mock(CapturedState.class); Runnable mockRunnable = mock(Runnable.class); ThreadLocalStateCaptor.THREAD_LOCAL.set(mockCapturedState); Object result = new Object(); Future<Object> futureResult = cs.submit(mockRunnable, result); assertThat("Expected the delegate response to return", result, sameInstance(futureResult.get())); executor.shutdown(); verifyStandardCaptures(mockCapturedState, mockRunnable); } @Test public void testCompletionServiceCallableCaptures() throws InterruptedException, Exception { ExecutorService executor = Executors.newCachedThreadPool(); CompletionService<Object> delegate = new ExecutorCompletionService<>(executor); CompletionService<Object> cs = StateCapture.capturingDecorator(delegate); CapturedState mockCapturedState = mock(CapturedState.class); Object expectedResult = new Object(); @SuppressWarnings("unchecked") Callable<Object> mockCallable = mock(Callable.class); when(mockCallable.call()).thenReturn(expectedResult); ThreadLocalStateCaptor.THREAD_LOCAL.set(mockCapturedState); Future<Object> futureResult = cs.submit(mockCallable); executor.shutdown(); verifyStandardCaptures(mockCapturedState, mockCallable, expectedResult, futureResult.get()); }
### Question: MXBeanPoller { public void shutdown() { running.set(false); executor.shutdown(); try { executor.awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.SECONDS); } catch (InterruptedException e) { executor.shutdownNow(); Thread.currentThread().interrupt(); } } MXBeanPoller(final MetricRecorder metricRecorder, final int pollingIntervalSeconds, final List<Sensor> sensors); MXBeanPoller(final ScheduledExecutorService executor, final MetricRecorder metricRecorder, final int pollingIntervalSeconds, final List<Sensor> sensors); static final MXBeanPoller withAutoShutdown( final MetricRecorder metricRecorder, int pollingIntervalSeconds, List<Sensor> sensors); void shutdown(); }### Answer: @Test public void shutdown() throws Exception { final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); MXBeanPoller poller = new MXBeanPoller(executor, new NullRecorder(), 5, Collections.emptyList()); poller.shutdown(); assertTrue("Executor not shutdown on poller shutdown", executor.isShutdown()); } @Test public void senses() throws Exception { final MetricRecorder recorder = new NullRecorder(); final Sensor sensor1 = mock(Sensor.class); final Sensor sensor2 = mock(Sensor.class); when(sensor1.addContext(any(TypedMap.class))).then(invocation -> invocation.getArgument(0)); when(sensor2.addContext(any(TypedMap.class))).then(invocation -> invocation.getArgument(0)); List<Sensor> sensors = new ArrayList<>(); sensors.add(sensor1); sensors.add(sensor2); MXBeanPoller poller = new MXBeanPoller(recorder, 1, sensors); Thread.sleep(1500); poller.shutdown(); final ArgumentMatcher<TypedMap> dataMatch = new DataMatcher(); verify(sensor1).addContext(argThat(dataMatch)); verify(sensor2).addContext(argThat(dataMatch)); verify(sensor1, atLeastOnce()).sense(any(MetricContext.class)); verify(sensor2, atLeastOnce()).sense(any(MetricContext.class)); }
### Question: FileRecorder extends MetricRecorder<MetricRecorder.RecorderContext> { static boolean isValid(final Metric label) { final String str = label.toString(); return !(str.contains("\n") || str.contains(",") || str.contains(":") || str.contains("=")); } FileRecorder(final String filename); static final FileRecorder withAutoShutdown( final String filename); void shutdown(); }### Answer: @Test public void validation() { final String[] good = { "snake_case_metric", "camelCaseMetric", "hyphenated-metric", "spaced out metric", "digits 0123456789", "G\u00FCnther", "\t!\"#$%&'()*+./;<>?@[\\]^`{|}~" }; for (final String s : good) { assertTrue("valid name [" + s + "]", FileRecorder.isValid(Metric.define(s))); } final String[] bad = { "metric_name, dimension=value", "metric_name:100ms:", "metric_name\nmetric", "metric=metric_name" }; for (final String s : bad) { assertFalse("invalid name [" + s + "]", FileRecorder.isValid(Metric.define(s))); } }
### Question: DoubleFormat { public static void format(Appendable sb, double value) { try { format_exception(sb, value); } catch (IOException e) { throw new IllegalStateException("Appendable must not throw IOException", e); } } private DoubleFormat(); static void format(Appendable sb, double value); }### Answer: @Test public void benchmark() throws Exception { final long iterations = 1000000; long duration_StringFormat = run_benchmark(iterations, (a) -> String.format("%.6f", a)); NumberFormat javaFormatter = NumberFormat.getInstance(); javaFormatter.setMinimumFractionDigits(0); javaFormatter.setMaximumFractionDigits(6); javaFormatter.setGroupingUsed(false); long duration_JavaFormat = run_benchmark(iterations, (a) -> javaFormatter.format(a)); long duration_JavaStringBuilder = run_benchmark(iterations, (a) -> (new StringBuilder()).append(a)); long duration_DoubleFormat = run_benchmark(iterations, (a) -> DoubleFormat.format(new StringBuilder(), a)); System.out.println("DoubleFormat Performance comparison: " + iterations +" iterations"); System.out.println("\tJava String.format: " + duration_StringFormat + " ms"); System.out.println("\tJava NumberFormat: " + duration_JavaFormat + " ms"); System.out.println("\tJava StringBuilder: " + duration_JavaStringBuilder + " ms"); System.out.println("\tDoubleFormat: " + duration_DoubleFormat + " ms"); assertTrue(duration_DoubleFormat < duration_StringFormat); assertTrue(duration_DoubleFormat < duration_JavaFormat); assertTrue(duration_DoubleFormat < duration_JavaStringBuilder); }
### Question: ContextAwareExecutor implements Executor { @Override public void execute(Runnable command) { executor.execute(ThreadContext.current().wrap(command)); } ContextAwareExecutor(Executor executor); @Override void execute(Runnable command); }### Answer: @Test public void currentContextIsPropagatedToTask() throws Exception { ThreadContext context = ThreadContext.emptyContext().with(KEY, "value"); try (ThreadContext.CloseableContext ignored = context.open()) { executor.execute(captureTask); } latch.await(); assertSame(context, contextCapture.get()); } @Test public void withNoContextDefaultIsUsed() throws Exception { executor.execute(captureTask); latch.await(); assertSame(ThreadContext.emptyContext(), contextCapture.get()); }
### Question: ImmutableTypedMap implements TypedMap { @Override public Set<Key> keySet() { return this.dataMap.keySet(); } private ImmutableTypedMap(Map<Key<?>, Entry<?>> dataMap); @Override final T get(Key<T> key); @Override int size(); @Override boolean isEmpty(); @Override Iterator<Entry> iterator(); @Override Iterator<Entry<T>> typedIterator(Class<T> clazz); @Override Set<Key> keySet(); @Override Set<Key<T>> typedKeySet(final Class<T> clazz); @Override boolean containsKey(final Key<?> key); @Override boolean containsValue(final Object value); }### Answer: @Test public void keyset() throws Exception { final TypedMap.Key<Double> ka = TypedMap.key("Alpha", Double.class); final TypedMap.Key<String> kb = TypedMap.key("Beta", String.class); final TypedMap.Key<UUID> kc = TypedMap.key("Gamma", UUID.class); final TypedMap.Key<Object> kd = TypedMap.key("Delta", Object.class); final Double va = Double.valueOf(867.5309); final String vb = "Here is a string, with...\nmultiple lines and stuff."; final UUID vc = UUID.randomUUID(); final Object vd = new Object(); TypedMap data = ImmutableTypedMap.Builder .with(kc, vc) .add(ka, va) .add(kb, vb) .add(kd, vd) .build(); Set<TypedMap.Key> s = data.keySet(); assertEquals("Set of keys has wrong size", 4, s.size()); assertTrue("Set of keys is missing a key", s.contains(ka)); assertTrue("Set of keys is missing a key", s.contains(kb)); assertTrue("Set of keys is missing a key", s.contains(kc)); assertTrue("Set of keys is missing a key", s.contains(kd)); }
### Question: ImmutableTypedMap implements TypedMap { @Override public <T> Set<Key<T>> typedKeySet(final Class<T> clazz) { Set<Key<T>> keys = new HashSet<>(); for (Key k : this.keySet()) { if (k.valueType.equals(clazz)) { keys.add(k); } } return Collections.unmodifiableSet(keys); } private ImmutableTypedMap(Map<Key<?>, Entry<?>> dataMap); @Override final T get(Key<T> key); @Override int size(); @Override boolean isEmpty(); @Override Iterator<Entry> iterator(); @Override Iterator<Entry<T>> typedIterator(Class<T> clazz); @Override Set<Key> keySet(); @Override Set<Key<T>> typedKeySet(final Class<T> clazz); @Override boolean containsKey(final Key<?> key); @Override boolean containsValue(final Object value); }### Answer: @Test public void typedKeyset() throws Exception { final TypedMap.Key<Double> ka = TypedMap.key("A", Double.class); final TypedMap.Key<String> kb = TypedMap.key("B", String.class); final TypedMap.Key<String> kc = TypedMap.key("C", String.class); final TypedMap.Key<Object> kd = TypedMap.key("D", Object.class); final Double va = Double.valueOf(3.14159); final String vb = "Mmm tasty pi"; final String vc = "but no love for tau"; final Object vd = "or a type safe string"; TypedMap data = ImmutableTypedMap.Builder .with(kc, vc) .add(ka, va) .add(kb, vb) .add(kd, vd) .build(); Set<TypedMap.Key<String>> s = data.typedKeySet(String.class); assertEquals("Typed set of keys has wrong size", 2, s.size()); assertFalse("Typed set of keys has unexpected member", s.contains(ka)); assertTrue("Typed set of keys is missing a key", s.contains(kb)); assertTrue("Typed set of keys is missing a key", s.contains(kc)); assertFalse("Typed set of keys has unexpected member", s.contains(kd)); }
### Question: ImmutableTypedMap implements TypedMap { @Override public Iterator<Entry> iterator() { return this.dataMap.values().iterator(); } private ImmutableTypedMap(Map<Key<?>, Entry<?>> dataMap); @Override final T get(Key<T> key); @Override int size(); @Override boolean isEmpty(); @Override Iterator<Entry> iterator(); @Override Iterator<Entry<T>> typedIterator(Class<T> clazz); @Override Set<Key> keySet(); @Override Set<Key<T>> typedKeySet(final Class<T> clazz); @Override boolean containsKey(final Key<?> key); @Override boolean containsValue(final Object value); }### Answer: @Test public void iterator() throws Exception { final TypedMap.Key<Long> ka = TypedMap.key("1", Long.class); final TypedMap.Key<Short> kb = TypedMap.key("2", Short.class); final TypedMap.Key<BigInteger> kc = TypedMap.key("5", BigInteger.class); final Long va = Long.valueOf(999999999); final Short vb = Short.valueOf((short)1); final BigInteger vc = BigInteger.valueOf(Long.MAX_VALUE+Short.MAX_VALUE); TypedMap data = ImmutableTypedMap.Builder .with(ka, va) .add(kb, vb) .add(kc, vc) .build(); assertEquals(3, data.size()); int i = 0; boolean seen_a = false; boolean seen_b = false; boolean seen_c = false; for (TypedMap.Entry e : data) { i++; if (e.getKey().equals(ka) && e.getValue().equals(va)) { seen_a = true; } if (e.getKey().equals(kb) && e.getValue().equals(vb)) { seen_b = true; } if (e.getKey().equals(kc) && e.getValue().equals(vc)) { seen_c = true; } } assertEquals("Iterator iterated incorrect increments", 3, i); assertTrue("Iterator missed an entry", seen_a); assertTrue("Iterator missed an entry", seen_b); assertTrue("Iterator missed an entry", seen_c); } @Test(expected=UnsupportedOperationException.class) public void iterator_remove() throws Exception { final TypedMap.Key<Long> ka = TypedMap.key("1", Long.class); final Long va = Long.valueOf(999999999); TypedMap data = ImmutableTypedMap.Builder.with(ka, va).build(); Iterator<TypedMap.Entry> it = data.iterator(); it.remove(); }
### Question: ImmutableTypedMap implements TypedMap { @Override public int size() { return this.dataMap.size(); } private ImmutableTypedMap(Map<Key<?>, Entry<?>> dataMap); @Override final T get(Key<T> key); @Override int size(); @Override boolean isEmpty(); @Override Iterator<Entry> iterator(); @Override Iterator<Entry<T>> typedIterator(Class<T> clazz); @Override Set<Key> keySet(); @Override Set<Key<T>> typedKeySet(final Class<T> clazz); @Override boolean containsKey(final Key<?> key); @Override boolean containsValue(final Object value); }### Answer: @Test public void forEach() throws Exception { final TypedMap.Key<Long> ka = TypedMap.key("1", Long.class); final TypedMap.Key<Short> kb = TypedMap.key("2", Short.class); final TypedMap.Key<BigInteger> kc = TypedMap.key("5", BigInteger.class); final Long va = Long.valueOf(999999999); final Short vb = Short.valueOf((short)1); final BigInteger vc = BigInteger.valueOf(Long.MAX_VALUE+Short.MAX_VALUE); TypedMap data = ImmutableTypedMap.Builder .with(ka, va) .add(kb, vb) .add(kc, vc) .build(); assertEquals(3, data.size()); final boolean[] seen = {false,false,false,false}; data.forEach((e) -> { if (e.getKey().equals(ka) && e.getValue().equals(va)) { seen[0] = true; } else if (e.getKey().equals(kb) && e.getValue().equals(vb)) { seen[1] = true; } else if (e.getKey().equals(kc) && e.getValue().equals(vc)) { seen[2] = true; } else { seen[3] = true; } }); assertTrue("forEach missed an entry", seen[0]); assertTrue("forEach missed an entry", seen[1]); assertTrue("forEach missed an entry", seen[2]); assertFalse("forEach hit an unexpected entry", seen[3]); } @Test public void forEachTyped() throws Exception { final TypedMap.Key<String> ka = TypedMap.key("y", String.class); final TypedMap.Key<Object> kb = TypedMap.key("n", Object.class); final TypedMap.Key<String> kc = TypedMap.key("m", String.class); final TypedMap.Key<Integer> kd = TypedMap.key("s", Integer.class); final String va = "yes"; final String vb = "no"; final String vc = "maybe"; final Integer vd = 50; TypedMap data = ImmutableTypedMap.Builder .with(ka, va) .add(kb, vb) .add(kc, vc) .add(kd, vd) .build(); assertEquals(4, data.size()); final boolean[] seen = {false,false,false,false,false}; data.forEachTyped(String.class, (e) -> { TypedMap.Key<String> k = e.getKey(); String v = e.getValue(); if (k.equals(ka) && v.equals(va)) { seen[0] = true; } else if (k.equals(kb) && v.equals(vb)) { seen[1] = true; } else if (k.equals(kc) && v.equals(vc)) { seen[2] = true; } else if (k.equals(kd) && v.equals(vd)) { seen[3] = true; } else { seen[4] = true; } }); assertTrue("forEachTyped missed an entry", seen[0]); assertFalse("forEachTyped hit an unexpected entry", seen[1]); assertTrue("forEachTyped missed an entry", seen[2]); assertFalse("forEachTyped hit an unexpected entry", seen[3]); assertFalse("forEachTyped hit an unexpected entry", seen[4]); }
### Question: ImmutableTypedMap implements TypedMap { @Override public <T> Iterator<Entry<T>> typedIterator(Class<T> clazz) { List<Entry<T>> entries = new ArrayList(); for (Iterator<Entry> it = this.iterator(); it.hasNext(); ) { final Entry e = it.next(); if (e.getKey().valueType.equals(clazz)) { entries.add(e); } } return Collections.unmodifiableCollection(entries).iterator(); } private ImmutableTypedMap(Map<Key<?>, Entry<?>> dataMap); @Override final T get(Key<T> key); @Override int size(); @Override boolean isEmpty(); @Override Iterator<Entry> iterator(); @Override Iterator<Entry<T>> typedIterator(Class<T> clazz); @Override Set<Key> keySet(); @Override Set<Key<T>> typedKeySet(final Class<T> clazz); @Override boolean containsKey(final Key<?> key); @Override boolean containsValue(final Object value); }### Answer: @Test public void typedIterator() throws Exception { final TypedMap.Key<String> ka = TypedMap.key("y", String.class); final TypedMap.Key<Object> kb = TypedMap.key("n", Object.class); final TypedMap.Key<String> kc = TypedMap.key("m", String.class); final String va = "yes"; final String vb = "no"; final String vc = "maybe"; TypedMap data = ImmutableTypedMap.Builder .with(ka, va) .add(kb, vb) .add(kc, vc) .build(); assertEquals(3, data.size()); int i = 0; boolean seen_a = false; boolean seen_b = false; boolean seen_c = false; Iterator<TypedMap.Entry<String>> it = data.typedIterator(String.class); while (it.hasNext()) { i++; final TypedMap.Entry<String> e = it.next(); TypedMap.Key<String> k = e.getKey(); String v = e.getValue(); if (k.equals(ka) && v.equals(va)) { seen_a = true; } if (k.equals(kb) && v.equals(vb)) { seen_b = true; } if (k.equals(kc) && v.equals(vc)) { seen_c = true; } } assertEquals("Iterator iterated incorrect increments", 2, i); assertTrue("Typed iterator missed an entry", seen_a); assertFalse("Typed iterator returned an entry of wrong type", seen_b); assertTrue("Typed iterator missed an entry", seen_c); } @Test(expected=UnsupportedOperationException.class) public void typedIterator_remove() throws Exception { final TypedMap.Key<String> ka = TypedMap.key("y", String.class); final String va = "yes"; TypedMap data = ImmutableTypedMap.Builder.with(ka, va).build(); Iterator<TypedMap.Entry<String>> it = data.typedIterator(String.class); it.remove(); }
### Question: NullContext implements MetricContext { @Override public TypedMap attributes() { return attributes; } NullContext(TypedMap attributes); NullContext(TypedMap attributes, MetricContext parent); static NullContext empty(); @Override TypedMap attributes(); @Override void record(Metric label, Number value, Unit unit, Instant time); @Override void count(Metric label, long delta); @Override void close(); @Override MetricContext newChild(TypedMap attributes); @Override MetricContext parent(); }### Answer: @Test public void nullContextCanHaveAttributes() { TypedMap.Key<String> ID = TypedMap.key("ID", String.class); TypedMap attributes = ImmutableTypedMap.Builder.with(ID, "id").build(); NullContext context = new NullContext(attributes); assertSame(attributes, context.attributes()); }
### Question: Metric { public static Metric define(final String name) { return new Metric(name); } private Metric(final String name); static Metric define(final String name); @Override final String toString(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test public void validation() throws Exception { final String[] goods = { "snake_case_metric", "camelCaseMetric", "hyphenated-metric", "spaced out metric", "digits 0123456789", "G\u00FCnther", "\t\n!\"#$%&'()*+,./:;<=>?@[\\]^`{|}~", " " }; for (String s : goods) { Metric.define(s); } final String[] bads = { null, "" }; for (String s : bads) { try { Metric.define(""); } catch (IllegalArgumentException expected) { continue; } fail("Expected exception not thrown for bad name '"+s+"'"); } }
### Question: MultiRecorder extends MetricRecorder<MultiRecorder.MultiRecorderContext> { @Override protected void record(Metric label, Number value, Unit unit, Instant time, MultiRecorderContext context) { context.contexts.parallelStream().forEach(t -> t.record(label, value, unit, time)); } MultiRecorder(List<MetricRecorder<?>> recorders); }### Answer: @Test public void recordIsSentToAllDelegates() { MetricContext context = recorder.context(attributes); context.record(METRIC, 42L, Unit.NONE, timestamp); verify(delegate1).record(eq(METRIC), eq(42L), eq(Unit.NONE), eq(timestamp), argThat(t -> attributes == t.attributes())); verify(delegate2).record(eq(METRIC), eq(42L), eq(Unit.NONE), eq(timestamp), argThat(t -> attributes == t.attributes())); }
### Question: MultiRecorder extends MetricRecorder<MultiRecorder.MultiRecorderContext> { @Override protected void count(Metric label, long delta, MultiRecorderContext context) { context.contexts.parallelStream().forEach(t -> t.count(label, delta)); } MultiRecorder(List<MetricRecorder<?>> recorders); }### Answer: @Test public void countIsSentToAllDelegates() { MetricContext context = recorder.context(attributes); context.count(METRIC, 42L); verify(delegate1).count(eq(METRIC), eq(42L), argThat(t -> attributes == t.attributes())); verify(delegate2).count(eq(METRIC), eq(42L), argThat(t -> attributes == t.attributes())); }
### Question: MultiRecorder extends MetricRecorder<MultiRecorder.MultiRecorderContext> { @Override protected void close(MultiRecorderContext context) { context.contexts.parallelStream().forEach(MetricContext::close); } MultiRecorder(List<MetricRecorder<?>> recorders); }### Answer: @Test public void closeIsSentToAllDelegates() { MetricContext context = recorder.context(attributes); context.close(); verify(delegate1).close(argThat(t -> attributes == t.attributes())); verify(delegate2).close(argThat(t -> attributes == t.attributes())); }