src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ClassStringBinding extends AbstractStringBinding<Class> implements Binding<Class, String> { @Override public String marshal(Class clazz) { return ClassUtils.determineReadableClassName(clazz.getName()); } @Override Class unmarshal(String object); @Override String marshal(Class clazz); Class<Class> getBoundClass(); }
@Test public void testMarshal() { assertEquals("org.jadira.bindings.core.jdk.ClassStringBindingTest", BINDING.marshal(ClassStringBindingTest.class)); assertEquals("org.jadira.bindings.core.jdk.ClassStringBindingTest[]", BINDING.marshal(new ClassStringBindingTest[]{}.getClass())); assertEquals("org.jadira.bindings.core....
ShortStringBinding extends AbstractStringBinding<Short> implements Binding<Short, String> { @Override public Short unmarshal(String object) { return Short.valueOf(Short.parseShort(object)); } @Override Short unmarshal(String object); Class<Short> getBoundClass(); }
@Test public void testUnmarshal() { assertEquals(new Short((short)0).toString(), BINDING.unmarshal("0").toString()); assertEquals(new Short((short)1).toString(), BINDING.unmarshal("1").toString()); assertEquals(new Short((short)32767).toString(), BINDING.unmarshal("" + Short.MAX_VALUE).toString()); assertEquals(new Sho...
AtomicIntegerStringBinding extends AbstractStringBinding<AtomicInteger> implements Binding<AtomicInteger, String> { @Override public AtomicInteger unmarshal(String object) { return new AtomicInteger(Integer.parseInt(object)); } @Override AtomicInteger unmarshal(String object); Class<AtomicInteger> getBoundClass(); }
@Test public void testUnmarshal() { assertEquals(new AtomicInteger(0).toString(), BINDING.unmarshal("0").toString()); assertEquals(new AtomicInteger(1).toString(), BINDING.unmarshal("1").toString()); assertEquals(new AtomicInteger(2147483647).toString(), BINDING.unmarshal("" + Integer.MAX_VALUE).toString()); assertEqua...
CalendarStringBinding extends AbstractStringBinding<Calendar> implements Binding<Calendar, String> { @Override public Calendar unmarshal(String object) { if (object.length() < 31 || object.charAt(26) != ':' || object.charAt(29) != '[' || object.charAt(object.length() - 1) != ']') { throw new IllegalArgumentException("U...
@Test public void testUnmarshal() { Calendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("Europe/London")); cal.setTimeInMillis(0); cal.set(2000, 10, 1, 23, 45); assertEquals(cal, BINDING.unmarshal("2000-11-01T23:45:00.000+00:00[Europe/London]")); }
CalendarStringBinding extends AbstractStringBinding<Calendar> implements Binding<Calendar, String> { @Override public String marshal(Calendar object) { if (object instanceof GregorianCalendar) { GregorianCalendar cal = (GregorianCalendar) object; DATE_FORMAT.get().setCalendar(cal); String str = DATE_FORMAT.get().format...
@Test public void testMarshal() { Calendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("Europe/London")); cal.setTimeInMillis(0); cal.set(2000, 10, 1, 23, 45); assertEquals("2000-11-01T23:45:00.000+00:00[Europe/London]", BINDING.marshal(cal)); }
PahoAsyncMqttClientService extends AbstractMqttClientService implements MqttClientService, MqttCallbackExtended, IMqttActionListener { @Override public String getClientId() { return mqttClient.getClientId(); } PahoAsyncMqttClientService(final String serverUri, final String clientId, final MqttClientConnectionTy...
@Test public void testConstructionBlankServerUri() throws MqttException { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_SERVER_URI); new PahoAsyncMqttClientService(VALUE_BLANK, BrokerHelper.getClientId(), MqttClientConnectionType.PUBSUB, null); } @Test public void testConstructio...
TopicSubscriptionHelper { public static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions) { List<String> records = new ArrayList<String>(); if (!CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.isSubscribed...
@Test public void testGetSubscribedTopicSubscriptions() { Assert.assertArrayEquals(new String[0], TopicSubscriptionHelper.getSubscribedTopicFilters(topicSubscriptions)); topicSubscriptions.get(0).setSubscribed(true); Assert.assertArrayEquals(new String[]{ TOPIC_FILTER_1}, TopicSubscriptionHelper.getSubscribedTopicFilte...
TopicSubscriptionHelper { public static void markUnsubscribed(List<TopicSubscription> topicSubscriptions) { if (!CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { topicSubscription.setSubscribed(false); } } } static TopicSubscription findByTopicFilter(final...
@Test public void testMarkUnsubscribedEmptyTopicSubscriptions() { TopicSubscriptionHelper.markUnsubscribed(new ArrayList<TopicSubscription>()); } @Test public void testMarkUnsubscribed() { Assert.assertArrayEquals(new String[0], TopicSubscriptionHelper.getSubscribedTopicFilters(topicSubscriptions)); topicSubscriptions....
MqttHeaderHelper { public static String getTopicHeaderValue(Message<?> message) { String value = null; if (message != null && message.getHeaders().containsKey(TOPIC)) { value = message.getHeaders().get(TOPIC, String.class); } return value; } static String getTopicHeaderValue(Message<?> message); static MqttQualityOfSe...
@Test public void testTopicHeader() { Assert.assertNull(MqttHeaderHelper.getTopicHeaderValue(null)); MessageBuilder<String> builder = MessageBuilder.withPayload("See topic header"); Assert.assertNull(MqttHeaderHelper.getTopicHeaderValue(builder.build())); builder.setHeader(MqttHeaderHelper.TOPIC, TOPIC); Assert.assertE...
MqttHeaderHelper { public static MqttQualityOfService getMqttQualityOfServiceHeaderValue(Message<?> message, int defaultLevelIdentifier) { Integer levelIdentifier = defaultLevelIdentifier; try { if (message != null && message.getHeaders().containsKey(QOS)) { levelIdentifier = message.getHeaders().get(QOS, Integer.class...
@Test public void testMqttQualityOfServiceHeader() { Assert.assertEquals(MqttQualityOfService.QOS_2, MqttHeaderHelper.getMqttQualityOfServiceHeaderValue(null, MqttQualityOfService.QOS_2.getLevelIdentifier())); MessageBuilder<String> builder = MessageBuilder.withPayload("See QoS header"); Assert.assertEquals(MqttQuality...
MqttHeaderHelper { public static boolean getRetainedHeaderValue(Message<?> message) { boolean retained = false; try { if (message != null && message.getHeaders().containsKey(RETAINED)) { retained = message.getHeaders().get(RETAINED, Boolean.class); } } catch (IllegalArgumentException ex) { LOG.debug("Could not convert ...
@Test public void testRetainedHeader() { Assert.assertFalse(MqttHeaderHelper.getRetainedHeaderValue(null)); MessageBuilder<String> builder = MessageBuilder.withPayload("See retained header"); Assert.assertFalse(MqttHeaderHelper.getRetainedHeaderValue(builder.build())); builder.setHeader(MqttHeaderHelper.RETAINED, "foo"...
MqttHeaderHelper { public static String getCorrelationIdHeaderValue(Message<?> message) { String correlationId = null; if (message != null && message.getHeaders().containsKey(CORRELATION_ID)) { correlationId = message.getHeaders().get(CORRELATION_ID, String.class); } return correlationId; } static String getTopicHeade...
@Test public void testCorrelationIdHeader() { Assert.assertNull(MqttHeaderHelper.getCorrelationIdHeaderValue(null)); MessageBuilder<String> builder = MessageBuilder.withPayload("See Correlation ID header"); Assert.assertNull(MqttHeaderHelper.getCorrelationIdHeaderValue(builder.build())); builder.setHeader(MqttHeaderHel...
MqttClientEventPublisher { public void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectedEvent(clientId, serverU...
@Test public void testPublishConnectedEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishConnectedEvent(CLIENT_ID, SERVER_URI, SUBSCRIBED_TOPICS_EMPTY, null, this); } @Test public void testPublishConnectedEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEP...
MqttClientEventPublisher { public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(cl...
@Test public void testPublishConnectionFailureEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishConnectionFailureEvent(CLIENT_ID, true, new Exception(), null, this); } @Test public void testPublishConnectionFailureEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMes...
MqttClientEventPublisher { public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, sour...
@Test public void testPublishConnectionLostEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishConnectionLostEvent(CLIENT_ID, true, null, this); } @Test public void testPublishConnectionLostEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_CLI...
MqttClientEventPublisher { public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } void publishConnectedEvent(Stri...
@Test public void testPublishDisconnectedEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishDisconnectedEvent(CLIENT_ID, null, this); } @Test public void testPublishDisconnectedEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_CLIENT_ID); App...
MqttClientEventPublisher { public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, so...
@Test public void testPublishMessageDeliveredEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishMessageDeliveredEvent(CLIENT_ID, MESSAGE_ID, null, this); } @Test public void testPublishMessageDeliveredEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION...
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId,...
@Test public void testPublishMessagePublishedEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishMessagePublishedEvent(CLIENT_ID, MESSAGE_ID, CORRELATION_ID, null, this); } @Test public void testPublishMessagePublishedEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectM...
AbstractMqttClientService implements MqttClientService { public void setInboundMessageChannel(MessageChannel inboundMessageChannel) { if (MqttClientConnectionType.PUBLISHER == connectionType) { throw new IllegalStateException(String.format( "Client ID %s is setup as a PUBLISHER and cannot receive messages from the Brok...
@Test public void testPublisherSetInboundMessageChannel() { AbstractMqttClientService clientService = Mockito.mock(AbstractMqttClientService.class, Mockito.withSettings().useConstructor(MqttClientConnectionType.PUBLISHER) .defaultAnswer(Mockito.CALLS_REAL_METHODS)); Assert.assertNull(clientService.inboundMessageChannel...
TopicSubscription { @Override public TopicSubscription clone() { TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService); record.setSubscribed(this.subscribed); return record; } TopicSubscription(final String topicFilter, final MqttQualityOfService qualityOfService); String getTopicFil...
@Test public void testClone() { TopicSubscription topic = new TopicSubscription(TOPIC_FILTER, MqttQualityOfService.QOS_0); TopicSubscription clone = topic.clone(); Assert.assertEquals(topic.getTopicFilter(), clone.getTopicFilter()); Assert.assertEquals(topic.getQualityOfService(), clone.getQualityOfService()); Assert.a...
MqttClientConfiguration { public void setDefaultQualityOfService(MqttQualityOfService defaultQualityOfService) { Assert.notNull(defaultQualityOfService, "'defaultQualityOfService' must be set!"); this.defaultQualityOfService = defaultQualityOfService; } MqttClientConfiguration(); MqttQualityOfService getDefaultQualityO...
@Test public void testDefaultQualityOfServiceNull() { MqttClientConfiguration configuration = new MqttClientConfiguration(); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("'defaultQualityOfService' must be set!"); configuration.setDefaultQualityOfService(null); }
MqttMessagePublishFailureEvent extends MqttMessageStatusEvent { public MessagingException getException() { return exception; } MqttMessagePublishFailureEvent(final String clientId, final MessagingException exception, final Object source); MessagingException getException(); }
@Test public void test() { final Message<String> message = MessageBuilder.withPayload(PAYLOAD).build(); final MessagingException exception = new MessagingException(message, String.format( "Client ID '%s' could not publish this message because either the topic or payload isn't set, or the payload could not be converted....
MqttMessageDeliveredEvent extends MqttMessageStatusEvent { public int getMessageIdentifier() { return messageIdentifier; } MqttMessageDeliveredEvent(String clientId, int messageIdentifier, Object source); int getMessageIdentifier(); }
@Test public void test() { MqttMessageDeliveredEvent event = new MqttMessageDeliveredEvent(CLIENT_ID, MESSAGE_ID, this); Assert.assertEquals(MESSAGE_ID, event.getMessageIdentifier()); }
MqttStatusEvent extends ApplicationEvent { public String getClientId() { return clientId; } MqttStatusEvent(String clientId, Object source); String getClientId(); }
@Test public void test() { MqttStatusEvent event = new MqttStatusEvent(CLIENT_ID, this); Assert.assertEquals(CLIENT_ID, event.getClientId()); }
MqttClientConnectionLostEvent extends MqttConnectionStatusEvent { public boolean isAutoReconnect() { return autoReconnect; } MqttClientConnectionLostEvent(String clientId, boolean autoReconnect, Object source); boolean isAutoReconnect(); }
@Test public void test() { MqttClientConnectionLostEvent event = new MqttClientConnectionLostEvent(CLIENT_ID, true, this); Assert.assertTrue(event.isAutoReconnect()); event = new MqttClientConnectionLostEvent(CLIENT_ID, false, this); Assert.assertFalse(event.isAutoReconnect()); }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSub...
@Test public void testFindMatch() { Assert.assertNotNull( TopicSubscriptionHelper.findByTopicFilter(TOPIC_FILTER_1, topicSubscriptions)); } @Test public void testFindNoMatchNoTopicFilter() { Assert.assertNull(TopicSubscriptionHelper.findByTopicFilter("test", topicSubscriptions)); } @Test public void testFindNoMatchWron...
JuelTransform implements DomTransform { @Override public Object transform(Object dom, MappingContext context) { if (dom instanceof String) { final String str = (String) dom; if (str.contains("${")) { final boolean assigned = session.setLocalContext(context); try { final ValueExpression expr = factory.createValueExpress...
@Test public void testNonString() { final Object in = new Object(); final Object out = new JuelTransform().transform(in, new MappingContext()); assertEquals(in, out); } @Test public void testPlainString() { final Object in = "Hello"; final Object out = new JuelTransform().transform(in, new MappingContext()); assertEqua...
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig)...
@Test public void testMap() { assertEquals(singletonMap(Arrays.asList(8_000_000_000L)), singletonMap(FixDoubles.fix(Arrays.asList(8_000_000_000.0)))); } @Test public void testDouble() { assertEquals(123.4, FixDoubles.fix(123.4)); } @Test public void testInt() { assertEquals(123, FixDoubles.fix(123.0)); } @Test public v...
LogConfig { public Logger getLogger() { return logger; } Logger getLogger(); }
@Test public void test() throws IOException { final LogConfig config = new MappingContext() .withParser(new SnakeyamlParser()) .fromStream(LogConfigTest.class.getClassLoader().getResourceAsStream("sample-inline.yaml")) .map(LogConfig.class); assertNotNull(config.getLogger()); assertEquals("org.myproject.MyLogger", conf...
JuelTransform implements DomTransform { public void configure(Configurator c) { Exceptions.wrap(() -> c.apply(this), RuntimeException::new); } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform wit...
@Test(expected=RuntimeException.class) public void testConfiguratorException() { new JuelTransform().configure(t -> { throw new Exception(); }); }
JuelTransform implements DomTransform { public static String getEnv(String key, String defaultValue) { final String existingValue = nullCoerce(System.getenv(key)); return ifAbsent(existingValue, give(defaultValue)); } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue)...
@Test public void testGetEnvExisting() { final String value = JuelTransform.getEnv("HOME", null); assertNotNull(value); } @Test public void testGetEnvNonExistent() { final String defaultValue = "someDefaultValue"; final String value = JuelTransform.getEnv("GIBB_BB_BBERISH", defaultValue); assertSame(defaultValue, value...
JuelTransform implements DomTransform { static String nullCoerce(String str) { return str != null && ! str.isEmpty() ? str : null; } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(...
@Test public void testNullCoerce() { assertEquals("nonNullString", JuelTransform.nullCoerce("nonNullString")); assertNull(JuelTransform.nullCoerce(null)); assertNull(JuelTransform.nullCoerce("")); }
MessageProducerImpl implements MessageProducer { @Override public void send(String destination, Message message) { prepareMessageHeaders(destination, message); implementation.withContext(() -> send(message)); } MessageProducerImpl(MessageInterceptor[] messageInterceptors, ChannelMapping channelMapping, MessageProducerI...
@Test public void shouldSendMessage() { ChannelMapping channelMapping = mock(ChannelMapping.class); MessageProducerImplementation implementation = mock(MessageProducerImplementation.class); MessageProducerImpl mp = new MessageProducerImpl(new MessageInterceptor[0], channelMapping, implementation); String transformedDes...
HttpDateHeaderFormatUtil { public static String nowAsHttpDateString() { return timeAsHttpDateString(ZonedDateTime.now(ZoneId.of("GMT"))); } static String nowAsHttpDateString(); static String timeAsHttpDateString(ZonedDateTime gmtTime); }
@Test public void shouldFormatDateNow() { Assert.assertNotNull((HttpDateHeaderFormatUtil.nowAsHttpDateString())); }
HttpDateHeaderFormatUtil { public static String timeAsHttpDateString(ZonedDateTime gmtTime) { return gmtTime.format(DateTimeFormatter.RFC_1123_DATE_TIME); } static String nowAsHttpDateString(); static String timeAsHttpDateString(ZonedDateTime gmtTime); }
@Test public void shouldFormatDate() { String expected = "Tue, 15 Nov 1994 08:12:31 GMT"; ZonedDateTime time = ZonedDateTime.parse(expected, DateTimeFormatter.RFC_1123_DATE_TIME); assertEquals(expected, HttpDateHeaderFormatUtil.timeAsHttpDateString(time)); }
CommandDispatcher { public void messageHandler(Message message) { logger.trace("Received message {} {}", commandDispatcherId, message); Optional<CommandHandler> possibleMethod = commandHandlers.findTargetMethod(message); if (!possibleMethod.isPresent()) { throw new RuntimeException("No method for " + message); } Comman...
@Test public void shouldDispatchCommand() { String commandDispatcherId = "fooId"; CommandDispatcherTestTarget target = spy(new CommandDispatcherTestTarget()); ChannelMapping channelMapping = mock(ChannelMapping.class); MessageConsumer messageConsumer = mock(MessageConsumer.class); MessageProducer messageProducer = mock...
ResourcePathPattern { public ResourcePath replacePlaceholders(PlaceholderValueProvider placeholderValueProvider) { return new ResourcePath(Arrays.stream(splits).map(s -> isPlaceholder(s) ? placeholderValueProvider.get(placeholderName(s)).orElseGet(() -> { throw new RuntimeException("Placeholder not found: " + placehold...
@Test public void shouldReplacePlaceholders() { ResourcePathPattern rpp = new ResourcePathPattern("/foo/{bar}"); ResourcePath rp = rpp.replacePlaceholders(new SingleValuePlaceholderValueProvider("baz")); assertEquals("/foo/baz", rp.toPath()); }
UserServiceImpl implements UserService { @Override public User getUserByApi(String token) { String s = HttpClientUtils.doGet(api_getUserByToken + token); QuarkResult quarkResult = JsonUtils.jsonToQuarkResult(s, User.class); User data= (User) quarkResult.getData(); return data; } @Override User getUserByApi(String toke...
@Test public void getUserByApi() throws Exception { User user =userService.getUserByApi("bee1a09b-9867-4f1a-9886-c25d8b0e42b1"); System.out.println(user); }
PartlyCovered { String partlyCovered(String string, boolean trigger){ if(trigger){ string = string.toLowerCase(); } return string; } }
@Test void test() { PartlyCovered partlyCovered = new PartlyCovered(); String string = partlyCovered.partlyCovered("THIS IS A STRING", false); assertThat(string).isEqualTo("THIS IS A STRING"); }
QuotesProperties { List<Quote> getQuotes() { return this.quotes; } QuotesProperties(List<Quote> quotes); }
@Test void staticQuotesAreLoaded() { assertThat(quotesProperties.getQuotes()).hasSize(2); }
Controller { @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) public Car get(@PathVariable String number) { return cacheClient.get(number); } Controller(CacheClient cacheClient); @PostMapping(path = "/{number}", produces= MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(code = HttpStatus.C...
@Test void putGet() throws Exception { String number = "BO5489"; Car car = Car.builder() .number(number) .name("VW") .build(); String content = objectMapper.writeValueAsString(car); mockMvc.perform( post("/cars/" + number) .content(content) .contentType(MediaType.APPLICATION_JSON_VALUE) ).andExpect(status().isCreated()...
Controller { @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) public Car get(@PathVariable String number) { return cacheClient.get(number); } Controller(CacheClient cacheClient); @PostMapping(value = "/{number}",produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(code = HttpStatus....
@Test void putGet() throws Exception { String number = "BO5489"; Car car = Car.builder().color(number).name("VW").build(); String content = objectMapper.writeValueAsString(car); mockMvc .perform( post("/cars/" + number).content(content).contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isCreated()); St...
StatefulBlockingClient { @Scheduled(fixedDelay = 3000) public void send() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("white") .name("vw") .build(); RegistrationDto registrationDto = template.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<...
@Test void sendMessageSynchronously() { ThrowableAssert.ThrowingCallable send = () -> statefulBlockingClient.send(); assertThatCode(send).doesNotThrowAnyException(); }
StatefulCallbackClient { @Scheduled(fixedDelay = 3000, initialDelay = 1500) public void sendAsynchronouslyWithCallback() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("black") .name("bmw") .build(); RabbitConverterFuture<RegistrationDto> rabbitConverterFuture = asyncRabbitTemplate.convertSendAndRecei...
@Test void sendAsynchronouslyWithCallback() { ThrowableAssert.ThrowingCallable send = () -> statefulCallbackClient.sendAsynchronouslyWithCallback(); assertThatCode(send).doesNotThrowAnyException(); }
StatefulFutureClient { @Scheduled(fixedDelay = 3000, initialDelay = 1500) public void sendWithFuture() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("black") .name("bmw") .build(); ListenableFuture<RegistrationDto> listenableFuture = asyncRabbitTemplate.convertSendAndReceiveAsType( directExchange.get...
@Test void sendAsynchronously() { ThrowableAssert.ThrowingCallable send = () -> statefulFutureClient.sendWithFuture(); assertThatCode(send) .doesNotThrowAnyException(); }
StatelessClient { @Scheduled(fixedDelay = 3000) public void sendAndForget() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("white") .name("vw") .build(); UUID correlationId = UUID.randomUUID(); registrationService.saveCar(carDto, correlationId); MessagePostProcessor messagePostProcessor = message -> {...
@Test void sendAndForget() { ThrowableAssert.ThrowingCallable send = () -> statelessClient.sendAndForget(); assertThatCode(send).doesNotThrowAnyException(); }
CarResource { @PutMapping private CarDto updateCar(@RequestBody CarDto carDto) { Car car = carMapper.toCar(carDto); return carMapper.toCarDto(carService.update(car)); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }
@Test @Sql("/insert_car.sql") void updateCar() throws Exception { CarDto carDto = CarDto.builder() .id(UUID.fromString("1b104b1a-8539-4e06-aea7-9d77f2193b80")) .name("vw") .color("white") .build(); mockMvc.perform( put("/cars") .content(objectMapper.writeValueAsString(carDto)) .contentType(MediaType.APPLICATION_JSON) )...
CarResource { @GetMapping(value = "/{uuid}") private CarDto get(@PathVariable UUID uuid){ return carMapper.toCarDto(carService.get(uuid)); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }
@Test @Sql("/insert_car.sql") void getCar() throws Exception { UUID id = UUID.fromString("1b104b1a-8539-4e06-aea7-9d77f2193b80"); mockMvc.perform( get("/cars/" + id) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(status().isOk()); }
CarResource { @DeleteMapping(value = "/{uuid}") @ResponseStatus(HttpStatus.NO_CONTENT) private void delete(@PathVariable UUID uuid){ carService.delete(uuid); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }
@Test @Sql("/insert_car.sql") void deleteCar() throws Exception { UUID id = UUID.fromString("1b104b1a-8539-4e06-aea7-9d77f2193b80"); mockMvc.perform( delete("/cars/" + id) ) .andExpect(status().isNoContent()); }
PartlyCovered { String covered(String string) { string = string.toLowerCase(); return string; } }
@Test void testSimple() { PartlyCovered fullyCovered = new PartlyCovered(); String string = fullyCovered.covered("THIS IS A STRING"); assertThat(string).isEqualTo("this is a string"); }
UserDetailsMapper { UserDetails toUserDetails(UserCredentials userCredentials) { return User.withUsername(userCredentials.getUsername()) .password(userCredentials.getPassword()) .roles(userCredentials.getRoles().toArray(String[]::new)) .build(); } }
@Test void toUserDetails() { UserCredentials userCredentials = UserCredentials.builder() .enabled(true) .password("password") .username("user") .roles(Set.of("USER", "ADMIN")) .build(); UserDetails userDetails = userDetailsMapper.toUserDetails(userCredentials); assertThat(userDetails.getUsername()).isEqualTo("user"); a...
BCryptExample { public String encode(String plainPassword) { int strength = 10; BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(strength, new SecureRandom()); return bCryptPasswordEncoder.encode(plainPassword); } String encode(String plainPassword); }
@Test void encode() { String plainPassword = "password"; String encoded = bcryptExample.encode(plainPassword); assertThat(encoded).startsWith("$2a$10"); }
Pbkdf2Example { public String encode(String plainPassword) { String pepper = "pepper"; int iterations = 200000; int hashWidth = 256; Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(pepper, iterations, hashWidth); return pbkdf2PasswordEncoder.encode(plainPassword); } String encode(String plainPa...
@Test void encode() { String plainPassword = "plainPassword"; String actual = pbkdf2Example.encode(plainPassword); assertThat(actual).hasSize(80); }
Argon2Example { public String encode(String plainPassword) { int saltLength = 16; int hashLength = 32; int parallelism = 1; int memory = 4096; int iterations = 3; Argon2PasswordEncoder argon2PasswordEncoder = new Argon2PasswordEncoder(saltLength, hashLength, parallelism, memory, iterations); return argon2PasswordEncode...
@Test void encode() { String plainPassword = "password"; String actual = argon2Example.encode(plainPassword); assertThat(actual).startsWith("$argon2id$v=19$m=4096,t=3,p=1"); }
SCryptExample { public String encode(String plainPassword) { int cpuCost = (int) Math.pow(2, 14); int memoryCost = 8; int parallelization = 1; int keyLength = 32; int saltLength = 64; SCryptPasswordEncoder sCryptPasswordEncoder = new SCryptPasswordEncoder(cpuCost, memoryCost, parallelization, keyLength, saltLength); re...
@Test void encode() { String plainPassword = "password"; String actual = sCryptExample.encode(plainPassword); assertThat(actual).hasSize(140); assertThat(actual).startsWith("$e0801"); }
BcCryptWorkFactorService { public int calculateStrength() { for (int strength = MIN_STRENGTH; strength <= MAX_STRENGTH; strength++) { long duration = calculateDuration(strength); if (duration >= GOAL_MILLISECONDS_PER_PASSWORD) { return strength; } } throw new RuntimeException( String.format( "Could not find suitable ro...
@Test void calculateStrength() { int strength = bcCryptWorkFactorService.calculateStrength(); assertThat(strength).isBetween(4, 31); }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength...
@Test void findCloserToShouldReturnNumber1IfItCloserToGoalThanNumber2() { int number1 = 950; int number2 = 1051; boolean actual = bcCryptWorkFactorService.isPreviousDurationCloserToGoal(number1, number2); assertThat(actual).isTrue(); } @Test void findCloserToShouldReturnNUmber2IfItCloserToGoalThanNumber1() { int number...
FullyCovered { String lowercase(String string) { string = string.toLowerCase(); return string; } }
@Test void test() { FullyCovered fullyCovered = new FullyCovered(); String string = fullyCovered.lowercase("THIS IS A STRING"); assertThat(string).isEqualTo("this is a string"); }
BcCryptWorkFactorService { int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
@Test void getStrengthShouldReturn4IfStrengthIs4() { int currentStrength = 4; int actual = bcCryptWorkFactorService.getStrength(0, 0, currentStrength); assertThat(actual).isEqualTo(4); } @Test void getStrengthShouldReturnPreviousStrengthIfPreviousDurationCloserToGoal() { int actual = bcCryptWorkFactorService.getStrengt...
Pbkdf2WorkFactorService { public int calculateIteration() { int iterationNumber = 150000; while (true) { Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(NO_ADDITIONAL_SECRET, iterationNumber, HASH_WIDTH); Stopwatch stopwatch = Stopwatch.createStarted(); pbkdf2PasswordEncoder.encode(TEST_PASSWORD...
@Test void calculateIteration() { int iterationNumber = pbkdf2WorkFactorService.calculateIteration(); assertThat(iterationNumber).isGreaterThanOrEqualTo(150000); }
MessageConsumer { public void consumeStringMessage(String messageString) throws IOException { logger.info("Consuming message '{}'", messageString); UserCreatedMessage message = objectMapper.readValue(messageString, UserCreatedMessage.class); Validator validator = Validation.buildDefaultValidatorFactory().getValidator()...
@Test @PactVerification("userCreatedMessagePact") public void verifyCreatePersonPact() throws IOException { messageConsumer.consumeStringMessage(new String(this.currentMessage)); }
ReactiveBatchProcessor { void start() { Scheduler scheduler = threadPoolScheduler(threads, threadPoolQueueSize); messageSource.getMessageBatches() .subscribeOn(Schedulers.from(Executors.newSingleThreadExecutor())) .doOnNext(batch -> logger.log(batch.toString())) .flatMap(batch -> Flowable.fromIterable(batch.getMessages...
@Test void allMessagesAreProcessedOnMultipleThreads() { int batches = 10; int batchSize = 3; int threads = 2; int threadPoolQueueSize = 10; MessageSource messageSource = new TestMessageSource(batches, batchSize); TestMessageHandler messageHandler = new TestMessageHandler(); ReactiveBatchProcessor processor = new Reacti...
IpAddressValidator implements ConstraintValidator<IpAddress, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { Pattern pattern = Pattern.compile("^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$"); Matcher matcher = pattern.matcher(value); try { if (!matcher.match...
@Test void test(){ IpAddressValidator validator = new IpAddressValidator(); assertTrue(validator.isValid("111.111.111.111", null)); assertFalse(validator.isValid("111.foo.111.111", null)); assertFalse(validator.isValid("111.111.256.111", null)); }
ValidatingServiceWithGroups { @Validated(OnCreate.class) void validateForCreate(@Valid InputWithCustomValidator input){ } }
@Test void whenInputIsInvalidForCreate_thenThrowsException() { InputWithCustomValidator input = validInput(); input.setId(42L); assertThrows(ConstraintViolationException.class, () -> { service.validateForCreate(input); }); }
ValidatingServiceWithGroups { @Validated(OnUpdate.class) void validateForUpdate(@Valid InputWithCustomValidator input){ } }
@Test void whenInputIsInvalidForUpdate_thenThrowsException() { InputWithCustomValidator input = validInput(); input.setId(null); assertThrows(ConstraintViolationException.class, () -> { service.validateForUpdate(input); }); }
ValidatingService { void validateInput(@Valid Input input){ } }
@Test void whenInputIsValid_thenThrowsNoException(){ Input input = new Input(); input.setNumberBetweenOneAndTen(5); input.setIpAddress("111.111.111.111"); service.validateInput(input); } @Test void whenInputIsInvalid_thenThrowsException(){ Input input = new Input(); input.setNumberBetweenOneAndTen(0); input.setIpAddres...
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); ...
@Test public void logTrace() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.TRACE); logger.log(LogLevel.TRACE, "logger name", "trace message"); assertThat(capture.toString(), containsString("TRACE logger name - trace message")); } @Test public void logFa...
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEna...
@Test public void isLogTraceEnabled() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.TRACE); assertTrue(logger.isEnabled(LogLevel.TRACE, "logger name")); } @Test public void isLogDebugEnabled() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .set...
HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads, int maxInitialLineLength, int maxHeadersSize, boolean followRedirects, CharSequence userAgent, List<RequestInterceptor> interceptors, ...
@Test public void testRelativeRedirects() throws Throwable { try (DeferredAssertions as = new DeferredAssertions()) { client.get().setURL("http: @Override public void receive(final State<?> object) { if (object.stateType() == StateType.Redirect) { as.add(new Assertion() { @Override public void exec() throws Throwable {...
HttpClient { public HttpRequestBuilder post() { return new RB(Method.POST); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads, int maxInitialLineLength, int maxHeadersSize, boolean followRedirects, CharSequence userAgent, List<RequestInterceptor> interceptors, ...
@Test public void testPost() throws Throwable { final AM am = new AM(); final String ur = "http: client.addActivityMonitor(am); final DeferredAssertions assertions = new DeferredAssertions(); final Set<StateType> stateTypes = new HashSet<>(); final String[] xheader = new String[1]; ResponseFuture f = client.post() .set...
MigrationsPlugin implements Plugin { public void init(Application<? extends ApplicationConfiguration> application) { DatabaseConfiguration dbConfig = application.getConfiguration().getDatabaseConfiguration(); URI uri = getUri(dbConfig.getUrl()); if (Strings.isNullOrEmpty(uri.getPath())) { flyway.setDataSource(dbConfig....
@Test public void shouldSetDataSourceOnInit() { plugin.init(application); verify(flyway).setDataSource("jdbc:mysql: verify(flyway).setSchemas("test"); } @Test public void shouldMigrateOnInit() { plugin.init(application); verify(flyway).migrate(); }
EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void h...
@Test public void shouldSetEntityKeyOnMetaDataWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("getCode"); handler.handle(metaData, key, method); verify(metaData).setEntityKey("code"); } @Test public void shouldSetEntityKeyOnMetaDataWhenOnField() throws Exception { Field field = Dumm...
SecureMultipleAnnotationHandler extends SecureAnnotationHandler { public void handle(SecurableMetaData metaData, Annotation annotation) { for (Secure secure : ((SecureMultiple) annotation).value()) { super.handle(metaData, secure); } } void handle(SecurableMetaData metaData, Annotation annotation); }
@Test public void shouldHandleSecureAnnotation() { SecurableMetaData metaData = mock(SecurableMetaData.class); SecureMultipleAnnotationHandler handler = new SecureMultipleAnnotationHandler(); SecureMultiple multiple = mock(SecureMultiple.class); Secure secure1 = mock(Secure.class); when(secure1.permissions()).thenRetur...
ManyToManyAnnotationHandler extends OneToManyAnnotationHandler { @Override public Class<?> getAnnotationType() { return ManyToMany.class; } @Override Class<?> getAnnotationType(); }
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), ManyToMany.class); }
ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return Action.class; } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Cl...
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), Action.class); }
ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateR...
@Test public void shouldAddActionMethodToMetadataWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("dummyAction"); handler.handle(metaData, annotation, method); ActionMetaData data = new ActionMetaData("dummyAction", "/dummy", method); verify(metaData).addActionMethod(data); } @Test p...
AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClien...
@Test public void shouldGetClientFromSessionIfClientNameAttributeIsSet() { Session session = mock(Session.class); when(session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn("client1"); assertEquals(filter.getClient(session), basicClient); } @Test public void shouldReturnNullClientFromSessionIfClientNa...
SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return Searchable.class; } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Ove...
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), Searchable.class); }
SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMeta...
@Test public void shouldAddSearchFieldToMetadataWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("getCode"); handler.handle(metaData, annotation, method); ParameterMetaData data = new ParameterMetaData("code", "code", String.class); metaData.addSearchField(data); } @Test public void ...
OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return OneToOne.class; } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Overrid...
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), OneToOne.class); }
OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { AssociationMetaData associationMetaData = new AssociationMetaData(getGetterName(method, false), method.getReturnType(), isEntity(method.getReturnType())); met...
@Test public void shouldAddToMetadataAssociationWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("getSpouse"); handler.handle(metaData, annotation, method); AssociationMetaData data = new AssociationMetaData("spouse", DummyModel.class, true); verify(metaData).addAssociation(data); } ...
SecureAnnotationHandler { public void handle(SecurableMetaData metaData, Annotation annotation) { metaData.addPermissionMetaData(constructPermissionMetaData(annotation)); } void handle(SecurableMetaData metaData, Annotation annotation); }
@Test public void shouldHandleSecureAnnotation() { SecurableMetaData metaData = mock(SecurableMetaData.class); SecureAnnotationHandler handler = new SecureAnnotationHandler(); Secure secure = mock(Secure.class); when(secure.permissions()).thenReturn(new String[] {"permission1", "permission2"}); when(secure.method()).th...
ManyToOneAnnotationHandler extends OneToOneAnnotationHandler { @Override public Class<?> getAnnotationType() { return ManyToOne.class; } @Override Class<?> getAnnotationType(); }
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), ManyToOne.class); }
EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public void construct() { LinkedList<EntityNode> queue = new LinkedList<EntityNode>(); queue.offer(this); while (! queue.isEmpty()) { EntityNode node = queue.poll(); for (CollectionMetaData collection : node.getValue().getCollections()) { if (! colle...
@Test public void shouldConstructEntityTree() { entityNode = new EntityNode(CompositeModel.class, namingStrategy); entityNode.construct(); assertEquals(entityNode.getChildren().size(), 2); }
EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public String getName() { return name; } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy naming...
@Test public void shouldPopulateEntityNodeName() { entityNode = new EntityNode(CompositeModel.class, namingStrategy); assertEquals(entityNode.getName(), "compositeModel"); }
EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public String getResourceName() { return resourceName; } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, Namin...
@Test public void shouldPopulateEntityResourceName() { entityNode = new EntityNode(CompositeModel.class, namingStrategy); assertEquals(entityNode.getResourceName(), "composite_models"); }
EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public EntityMetaData getEntityMetaData() { return getValue(); } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collectio...
@Test public void shouldPopulateEntityMetaData() { entityNode = new EntityNode(Parent.class, namingStrategy); assertEquals(entityNode.getEntityMetaData(), EntityMetaDataProvider.instance().getEntityMetaData(Parent.class)); }
ResourceWrapper { public CtClass getGeneratedClass() { return generatedClass; } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }
@Test public void shouldCreateGeneratedClass() { wrapper = new ResourceWrapper(resource, entityClass); assertNotNull(wrapper.getGeneratedClass()); }
ResourceWrapper { protected ResourceClassCreator getResourceClassCreator() { return new ResourceClassCreator(resource, namingStrategy, entityClass, path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }
@Test public void shouldCreateResourceClassCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourceClassCreator creator = wrapper.getResourceClassCreator(); assertEquals(creator.getEntityClass(), entityClass); assertEquals(creator.getPath(), resource.getPath()); assertEquals(creator.getResource()...
ResourceWrapper { protected CreateMethodCreator getCreateMethodCreator(ResourcePath path) { return new CreateMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }
@Test public void shouldGetCreateMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, true, namingStrategy); CreateMethodCreator creator = wrapper.getCreateMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); }
ResourceWrapper { protected ReadMethodCreator getReadMethodCreator(ResourcePath path) { return new ReadMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }
@Test public void shouldGetReadMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); ReadMethodCreator creator = wrapper.getReadMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); }
ResourceWrapper { protected ActionMethodCreator getActionMethodCreator(ResourcePath path, ActionMetaData action) { return new ActionMethodCreator(generatedClass, resource, path, this.path, action); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); Ct...
@Test public void shouldGetActionMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); ActionMetaData action = mock(ActionMetaData.class); ActionMethodCreator creator = wrapper.getActionMethodCreator(resourcePath, action);...
ResourceWrapper { protected DeleteMethodCreator getDeleteMethodCreator(ResourcePath path) { return new DeleteMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }
@Test public void shouldGetDeleteMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); DeleteMethodCreator creator = wrapper.getDeleteMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); }
ResourceWrapper { protected ListMethodCreator getListMethodCreator(ResourcePath path) { return new ListMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }
@Test public void shouldGetListMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); ListMethodCreator creator = wrapper.getListMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); }
ResourceWrapper { protected UpdateMethodCreator getUpdateMethodCreator(ResourcePath path) { return new UpdateMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }
@Test public void shouldGetUpdateMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); UpdateMethodCreator creator = wrapper.getUpdateMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); }
PathAnnotationHandler extends AbstractResourceAnnotationHandler { public Class<?> getAnnotationType() { return Path.class; } void handle(ResourceMetaData metaData, Annotation annotation, Method method); Class<?> getAnnotationType(); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); ...
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), Path.class); }
PathAnnotationHandler extends AbstractResourceAnnotationHandler { public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { if (! hasHttpMethod(method)) { ResourceMetaData subResource = new ResourceMetaData(method.getReturnType(), HttpUtil.concatPaths(metaData.getPath(), ((Path)annotation).v...
@Test public void shouldAddSubResourceLocatorToResource() throws Exception { Path path = mock(Path.class); when(path.value()).thenReturn("/sub"); handler.handle(metaData, path, DummyResource.class.getMethod("subResource")); assertTrue(! metaData.getSubResources().isEmpty()); assertEquals(metaData.getSubResources().iter...
HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : nul...
@Test public void shouldHandleGETAnnotation() throws Exception { GETAnnotationHandler handler = new GETAnnotationHandler(); handler.handle(metaData, mock(GET.class), DummyResource.class.getMethod("get")); assertTrue(! metaData.getResourceMethods().isEmpty()); assertEquals(metaData.getResourceMethods().iterator().next()...
AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { @SuppressWarnings("rawtypes") protected User retrieveProfile(Session session) { Object profile = session.getAttribute(PRINCIPAL); if (profile == null) { return null; } Client client = getClient(session); Cla...
@Test public void shouldReturnNullProfileIfNotFoundInSession() { Session session = mock(Session.class); when(session.getAttribute(AuthenticationFilter.PRINCIPAL)).thenReturn(null); assertNull(filter.retrieveProfile(session)); }
ResourceMetaDataBuilder extends MetaDataBuilder<ResourceMetaData, AbstractResourceAnnotationHandler> { @Override public ResourceMetaData build() { ResourceMetaData metaData = super.build(); for (ResourceMetaData subResource : metaData.getSubResources()) { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(su...
@Test public void shouldBuildResourceMetaData() throws Exception { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(DummyResource.class); ResourceMetaData metaData = builder.build(); assertEquals(metaData.getResourceMethods().size(), 1); assertEquals(metaData.getResourceMethods().iterator().next(), new Res...