formatting work

This commit is contained in:
Eugen Paraschiv 2018-03-04 17:53:14 +02:00
parent 5fd8e4293e
commit 8d633d6402
48 changed files with 101 additions and 248 deletions

View File

@ -9,8 +9,7 @@ public class AttrListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
servletContextEvent.getServletContext()
.setAttribute("servlet-context-attr", "test");
servletContextEvent.getServletContext().setAttribute("servlet-context-attr", "test");
System.out.println("context init");
}

View File

@ -16,8 +16,7 @@ public class EchoServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
Path path = File.createTempFile("echo", "tmp")
.toPath();
Path path = File.createTempFile("echo", "tmp").toPath();
Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
Files.copy(path, response.getOutputStream());
Files.delete(path);

View File

@ -18,8 +18,7 @@ public class HelloFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletResponse.getOutputStream()
.print(filterConfig.getInitParameter("msg"));
servletResponse.getOutputStream().print(filterConfig.getInitParameter("msg"));
filterChain.doFilter(servletRequest, servletResponse);
}

View File

@ -21,9 +21,7 @@ public class HelloServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
response.getOutputStream()
.write(servletConfig.getInitParameter("msg")
.getBytes());
response.getOutputStream().write(servletConfig.getInitParameter("msg").getBytes());
} catch (IOException e) {
e.printStackTrace();
}

View File

@ -98,13 +98,8 @@ public class MySQLAutoconfiguration {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate");
return Arrays.stream(CLASS_NAMES)
.filter(className -> ClassUtils.isPresent(className, context.getClassLoader()))
.map(className -> ConditionOutcome.match(message.found("class")
.items(Style.NORMAL, className)))
.findAny()
.orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes")
.items(Style.NORMAL, Arrays.asList(CLASS_NAMES))));
return Arrays.stream(CLASS_NAMES).filter(className -> ClassUtils.isPresent(className, context.getClassLoader())).map(className -> ConditionOutcome.match(message.found("class").items(Style.NORMAL, className))).findAny()
.orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES))));
}
}

View File

@ -28,9 +28,7 @@ public class ContactInfoValidator implements ConstraintValidator<ContactInfo, St
if (StringUtils.isEmptyOrWhitespace(expressionType)) {
LOG.error("Contact info type missing!");
} else {
pattern = expressionRepository.findOne(expressionType)
.map(ContactInfoExpression::getPattern)
.orElse("");
pattern = expressionRepository.findOne(expressionType).map(ContactInfoExpression::getPattern).orElse("");
}
}

View File

@ -18,10 +18,7 @@ public class PersistenceConfig {
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2)
.addScript("schema-expressions.sql")
.addScript("data-expressions.sql")
.build();
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2).addScript("schema-expressions.sql").addScript("data-expressions.sql").build();
return db;
}
}

View File

@ -12,15 +12,11 @@ public class MyBeanNotOfRequiredTypeFailureAnalyzer extends AbstractFailureAnaly
}
private String getDescription(BeanNotOfRequiredTypeException ex) {
return String.format("The bean %s could not be injected as %s because it is of type %s", ex.getBeanName(), ex.getRequiredType()
.getName(),
ex.getActualType()
.getName());
return String.format("The bean %s could not be injected as %s because it is of type %s", ex.getBeanName(), ex.getRequiredType().getName(), ex.getActualType().getName());
}
private String getAction(BeanNotOfRequiredTypeException ex) {
return String.format("Consider creating a bean with name %s of type %s", ex.getBeanName(), ex.getRequiredType()
.getName());
return String.format("Consider creating a bean with name %s of type %s", ex.getBeanName(), ex.getRequiredType().getName());
}
}

View File

@ -11,8 +11,6 @@ public class AuthorDao {
}
public Optional<Author> getAuthor(String id) {
return authors.stream()
.filter(author -> id.equals(author.getId()))
.findFirst();
return authors.stream().filter(author -> id.equals(author.getId())).findFirst();
}
}

View File

@ -13,8 +13,7 @@ public class Mutation implements GraphQLMutationResolver {
public Post writePost(String title, String text, String category, String author) {
Post post = new Post();
post.setId(UUID.randomUUID()
.toString());
post.setId(UUID.randomUUID().toString());
post.setTitle(title);
post.setText(text);
post.setCategory(category);

View File

@ -11,16 +11,11 @@ public class PostDao {
}
public List<Post> getRecentPosts(int count, int offset) {
return posts.stream()
.skip(offset)
.limit(count)
.collect(Collectors.toList());
return posts.stream().skip(offset).limit(count).collect(Collectors.toList());
}
public List<Post> getAuthorPosts(String author) {
return posts.stream()
.filter(post -> author.equals(post.getAuthorId()))
.collect(Collectors.toList());
return posts.stream().filter(post -> author.equals(post.getAuthorId())).collect(Collectors.toList());
}
public void savePost(Post post) {

View File

@ -31,6 +31,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
registry.addInterceptor(localeChangeInterceptor());
}
}

View File

@ -15,18 +15,17 @@ public class QueryController {
private static int REQUEST_COUNTER = 0;
@GetMapping("/reqcount")
public int getReqCount(){
public int getReqCount() {
return REQUEST_COUNTER;
}
@GetMapping("/{code}")
public String getStockPrice(@PathVariable String code){
public String getStockPrice(@PathVariable String code) {
REQUEST_COUNTER++;
if("BTC".equalsIgnoreCase(code))
if ("BTC".equalsIgnoreCase(code))
return "10000";
else return "N/A";
else
return "N/A";
}
}

View File

@ -28,11 +28,7 @@ public class WebMvcConfigure extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver());
}
@Bean

View File

@ -13,7 +13,6 @@ public class AnnotationServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/annotationservlet.jsp")
.forward(request, response);
request.getRequestDispatcher("/annotationservlet.jsp").forward(request, response);
}
}

View File

@ -14,12 +14,10 @@ public class FeaturesAspect {
@Around(value = "@within(featureAssociation) || @annotation(featureAssociation)")
public Object checkAspect(ProceedingJoinPoint joinPoint, FeatureAssociation featureAssociation) throws Throwable {
if (featureAssociation.value()
.isActive()) {
if (featureAssociation.value().isActive()) {
return joinPoint.proceed();
} else {
LOG.info("Feature " + featureAssociation.value()
.name() + " is not enabled!");
LOG.info("Feature " + featureAssociation.value().name() + " is not enabled!");
return null;
}
}

View File

@ -17,8 +17,7 @@ public enum MyFeatures implements Feature {
EMPLOYEE_MANAGEMENT_FEATURE;
public boolean isActive() {
return FeatureContext.getFeatureManager()
.isActive(this);
return FeatureContext.getFeatureManager().isActive(this);
}
}

View File

@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.boot.boottest","org.baeldung.repository" })
@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.boot.boottest", "org.baeldung.repository" })
@PropertySource("classpath:persistence-generic-entity.properties")
@EnableTransactionManagement
public class H2JpaConfig {

View File

@ -39,31 +39,21 @@ public class GenericEntityController {
@RequestMapping("/entity/findby/{id}")
public GenericEntity findById(@PathVariable Long id) {
return entityList.stream()
.filter(entity -> entity.getId()
.equals(id))
.findFirst()
.get();
return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get();
}
@GetMapping("/entity/findbydate/{date}")
public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) {
return entityList.stream()
.findFirst()
.get();
return entityList.stream().findFirst().get();
}
@GetMapping("/entity/findbymode/{mode}")
public GenericEntity findByEnum(@PathVariable("mode") Modes mode) {
return entityList.stream()
.findFirst()
.get();
return entityList.stream().findFirst().get();
}
@GetMapping("/entity/findbyversion")
public ResponseEntity findByVersion(@Version String version) {
return version != null ? new ResponseEntity(entityList.stream()
.findFirst()
.get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND);
return version != null ? new ResponseEntity(entityList.stream().findFirst().get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND);
}
}

View File

@ -9,23 +9,20 @@ import java.util.Set;
public class GenericBigDecimalConverter implements GenericConverter {
@Override
public Set<ConvertiblePair> getConvertibleTypes () {
public Set<ConvertiblePair> getConvertibleTypes() {
ConvertiblePair[] pairs = new ConvertiblePair[] {
new ConvertiblePair(Number.class, BigDecimal.class),
new ConvertiblePair(String.class, BigDecimal.class)};
ConvertiblePair[] pairs = new ConvertiblePair[] { new ConvertiblePair(Number.class, BigDecimal.class), new ConvertiblePair(String.class, BigDecimal.class) };
return ImmutableSet.copyOf(pairs);
}
@Override
public Object convert (Object source, TypeDescriptor sourceType,
TypeDescriptor targetType) {
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (sourceType.getType() == BigDecimal.class) {
return source;
}
if(sourceType.getType() == String.class) {
if (sourceType.getType() == String.class) {
String number = (String) source;
return new BigDecimal(number);
} else {

View File

@ -1,6 +1,5 @@
package org.baeldung.boot.converter;
import com.baeldung.toggle.Employee;
import org.springframework.core.convert.converter.Converter;

View File

@ -36,8 +36,7 @@ public class UserCombinedSerializer {
public static class UserJsonDeserializer extends JsonDeserializer<User> {
@Override
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
TreeNode treeNode = jsonParser.getCodec()
.readTree(jsonParser);
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor");
return new User(Color.web(favoriteColor.asText()));
}

View File

@ -15,8 +15,7 @@ import java.io.IOException;
public class UserJsonDeserializer extends JsonDeserializer<User> {
@Override
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
TreeNode treeNode = jsonParser.getCodec()
.readTree(jsonParser);
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor");
return new User(Color.web(favoriteColor.asText()));
}

View File

@ -14,8 +14,7 @@ public class MonitoringConfig {
@Bean
public JmxReporter jmxReporter() {
JmxReporter reporter = JmxReporter.forRegistry(registry)
.build();
JmxReporter reporter = JmxReporter.forRegistry(registry).build();
reporter.start();
return reporter;
}

View File

@ -10,13 +10,9 @@ public class MyHealthCheck implements HealthIndicator {
public Health health() {
int errorCode = check(); // perform some specific health check
if (errorCode != 0) {
return Health.down()
.withDetail("Error Code", errorCode)
.withDetail("Description", "You custom MyHealthCheck endpoint is down")
.build();
return Health.down().withDetail("Error Code", errorCode).withDetail("Description", "You custom MyHealthCheck endpoint is down").build();
}
return Health.up()
.build();
return Health.up().build();
}
public int check() {

View File

@ -21,7 +21,7 @@ import java.util.concurrent.Executors;
@RestController
@EnableAutoConfiguration(exclude = MySQLAutoconfiguration.class)
@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources","org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.boot.config"})
@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.boot.config" })
public class SpringBootApplication {
private static ApplicationContext applicationContext;

View File

@ -16,8 +16,7 @@ public class LoginServiceImpl implements LoginService {
public boolean login(String userName, char[] password) {
boolean success;
if (userName.equals("admin") && "secret".toCharArray()
.equals(password)) {
if (userName.equals("admin") && "secret".toCharArray().equals(password)) {
counterService.increment("counter.login.success");
success = true;
} else {

View File

@ -14,14 +14,12 @@ public class FooRepositoryImpl implements FooRepository {
@Override
public void save(Foo foo) {
sessionFactory.getCurrentSession()
.saveOrUpdate(foo);
sessionFactory.getCurrentSession().saveOrUpdate(foo);
}
@Override
public Foo get(Integer id) {
return sessionFactory.getCurrentSession()
.get(Foo.class, id);
return sessionFactory.getCurrentSession().get(Foo.class, id);
}
}

View File

@ -40,8 +40,7 @@ public class SpringBootWithServletComponentIntegrationTest {
FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter");
assertNotNull(filterRegistration);
assertTrue(filterRegistration.getServletNameMappings()
.contains("echo servlet"));
assertTrue(filterRegistration.getServletNameMappings().contains("echo servlet"));
}
@Autowired

View File

@ -60,11 +60,8 @@ public class DisplayBeanIntegrationTest {
@SuppressWarnings("rawtypes")
ResponseEntity<List> entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class);
List<Map<String, Object>> allBeans = (List) ((Map) entity.getBody()
.get(0)).get("beans");
List<String> beanNamesList = allBeans.stream()
.map(x -> (String) x.get("bean"))
.collect(Collectors.toList());
List<Map<String, Object>> allBeans = (List) ((Map) entity.getBody().get(0)).get("beans");
List<String> beanNamesList = allBeans.stream().map(x -> (String) x.get("bean")).collect(Collectors.toList());
assertThat(beanNamesList, hasItem("fooController"));
assertThat(beanNamesList, hasItem("fooService"));

View File

@ -26,18 +26,12 @@ public class AppLiveTest {
@Test
public void getIndex() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Index Page")));
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("Index Page")));
}
@Test
public void getLocal() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/local")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("/local")));
mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("/local")));
}
}

View File

@ -39,7 +39,8 @@ public class KongAdminAPILiveTest {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
}
@Autowired TestRestTemplate restTemplate;
@Autowired
TestRestTemplate restTemplate;
@Test
public void givenEndpoint_whenQueryStockPrice_thenPriceCorrect() {

View File

@ -30,7 +30,8 @@ public class KongLoadBalanceLiveTest {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
}
@Autowired TestRestTemplate restTemplate;
@Autowired
TestRestTemplate restTemplate;
@Test
public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception {

View File

@ -35,8 +35,7 @@ public class ToggleIntegrationTest {
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
.build();
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
@ -46,8 +45,7 @@ public class ToggleIntegrationTest {
System.setProperty("employee.feature", "false");
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + ""))
.andExpect(status().is(200));
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200));
emp = employeeRepository.findOne(1L);
assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5);
@ -60,8 +58,7 @@ public class ToggleIntegrationTest {
System.setProperty("employee.feature", "true");
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + ""))
.andExpect(status().is(200));
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200));
emp = employeeRepository.findOne(1L);
assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5);

View File

@ -21,17 +21,14 @@ public class UtilsControllerIntegrationTest {
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController)
.build();
this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController).build();
}
@Test
public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception {
String param = "testparam";
this.mockMvc.perform(post("/setParam").param("param", param)
.sessionAttr("parameter", param))
.andExpect(status().isOk());
this.mockMvc.perform(post("/setParam").param("param", param).sessionAttr("parameter", param)).andExpect(status().isOk());
}
}

View File

@ -14,9 +14,7 @@ public class MyStompSessionHandlerIntegrationTest {
StompHeaders mockHeader = Mockito.mock(StompHeaders.class);
MyStompSessionHandler sessionHandler = new MyStompSessionHandler();
sessionHandler.afterConnected(mockSession, mockHeader);
Mockito.verify(mockSession)
.subscribe("/topic/messages", sessionHandler);
Mockito.verify(mockSession)
.send(Mockito.anyString(), Mockito.anyObject());
Mockito.verify(mockSession).subscribe("/topic/messages", sessionHandler);
Mockito.verify(mockSession).send(Mockito.anyString(), Mockito.anyObject());
}
}

View File

@ -34,56 +34,36 @@ public class SpringBootApplicationIntegrationTest {
@Before
public void setupMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.build();
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception {
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all"))
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andExpect(MockMvcResultMatchers.content()
.contentType(contentType))
.andExpect(jsonPath("$", hasSize(4)));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4)));
}
@Test
public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception {
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30"))
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andExpect(MockMvcResultMatchers.content()
.contentType(contentType))
.andExpect(jsonPath("$.id", equalTo(1)));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType))
.andExpect(jsonPath("$.id", equalTo(1)));
}
@Test
public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception {
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name()))
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andExpect(MockMvcResultMatchers.content()
.contentType(contentType))
.andExpect(jsonPath("$.id", equalTo(1)));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$.id", equalTo(1)));
}
@Test
public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception {
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion")
.header("Version", "1.0.0"))
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andExpect(MockMvcResultMatchers.content()
.contentType(contentType))
.andExpect(jsonPath("$.id", equalTo(1)));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType))
.andExpect(jsonPath("$.id", equalTo(1)));
}
}

View File

@ -61,15 +61,11 @@ public class SpringBootMailIntegrationTest {
}
private String getMessage(WiserMessage wiserMessage) throws MessagingException, IOException {
return wiserMessage.getMimeMessage()
.getContent()
.toString()
.trim();
return wiserMessage.getMimeMessage().getContent().toString().trim();
}
private String getSubject(WiserMessage wiserMessage) throws MessagingException {
return wiserMessage.getMimeMessage()
.getSubject();
return wiserMessage.getMimeMessage().getSubject();
}
private SimpleMailMessage composeEmailMessage() {

View File

@ -33,8 +33,7 @@ public class DetailsServiceClientIntegrationTest {
@Before
public void setUp() throws Exception {
String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john"));
this.server.expect(requestTo("/john/details"))
.andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON));
this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON));
}
@Test

View File

@ -41,7 +41,7 @@ public class H2TestProfileJPAConfig {
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.domain", "org.baeldung.boot.boottest","org.baeldung.model" });
em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.domain", "org.baeldung.boot.boottest", "org.baeldung.model" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;

View File

@ -33,8 +33,7 @@ public class CustomConverterIntegrationTest {
public void whenConvertStringToEmployee_thenSuccess() {
Employee employee = conversionService.convert("1,50000.00", Employee.class);
Employee actualEmployee = new Employee(1, 50000.00);
assertThat(conversionService.convert("1,50000.00", Employee.class))
.isEqualToComparingFieldByField(actualEmployee);
assertThat(conversionService.convert("1,50000.00", Employee.class)).isEqualToComparingFieldByField(actualEmployee);
}
@Test
@ -44,11 +43,8 @@ public class CustomConverterIntegrationTest {
@Test
public void whenConvertingToBigDecimalUsingGenericConverter_thenSuccess() {
assertThat(conversionService.convert(Integer.valueOf(11), BigDecimal.class))
.isEqualTo(BigDecimal.valueOf(11.00).setScale(2, BigDecimal.ROUND_HALF_EVEN));
assertThat(conversionService.convert(Double.valueOf(25.23), BigDecimal.class))
.isEqualByComparingTo(BigDecimal.valueOf(Double.valueOf(25.23)));
assertThat(conversionService.convert("2.32", BigDecimal.class))
.isEqualTo(BigDecimal.valueOf(2.32));
assertThat(conversionService.convert(Integer.valueOf(11), BigDecimal.class)).isEqualTo(BigDecimal.valueOf(11.00).setScale(2, BigDecimal.ROUND_HALF_EVEN));
assertThat(conversionService.convert(Double.valueOf(25.23), BigDecimal.class)).isEqualByComparingTo(BigDecimal.valueOf(Double.valueOf(25.23)));
assertThat(conversionService.convert("2.32", BigDecimal.class)).isEqualTo(BigDecimal.valueOf(2.32));
}
}

View File

@ -26,10 +26,6 @@ public class StringToEmployeeConverterControllerIntegrationTest {
@Test
public void getStringToEmployeeTest() throws Exception {
mockMvc.perform(get("/string-to-employee?employee=1,2000"))
.andDo(print())
.andExpect(jsonPath("$.id", is(1)))
.andExpect(jsonPath("$.salary", is(2000.0)))
.andExpect(status().isOk());
mockMvc.perform(get("/string-to-employee?employee=1,2000")).andDo(print()).andExpect(jsonPath("$.id", is(1))).andExpect(jsonPath("$.salary", is(2000.0))).andExpect(status().isOk());
}
}

View File

@ -47,10 +47,7 @@ public class EmployeeControllerIntegrationTest {
Employee alex = new Employee("alex");
given(service.save(Mockito.anyObject())).willReturn(alex);
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON)
.content(JsonUtil.toJson(alex)))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.name", is("alex")));
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(alex))).andExpect(status().isCreated()).andExpect(jsonPath("$.name", is("alex")));
verify(service, VerificationModeFactory.times(1)).save(Mockito.anyObject());
reset(service);
}
@ -65,12 +62,8 @@ public class EmployeeControllerIntegrationTest {
given(service.getAllEmployees()).willReturn(allEmployees);
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(3)))
.andExpect(jsonPath("$[0].name", is(alex.getName())))
.andExpect(jsonPath("$[1].name", is(john.getName())))
.andExpect(jsonPath("$[2].name", is(bob.getName())));
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(3))).andExpect(jsonPath("$[0].name", is(alex.getName()))).andExpect(jsonPath("$[1].name", is(john.getName())))
.andExpect(jsonPath("$[2].name", is(bob.getName())));
verify(service, VerificationModeFactory.times(1)).getAllEmployees();
reset(service);
}

View File

@ -66,8 +66,6 @@ public class EmployeeRepositoryIntegrationTest {
List<Employee> allEmployees = employeeRepository.findAll();
assertThat(allEmployees).hasSize(3)
.extracting(Employee::getName)
.containsOnly(alex.getName(), ron.getName(), bob.getName());
assertThat(allEmployees).hasSize(3).extracting(Employee::getName).containsOnly(alex.getName(), ron.getName(), bob.getName());
}
}

View File

@ -50,12 +50,10 @@ public class EmployeeRestControllerIntegrationTest {
@Test
public void whenValidInput_thenCreateEmployee() throws IOException, Exception {
Employee bob = new Employee("bob");
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON)
.content(JsonUtil.toJson(bob)));
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(bob)));
List<Employee> found = repository.findAll();
assertThat(found).extracting(Employee::getName)
.containsOnly("bob");
assertThat(found).extracting(Employee::getName).containsOnly("bob");
}
@Test
@ -64,13 +62,8 @@ public class EmployeeRestControllerIntegrationTest {
createTestEmployee("bob");
createTestEmployee("alex");
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2))))
.andExpect(jsonPath("$[0].name", is("bob")))
.andExpect(jsonPath("$[1].name", is("alex")));
mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2))))
.andExpect(jsonPath("$[0].name", is("bob"))).andExpect(jsonPath("$[1].name", is("alex")));
}
private void createTestEmployee(String name) {

View File

@ -47,18 +47,12 @@ public class EmployeeServiceImplIntegrationTest {
List<Employee> allEmployees = Arrays.asList(john, bob, alex);
Mockito.when(employeeRepository.findByName(john.getName()))
.thenReturn(john);
Mockito.when(employeeRepository.findByName(alex.getName()))
.thenReturn(alex);
Mockito.when(employeeRepository.findByName("wrong_name"))
.thenReturn(null);
Mockito.when(employeeRepository.findById(john.getId()))
.thenReturn(john);
Mockito.when(employeeRepository.findAll())
.thenReturn(allEmployees);
Mockito.when(employeeRepository.findById(-99L))
.thenReturn(null);
Mockito.when(employeeRepository.findByName(john.getName())).thenReturn(john);
Mockito.when(employeeRepository.findByName(alex.getName())).thenReturn(alex);
Mockito.when(employeeRepository.findByName("wrong_name")).thenReturn(null);
Mockito.when(employeeRepository.findById(john.getId())).thenReturn(john);
Mockito.when(employeeRepository.findAll()).thenReturn(allEmployees);
Mockito.when(employeeRepository.findById(-99L)).thenReturn(null);
}
@Test
@ -116,26 +110,21 @@ public class EmployeeServiceImplIntegrationTest {
List<Employee> allEmployees = employeeService.getAllEmployees();
verifyFindAllEmployeesIsCalledOnce();
assertThat(allEmployees).hasSize(3)
.extracting(Employee::getName)
.contains(alex.getName(), john.getName(), bob.getName());
assertThat(allEmployees).hasSize(3).extracting(Employee::getName).contains(alex.getName(), john.getName(), bob.getName());
}
private void verifyFindByNameIsCalledOnce(String name) {
Mockito.verify(employeeRepository, VerificationModeFactory.times(1))
.findByName(name);
Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findByName(name);
Mockito.reset(employeeRepository);
}
private void verifyFindByIdIsCalledOnce() {
Mockito.verify(employeeRepository, VerificationModeFactory.times(1))
.findById(Mockito.anyLong());
Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findById(Mockito.anyLong());
Mockito.reset(employeeRepository);
}
private void verifyFindAllEmployeesIsCalledOnce() {
Mockito.verify(employeeRepository, VerificationModeFactory.times(1))
.findAll();
Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findAll();
Mockito.reset(employeeRepository);
}
}

View File

@ -23,30 +23,21 @@ public class ConfigPropertiesIntegrationTest {
@Test
public void whenListPropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertTrue("Couldn't bind list property!", properties.getDefaultRecipients()
.size() == 2);
Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", properties.getDefaultRecipients()
.size() == 2);
Assert.assertTrue("Couldn't bind list property!", properties.getDefaultRecipients().size() == 2);
Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", properties.getDefaultRecipients().size() == 2);
}
@Test
public void whenMapPropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertTrue("Couldn't bind map property!", properties.getAdditionalHeaders() != null);
Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", properties.getAdditionalHeaders()
.size() == 3);
Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", properties.getAdditionalHeaders().size() == 3);
}
@Test
public void whenObjectPropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertTrue("Couldn't bind map property!", properties.getCredentials() != null);
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials()
.getAuthMethod()
.equals("SHA1"));
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials()
.getUsername()
.equals("john"));
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials()
.getPassword()
.equals("password"));
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getAuthMethod().equals("SHA1"));
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getUsername().equals("john"));
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getPassword().equals("password"));
}
}

View File

@ -47,8 +47,7 @@ public class UserRepositoryIntegrationTest {
Optional<User> foundUser = userRepository.findOneByName(USER_NAME_ADAM);
assertThat(foundUser.isPresent(), equalTo(true));
assertThat(foundUser.get()
.getName(), equalTo(USER_NAME_ADAM));
assertThat(foundUser.get().getName(), equalTo(USER_NAME_ADAM));
}
@Test
@ -84,8 +83,7 @@ public class UserRepositoryIntegrationTest {
CompletableFuture<User> userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS);
assertThat(userByStatus.get()
.getName(), equalTo(USER_NAME_ADAM));
assertThat(userByStatus.get().getName(), equalTo(USER_NAME_ADAM));
}