formatting work

This commit is contained in:
eugenp 2017-01-29 16:06:01 +02:00
parent 034cde6e20
commit 966e53a85b
58 changed files with 932 additions and 1046 deletions

View File

@ -11,28 +11,28 @@ import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
@EnableWebMvc
@Configuration
@ComponentScan({"com.baeldung.freemarker"})
@ComponentScan({ "com.baeldung.freemarker" })
public class SpringWebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Bean
public FreeMarkerViewResolver freemarkerViewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setCache(true);
resolver.setPrefix("");
resolver.setSuffix(".ftl");
return resolver;
}
@Bean
public FreeMarkerViewResolver freemarkerViewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setCache(true);
resolver.setPrefix("");
resolver.setSuffix(".ftl");
return resolver;
}
@Bean
public FreeMarkerConfigurer freemarkerConfig() {
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/ftl/");
return freeMarkerConfigurer;
}
@Bean
public FreeMarkerConfigurer freemarkerConfig() {
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/ftl/");
return freeMarkerConfigurer;
}
}

View File

@ -4,19 +4,19 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche
public class WebConfiguration extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringWebConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringWebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
}

View File

@ -16,33 +16,31 @@ import com.baeldung.freemarker.model.Car;
@Controller
public class SpringController {
private static List<Car> carList = new ArrayList<Car>();
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
return "redirect:/cars";
}
static {
carList.add(new Car("Honda", "Civic"));
carList.add(new Car("Toyota", "Camry"));
carList.add(new Car("Nissan", "Altima"));
}
private static List<Car> carList = new ArrayList<Car>();
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
return "redirect:/cars";
}
@RequestMapping(value = "/cars", method = RequestMethod.GET)
public String init(@ModelAttribute("model") ModelMap model) {
model.addAttribute("carList", carList);
return "index";
}
static {
carList.add(new Car("Honda", "Civic"));
carList.add(new Car("Toyota", "Camry"));
carList.add(new Car("Nissan", "Altima"));
}
@RequestMapping(value = "/cars", method = RequestMethod.GET)
public String init(@ModelAttribute("model") ModelMap model) {
model.addAttribute("carList", carList);
return "index";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addCar(@ModelAttribute("car") Car car) {
if (null != car && null != car.getMake() && null != car.getModel() && !car.getMake().isEmpty() && !car.getModel().isEmpty()) {
carList.add(car);
}
return "redirect:/cars";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addCar(@ModelAttribute("car") Car car) {
if (null != car && null != car.getMake() && null != car.getModel()
&& !car.getMake().isEmpty() && !car.getModel().isEmpty()) {
carList.add(car);
}
return "redirect:/cars";
}
}

View File

@ -2,32 +2,32 @@ package com.baeldung.freemarker.model;
public class Car {
private String make;
private String model;
public Car(){
}
public Car(String make, String model) {
this.make = make;
private String make;
private String model;
public Car() {
}
public Car(String make, String model) {
this.make = make;
this.model = model;
}
public String getMake() {
return make;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public void setModel(String model) {
this.model = model;
}
}

View File

@ -19,21 +19,13 @@ public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAda
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1").password("user1Pass")
.authorities("ROLE_USER");
auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/securityNone").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
http.authorizeRequests().antMatchers("/securityNone").permitAll().anyRequest().authenticated().and().httpBasic().authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new CustomFilter(),
BasicAuthenticationFilter.class);
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
}
}

View File

@ -5,7 +5,7 @@ import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("org.baeldung.security")
//@ImportResource({ "classpath:webSecurityConfig.xml" })
// @ImportResource({ "classpath:webSecurityConfig.xml" })
public class SecSecurityConfig {
public SecSecurityConfig() {

View File

@ -9,8 +9,7 @@ import org.springframework.context.annotation.FilterType;
@Configuration
@EnableAutoConfiguration
@ComponentScan(excludeFilters =
@ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.voter.*"))
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.voter.*"))
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);

View File

@ -7,7 +7,7 @@ import org.springframework.transaction.annotation.Transactional;
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(final String username);
@Transactional
void removeUserByUsername(String username);

View File

@ -15,7 +15,7 @@ import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="user_table")
@Table(name = "user_table")
public class User {
@Id

View File

@ -21,13 +21,6 @@ public class MinuteBasedVoter implements AccessDecisionVoter {
@Override
public int vote(Authentication authentication, Object object, Collection collection) {
return authentication
.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.filter(r -> "ROLE_USER".equals(r) && LocalDateTime.now().getMinute() % 2 != 0)
.findAny()
.map(s -> ACCESS_DENIED)
.orElseGet(() -> ACCESS_ABSTAIN);
return authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).filter(r -> "ROLE_USER".equals(r) && LocalDateTime.now().getMinute() % 2 != 0).findAny().map(s -> ACCESS_DENIED).orElseGet(() -> ACCESS_ABSTAIN);
}
}

View File

@ -8,7 +8,7 @@ import org.springframework.context.annotation.FilterType;
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {"org.baeldung.voter"})
@ComponentScan(basePackages = { "org.baeldung.voter" })
public class VoterApplication {
public static void main(String[] args) {

View File

@ -24,10 +24,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter: off
auth.inMemoryAuthentication()
.withUser("user").password("pass").roles("USER")
.and()
.withUser("admin").password("pass").roles("ADMIN");
auth.inMemoryAuthentication().withUser("user").password("pass").roles("USER").and().withUser("admin").password("pass").roles("ADMIN");
// @formatter: on
}
@ -36,33 +33,15 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// @formatter: off
http
// needed so our login could work
.csrf()
.disable()
.authorizeRequests()
.anyRequest()
.authenticated()
.accessDecisionManager(accessDecisionManager())
.antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER")
.and()
.formLogin()
.permitAll()
.and()
.logout()
.permitAll()
.deleteCookies("JSESSIONID")
.logoutSuccessUrl("/login");
.csrf().disable().authorizeRequests().anyRequest().authenticated().accessDecisionManager(accessDecisionManager()).antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER").and().formLogin().permitAll().and().logout().permitAll()
.deleteCookies("JSESSIONID").logoutSuccessUrl("/login");
// @formatter: on
}
@Bean
public AccessDecisionManager accessDecisionManager() {
// @formatter: off
List<AccessDecisionVoter<? extends Object>> decisionVoters =
Arrays.asList(
new WebExpressionVoter(),
new RoleVoter(),
new AuthenticatedVoter(),
new MinuteBasedVoter());
List<AccessDecisionVoter<? extends Object>> decisionVoters = Arrays.asList(new WebExpressionVoter(), new RoleVoter(), new AuthenticatedVoter(), new MinuteBasedVoter());
// @formatter: on
return new UnanimousBased(decisionVoters);
}

View File

@ -7,7 +7,7 @@ import org.springframework.context.annotation.ImportResource;
* Created by ambrusadrianz on 09/10/2016.
*/
@Configuration
@ImportResource({"classpath:spring-security.xml"})
@ImportResource({ "classpath:spring-security.xml" })
public class XmlSecurityConfig {
public XmlSecurityConfig() {
super();

View File

@ -15,6 +15,7 @@ public class MyUserLiveTest {
private final MyUser userJohn = new MyUser("john", "doe", "john@doe.com", 11);
private String URL_PREFIX = "http://localhost:8082/spring-security-rest-full/auth/api/myusers";
@Test
public void whenGettingListOfUsers_thenCorrect() {
final Response response = givenAuth().get(URL_PREFIX);

View File

@ -16,11 +16,11 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationFa
@ComponentScan("org.baeldung.security")
public class SecurityJavaConfig extends WebSecurityConfigurerAdapter {
// @Autowired
// private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
// @Autowired
// private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
// @Autowired
// private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
// @Autowired
// private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
public SecurityJavaConfig() {
super();

View File

@ -20,7 +20,7 @@ public class WebConfig extends WebMvcConfigurerAdapter {
public WebConfig() {
super();
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");

View File

@ -14,26 +14,24 @@ import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class AsyncController {
private static final Logger log = Logger.getLogger(AsyncService.class);
private static final Logger log = Logger.getLogger(AsyncService.class);
@Autowired
private AsyncService asyncService;
@Autowired
private AsyncService asyncService;
@RequestMapping(method = RequestMethod.GET, value = "/async")
@ResponseBody
public Object standardProcessing() throws Exception {
log.info("Outside the @Async logic - before the async call: "
+ SecurityContextHolder.getContext().getAuthentication().getPrincipal());
asyncService.asyncCall();
log.info("Inside the @Async logic - after the async call: "
+ SecurityContextHolder.getContext().getAuthentication().getPrincipal());
return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
@RequestMapping(method = RequestMethod.GET, value = "/async2")
@ResponseBody
public Callable<Boolean> springMVCAsyncTest() {
return asyncService.checkIfPrincipalPropagated();
}
@RequestMapping(method = RequestMethod.GET, value = "/async")
@ResponseBody
public Object standardProcessing() throws Exception {
log.info("Outside the @Async logic - before the async call: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
asyncService.asyncCall();
log.info("Inside the @Async logic - after the async call: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
@RequestMapping(method = RequestMethod.GET, value = "/async2")
@ResponseBody
public Callable<Boolean> springMVCAsyncTest() {
return asyncService.checkIfPrincipalPropagated();
}
}

View File

@ -3,9 +3,9 @@ package org.baeldung.web.service;
import java.util.concurrent.Callable;
public interface AsyncService {
void asyncCall();
Callable<Boolean> checkIfPrincipalPropagated();
void asyncCall();
Callable<Boolean> checkIfPrincipalPropagated();
}

View File

@ -10,27 +10,25 @@ import org.springframework.stereotype.Service;
@Service
public class AsyncServiceImpl implements AsyncService {
private static final Logger log = Logger.getLogger(AsyncService.class);
private static final Logger log = Logger.getLogger(AsyncService.class);
@Async
@Override
public void asyncCall() {
log.info("Inside the @Async logic: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
}
@Async
@Override
public void asyncCall() {
log.info("Inside the @Async logic: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
}
@Override
public Callable<Boolean> checkIfPrincipalPropagated() {
Object before
= SecurityContextHolder.getContext().getAuthentication().getPrincipal();
log.info("Before new thread: " + before);
@Override
public Callable<Boolean> checkIfPrincipalPropagated() {
Object before = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
log.info("Before new thread: " + before);
return new Callable<Boolean>() {
public Boolean call() throws Exception {
Object after
= SecurityContextHolder.getContext().getAuthentication().getPrincipal();
log.info("New thread: " + after);
return before == after;
}
};
}
return new Callable<Boolean>() {
public Boolean call() throws Exception {
Object after = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
log.info("New thread: " + after);
return before == after;
}
};
}
}

View File

@ -22,27 +22,27 @@ import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class})
@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class })
public class AsyncControllerTest {
@Autowired
WebApplicationContext wac;
@Autowired
MockHttpSession session;
@Mock
AsyncController controller;
@Autowired
WebApplicationContext wac;
@Autowired
MockHttpSession session;
private MockMvc mockMvc;
@Mock
AsyncController controller;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
private MockMvc mockMvc;
@Test
public void testAsync() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/async")).andExpect(status().is5xxServerError());
}
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void testAsync() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/async")).andExpect(status().is5xxServerError());
}
}

View File

@ -10,10 +10,10 @@ import org.springframework.web.multipart.commons.CommonsMultipartResolver;
@ComponentScan({ "org.baeldung.web" })
public class TestConfig {
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
return multipartResolver;
}
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
return multipartResolver;
}
}

View File

@ -13,17 +13,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("password").roles("ADMIN");
auth.inMemoryAuthentication().withUser("admin").password("password").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().and()
.authorizeRequests()
.antMatchers("/").hasRole("ADMIN")
.anyRequest().authenticated();
http.httpBasic().and().authorizeRequests().antMatchers("/").hasRole("ADMIN").anyRequest().authenticated();
}
}

View File

@ -42,10 +42,10 @@ public class SessionControllerTest {
@Test
public void testRedisControlsSession() {
ResponseEntity<String> result = testRestTemplateWithAuth.getForEntity(testUrl, String.class);
assertEquals("hello admin", result.getBody()); //login worked
assertEquals("hello admin", result.getBody()); // login worked
Set<String> redisResult = jedis.keys("*");
assertTrue(redisResult.size() > 0); //redis is populated with session data
assertTrue(redisResult.size() > 0); // redis is populated with session data
String sessionCookie = result.getHeaders().get("Set-Cookie").get(0).split(";")[0];
HttpHeaders headers = new HttpHeaders();
@ -53,12 +53,12 @@ public class SessionControllerTest {
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
result = testRestTemplate.exchange(testUrl, HttpMethod.GET, httpEntity, String.class);
assertEquals("hello admin", result.getBody()); //access with session works worked
assertEquals("hello admin", result.getBody()); // access with session works worked
jedis.flushAll(); //clear all keys in redis
jedis.flushAll(); // clear all keys in redis
result = testRestTemplate.exchange(testUrl, HttpMethod.GET, httpEntity, String.class);
assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());//access denied after sessions are removed in redis
assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());// access denied after sessions are removed in redis
}
}

View File

@ -18,7 +18,7 @@ import java.util.concurrent.Executors;
@Configuration
@EnableAsync
@EnableScheduling
public class ThreadConfig extends AsyncConfigurerSupport implements SchedulingConfigurer{
public class ThreadConfig extends AsyncConfigurerSupport implements SchedulingConfigurer {
@Autowired
private BeanFactory beanFactory;

View File

@ -47,71 +47,71 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application
this.applicationContext = applicationContext;
}
@Bean
public ViewResolver htmlViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine(htmlTemplateResolver()));
resolver.setContentType("text/html");
resolver.setCharacterEncoding("UTF-8");
resolver.setViewNames(ArrayUtil.array("*.html"));
return resolver;
}
@Bean
public ViewResolver htmlViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine(htmlTemplateResolver()));
resolver.setContentType("text/html");
resolver.setCharacterEncoding("UTF-8");
resolver.setViewNames(ArrayUtil.array("*.html"));
return resolver;
}
@Bean
public ViewResolver javascriptViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine(javascriptTemplateResolver()));
resolver.setContentType("application/javascript");
resolver.setCharacterEncoding("UTF-8");
resolver.setViewNames(ArrayUtil.array("*.js"));
return resolver;
}
@Bean
public ViewResolver javascriptViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine(javascriptTemplateResolver()));
resolver.setContentType("application/javascript");
resolver.setCharacterEncoding("UTF-8");
resolver.setViewNames(ArrayUtil.array("*.js"));
return resolver;
}
@Bean
public ViewResolver plainViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine(plainTemplateResolver()));
resolver.setContentType("text/plain");
resolver.setCharacterEncoding("UTF-8");
resolver.setViewNames(ArrayUtil.array("*.txt"));
return resolver;
}
@Bean
public ViewResolver plainViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine(plainTemplateResolver()));
resolver.setContentType("text/plain");
resolver.setCharacterEncoding("UTF-8");
resolver.setViewNames(ArrayUtil.array("*.txt"));
return resolver;
}
private TemplateEngine templateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.addDialect(new LayoutDialect(new GroupingStrategy()));
engine.addDialect(new Java8TimeDialect());
engine.setTemplateResolver(templateResolver);
engine.setTemplateEngineMessageSource(messageSource());
return engine;
}
private TemplateEngine templateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.addDialect(new LayoutDialect(new GroupingStrategy()));
engine.addDialect(new Java8TimeDialect());
engine.setTemplateResolver(templateResolver);
engine.setTemplateEngineMessageSource(messageSource());
return engine;
}
private ITemplateResolver htmlTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/views/");
resolver.setCacheable(false);
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
private ITemplateResolver htmlTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/views/");
resolver.setCacheable(false);
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
private ITemplateResolver javascriptTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/js/");
resolver.setCacheable(false);
resolver.setTemplateMode(TemplateMode.JAVASCRIPT);
return resolver;
}
private ITemplateResolver javascriptTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/js/");
resolver.setCacheable(false);
resolver.setTemplateMode(TemplateMode.JAVASCRIPT);
return resolver;
}
private ITemplateResolver plainTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/txt/");
resolver.setCacheable(false);
resolver.setTemplateMode(TemplateMode.TEXT);
return resolver;
}
private ITemplateResolver plainTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/txt/");
resolver.setCacheable(false);
resolver.setTemplateMode(TemplateMode.TEXT);
return resolver;
}
@Bean
@Description("Spring Message Resolver")
@ -121,7 +121,7 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application
return messageSource;
}
@Bean
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(new Locale("en"));
@ -140,12 +140,12 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application
registry.addInterceptor(localeChangeInterceptor());
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/");
}
@Override
@Override
@Description("Custom Conversion Service")
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new NameFormatter());

View File

@ -13,13 +13,13 @@ import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class DatesController {
@RequestMapping(value = "/dates", method = RequestMethod.GET)
public String getInfo(Model model) {
model.addAttribute("standardDate", new Date());
model.addAttribute("localDateTime", LocalDateTime.now());
model.addAttribute("localDate", LocalDate.now());
model.addAttribute("timestamp", Instant.now());
return "dates.html";
}
@RequestMapping(value = "/dates", method = RequestMethod.GET)
public String getInfo(Model model) {
model.addAttribute("standardDate", new Date());
model.addAttribute("localDateTime", LocalDateTime.now());
model.addAttribute("localDate", LocalDate.now());
model.addAttribute("timestamp", Instant.now());
return "dates.html";
}
}

View File

@ -31,24 +31,24 @@ import com.baeldung.thymeleaf.config.WebMVCSecurity;
@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class })
public class ExpressionUtilityObjectsControllerIntegrationTest {
@Autowired
WebApplicationContext wac;
@Autowired
MockHttpSession session;
@Autowired
WebApplicationContext wac;
@Autowired
MockHttpSession session;
private MockMvc mockMvc;
private MockMvc mockMvc;
@Autowired
private Filter springSecurityFilterChain;
@Autowired
private Filter springSecurityFilterChain;
protected RequestPostProcessor testUser() {
return user("user1").password("user1Pass").roles("USER");
}
protected RequestPostProcessor testUser() {
return user("user1").password("user1Pass").roles("USER");
}
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
}
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
}
@Test
public void testGetObjects() throws Exception {

View File

@ -25,8 +25,7 @@ public class UserController {
myUserService.registerNewUserAccount(accountDto);
model.addAttribute("message", "Registration successful");
return "index";
}
catch(final Exception exc){
} catch (final Exception exc) {
model.addAttribute("message", "Registration failed");
return "index";

View File

@ -29,7 +29,7 @@ public class MyUserDAO {
entityManager.persist(user);
return user;
}
public void removeUserByUsername(String username) {
final Query query = entityManager.createQuery("delete from MyUser where username=:username");
query.setParameter("username", username);

View File

@ -33,8 +33,8 @@ public class MyUserService {
final MyUser user = myUserDAO.findByUsername(username);
return user;
}
public void removeUserByUsername(String username){
public void removeUserByUsername(String username) {
myUserDAO.removeUserByUsername(username);
}

View File

@ -17,7 +17,7 @@ public class MyUserDto {
public void setUsername(final String username) {
this.username = username;
}
public String getPassword() {
return password;
}

View File

@ -59,8 +59,8 @@ public class CustomUserDetailsServiceIntegrationTest {
myUserService.removeUserByUsername(USERNAME);
}
}
@Test (expected = BadCredentialsException.class)
@Test(expected = BadCredentialsException.class)
public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() {
try {
MyUserDto userDTO = new MyUserDto();
@ -69,15 +69,13 @@ public class CustomUserDetailsServiceIntegrationTest {
try {
myUserService.registerNewUserAccount(userDTO);
}
catch (Exception exc) {
} catch (Exception exc) {
LOG.log(Level.SEVERE, "Error creating account");
}
}
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD);
Authentication authentication = authenticationProvider.authenticate(auth);
}
finally {
} finally {
myUserService.removeUserByUsername(USERNAME);
}
}

View File

@ -20,7 +20,7 @@ import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DefaultParser {
private File file;
public DefaultParser(File file) {
@ -69,7 +69,7 @@ public class DefaultParser {
}
return node;
}
public NodeList getNodeListByTitle(String name) {
NodeList nodeList = null;
try {
@ -125,11 +125,11 @@ public class DefaultParser {
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(this.getFile());
this.clean(xmlDocument);
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setNamespaceContext(new NamespaceContext() {
@Override

View File

@ -17,115 +17,114 @@ import org.dom4j.io.XMLWriter;
public class Dom4JParser {
private File file;
private File file;
public Dom4JParser(File file) {
this.file = file;
}
public Dom4JParser(File file) {
this.file = file;
}
public Element getRootElement() {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
return document.getRootElement();
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
}
public Element getRootElement() {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
return document.getRootElement();
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
}
public List<Element> getFirstElementList() {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
return document.getRootElement().elements();
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
}
public List<Element> getFirstElementList() {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
return document.getRootElement().elements();
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
}
public Node getNodeById(String id) {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
List<Node> elements = document.selectNodes("//*[@tutId='" + id + "']");
return elements.get(0);
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
}
public Node getNodeById(String id) {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
List<Node> elements = document.selectNodes("//*[@tutId='" + id + "']");
return elements.get(0);
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
}
public Node getElementsListByTitle(String name) {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
List<Node> elements = document
.selectNodes("//tutorial[descendant::title[text()=" + "'" + name + "'" + "]]");
return elements.get(0);
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
}
public Node getElementsListByTitle(String name) {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
List<Node> elements = document.selectNodes("//tutorial[descendant::title[text()=" + "'" + name + "'" + "]]");
return elements.get(0);
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
}
public void generateModifiedDocument() {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
List<Node> nodes = document.selectNodes("/tutorials/tutorial");
for (Node node : nodes) {
Element element = (Element) node;
Iterator<Element> iterator = element.elementIterator("title");
while (iterator.hasNext()) {
Element title = (Element) iterator.next();
title.setText(title.getText() + " updated");
}
}
XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_updated.xml")));
writer.write(document);
writer.close();
} catch (DocumentException e) {
e.printStackTrace();
public void generateModifiedDocument() {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
List<Node> nodes = document.selectNodes("/tutorials/tutorial");
for (Node node : nodes) {
Element element = (Element) node;
Iterator<Element> iterator = element.elementIterator("title");
while (iterator.hasNext()) {
Element title = (Element) iterator.next();
title.setText(title.getText() + " updated");
}
}
XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_updated.xml")));
writer.write(document);
writer.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void generateNewDocument() {
try {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("XMLTutorials");
Element tutorialElement = root.addElement("tutorial").addAttribute("tutId", "01");
tutorialElement.addAttribute("type", "xml");
public void generateNewDocument() {
try {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("XMLTutorials");
Element tutorialElement = root.addElement("tutorial").addAttribute("tutId", "01");
tutorialElement.addAttribute("type", "xml");
tutorialElement.addElement("title").addText("XML with Dom4J");
tutorialElement.addElement("title").addText("XML with Dom4J");
tutorialElement.addElement("description").addText("XML handling with Dom4J");
tutorialElement.addElement("description").addText("XML handling with Dom4J");
tutorialElement.addElement("date").addText("14/06/2016");
tutorialElement.addElement("date").addText("14/06/2016");
tutorialElement.addElement("author").addText("Dom4J tech writer");
tutorialElement.addElement("author").addText("Dom4J tech writer");
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_new.xml")), format);
writer.write(document);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_new.xml")), format);
writer.write(document);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public File getFile() {
return file;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public void setFile(File file) {
this.file = file;
}
}

View File

@ -12,51 +12,50 @@ import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
public class JDomParser {
private File file;
private File file;
public JDomParser(File file) {
this.file = file;
}
public JDomParser(File file) {
this.file = file;
}
public List<Element> getAllTitles() {
try {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(this.getFile());
Element tutorials = doc.getRootElement();
List<Element> titles = tutorials.getChildren("tutorial");
return titles;
} catch (JDOMException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public Element getNodeById(String id) {
try {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(file);
String filter = "//*[@tutId='" + id + "']";
XPathFactory xFactory = XPathFactory.instance();
XPathExpression<Element> expr = xFactory.compile(filter, Filters.element());
List<Element> node = expr.evaluate(document);
return node.get(0);
} catch (JDOMException | IOException e ) {
e.printStackTrace();
return null;
}
}
public List<Element> getAllTitles() {
try {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(this.getFile());
Element tutorials = doc.getRootElement();
List<Element> titles = tutorials.getChildren("tutorial");
return titles;
} catch (JDOMException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public File getFile() {
return file;
}
public Element getNodeById(String id) {
try {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(file);
String filter = "//*[@tutId='" + id + "']";
XPathFactory xFactory = XPathFactory.instance();
XPathExpression<Element> expr = xFactory.compile(filter, Filters.element());
List<Element> node = expr.evaluate(document);
public void setFile(File file) {
this.file = file;
}
return node.get(0);
} catch (JDOMException | IOException e) {
e.printStackTrace();
return null;
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}

View File

@ -13,56 +13,56 @@ import com.baeldung.xml.binding.Tutorials;
public class JaxbParser {
private File file;
private File file;
public JaxbParser(File file) {
this.file = file;
}
public JaxbParser(File file) {
this.file = file;
}
public Tutorials getFullDocument() {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Tutorials tutorials = (Tutorials) jaxbUnmarshaller.unmarshal(this.getFile());
return tutorials;
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
public Tutorials getFullDocument() {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Tutorials tutorials = (Tutorials) jaxbUnmarshaller.unmarshal(this.getFile());
return tutorials;
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
public void createNewDocument() {
Tutorials tutorials = new Tutorials();
tutorials.setTutorial(new ArrayList<Tutorial>());
Tutorial tut = new Tutorial();
tut.setTutId("01");
tut.setType("XML");
tut.setTitle("XML with Jaxb");
tut.setDescription("XML Binding with Jaxb");
tut.setDate("04/02/2015");
tut.setAuthor("Jaxb author");
tutorials.getTutorial().add(tut);
public void createNewDocument() {
Tutorials tutorials = new Tutorials();
tutorials.setTutorial(new ArrayList<Tutorial>());
Tutorial tut = new Tutorial();
tut.setTutId("01");
tut.setType("XML");
tut.setTitle("XML with Jaxb");
tut.setDescription("XML Binding with Jaxb");
tut.setDate("04/02/2015");
tut.setAuthor("Jaxb author");
tutorials.getTutorial().add(tut);
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(tutorials, file);
jaxbMarshaller.marshal(tutorials, file);
} catch (JAXBException e) {
e.printStackTrace();
}
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
public File getFile() {
return file;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public void setFile(File file) {
this.file = file;
}
}

View File

@ -17,13 +17,13 @@ import org.xml.sax.SAXException;
public class JaxenDemo {
private File file;
private File file;
public JaxenDemo(File file) {
this.file = file;
}
public List getAllTutorial(){
public JaxenDemo(File file) {
this.file = file;
}
public List getAllTutorial() {
try {
FileInputStream fileIS = new FileInputStream(this.getFile());
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
@ -33,25 +33,24 @@ public class JaxenDemo {
Document xmlDocument = builder.parse(fileIS);
String expression = "/tutorials/tutorial";
XPath path = new DOMXPath(expression);
List result = path.selectNodes(xmlDocument);
return result;
} catch (SAXException | IOException | ParserConfigurationException | JaxenException e) {
e.printStackTrace();
return null;
}
}
public File getFile() {
return file;
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public void setFile(File file) {
this.file = file;
}
}

View File

@ -21,100 +21,100 @@ import com.baeldung.xml.binding.Tutorial;
public class StaxParser {
private File file;
private File file;
public StaxParser(File file) {
this.file = file;
}
public StaxParser(File file) {
this.file = file;
}
public List<Tutorial> getAllTutorial() {
boolean bTitle = false;
boolean bDescription = false;
boolean bDate = false;
boolean bAuthor = false;
List<Tutorial> tutorials = new ArrayList<Tutorial>();
try {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(this.getFile()));
Tutorial current = null;
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
switch (event.getEventType()) {
case XMLStreamConstants.START_ELEMENT:
StartElement startElement = event.asStartElement();
String qName = startElement.getName().getLocalPart();
if (qName.equalsIgnoreCase("tutorial")) {
current = new Tutorial();
Iterator<Attribute> attributes = startElement.getAttributes();
while (attributes.hasNext()) {
Attribute currentAt = attributes.next();
if (currentAt.getName().toString().equalsIgnoreCase("tutId")) {
current.setTutId(currentAt.getValue());
} else if (currentAt.getName().toString().equalsIgnoreCase("type")) {
current.setType(currentAt.getValue());
}
}
} else if (qName.equalsIgnoreCase("title")) {
bTitle = true;
} else if (qName.equalsIgnoreCase("description")) {
bDescription = true;
} else if (qName.equalsIgnoreCase("date")) {
bDate = true;
} else if (qName.equalsIgnoreCase("author")) {
bAuthor = true;
}
break;
case XMLStreamConstants.CHARACTERS:
Characters characters = event.asCharacters();
if (bTitle) {
if (current != null) {
current.setTitle(characters.getData());
}
bTitle = false;
}
if (bDescription) {
if (current != null) {
current.setDescription(characters.getData());
}
bDescription = false;
}
if (bDate) {
if (current != null) {
current.setDate(characters.getData());
}
bDate = false;
}
if (bAuthor) {
if (current != null) {
current.setAuthor(characters.getData());
}
bAuthor = false;
}
break;
case XMLStreamConstants.END_ELEMENT:
EndElement endElement = event.asEndElement();
if (endElement.getName().getLocalPart().equalsIgnoreCase("tutorial")) {
if(current != null){
tutorials.add(current);
}
}
break;
}
}
public List<Tutorial> getAllTutorial() {
boolean bTitle = false;
boolean bDescription = false;
boolean bDate = false;
boolean bAuthor = false;
List<Tutorial> tutorials = new ArrayList<Tutorial>();
try {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(this.getFile()));
Tutorial current = null;
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
switch (event.getEventType()) {
case XMLStreamConstants.START_ELEMENT:
StartElement startElement = event.asStartElement();
String qName = startElement.getName().getLocalPart();
if (qName.equalsIgnoreCase("tutorial")) {
current = new Tutorial();
Iterator<Attribute> attributes = startElement.getAttributes();
while (attributes.hasNext()) {
Attribute currentAt = attributes.next();
if (currentAt.getName().toString().equalsIgnoreCase("tutId")) {
current.setTutId(currentAt.getValue());
} else if (currentAt.getName().toString().equalsIgnoreCase("type")) {
current.setType(currentAt.getValue());
}
}
} else if (qName.equalsIgnoreCase("title")) {
bTitle = true;
} else if (qName.equalsIgnoreCase("description")) {
bDescription = true;
} else if (qName.equalsIgnoreCase("date")) {
bDate = true;
} else if (qName.equalsIgnoreCase("author")) {
bAuthor = true;
}
break;
case XMLStreamConstants.CHARACTERS:
Characters characters = event.asCharacters();
if (bTitle) {
if (current != null) {
current.setTitle(characters.getData());
}
bTitle = false;
}
if (bDescription) {
if (current != null) {
current.setDescription(characters.getData());
}
bDescription = false;
}
if (bDate) {
if (current != null) {
current.setDate(characters.getData());
}
bDate = false;
}
if (bAuthor) {
if (current != null) {
current.setAuthor(characters.getData());
}
bAuthor = false;
}
break;
case XMLStreamConstants.END_ELEMENT:
EndElement endElement = event.asEndElement();
if (endElement.getName().getLocalPart().equalsIgnoreCase("tutorial")) {
if (current != null) {
tutorials.add(current);
}
}
break;
}
}
} catch (FileNotFoundException | XMLStreamException e) {
e.printStackTrace();
}
} catch (FileNotFoundException | XMLStreamException e) {
e.printStackTrace();
}
return tutorials;
}
return tutorials;
}
public File getFile() {
return file;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public void setFile(File file) {
this.file = file;
}
}

View File

@ -5,55 +5,64 @@ import javax.xml.bind.annotation.XmlElement;
public class Tutorial {
private String tutId;
private String type;
private String title;
private String description;
private String date;
private String author;
public String getTutId() {
return tutId;
}
@XmlAttribute
public void setTutId(String tutId) {
this.tutId = tutId;
}
public String getType() {
return type;
}
@XmlAttribute
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
@XmlElement
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
@XmlElement
public void setDescription(String description) {
this.description = description;
}
public String getDate() {
return date;
}
@XmlElement
public void setDate(String date) {
this.date = date;
}
public String getAuthor() {
return author;
}
@XmlElement
public void setAuthor(String author) {
this.author = author;
}
private String tutId;
private String type;
private String title;
private String description;
private String date;
private String author;
public String getTutId() {
return tutId;
}
@XmlAttribute
public void setTutId(String tutId) {
this.tutId = tutId;
}
public String getType() {
return type;
}
@XmlAttribute
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
@XmlElement
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
@XmlElement
public void setDescription(String description) {
this.description = description;
}
public String getDate() {
return date;
}
@XmlElement
public void setDate(String date) {
this.date = date;
}
public String getAuthor() {
return author;
}
@XmlElement
public void setAuthor(String author) {
this.author = author;
}
}

View File

@ -8,16 +8,15 @@ import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Tutorials {
private List<Tutorial> tutorial;
private List<Tutorial> tutorial;
public List<Tutorial> getTutorial() {
return tutorial;
}
@XmlElement
public void setTutorial(List<Tutorial> tutorial) {
this.tutorial = tutorial;
}
public List<Tutorial> getTutorial() {
return tutorial;
}
@XmlElement
public void setTutorial(List<Tutorial> tutorial) {
this.tutorial = tutorial;
}
}

View File

@ -11,7 +11,7 @@ import org.w3c.dom.NodeList;
public class DefaultParserUnitTest {
final String fileName = "src/test/resources/example.xml";
final String fileNameSpace = "src/test/resources/example_namespace.xml";
DefaultParser parser;
@ -51,9 +51,9 @@ public class DefaultParserUnitTest {
String type = node.getAttributes().getNamedItem("type").getNodeValue();
assertEquals("android", type);
}
@Test
public void getNodeListByDateTest(){
public void getNodeListByDateTest() {
parser = new DefaultParser(new File(fileName));
NodeList list = parser.getNodeListByTitle("04022016");
for (int i = 0; null != list && i < list.getLength(); i++) {
@ -68,9 +68,9 @@ public class DefaultParserUnitTest {
assertEquals("SpringAuthor", nod.getLastChild().getTextContent());
}
}
@Test
public void getNodeListWithNamespaceTest(){
public void getNodeListWithNamespaceTest() {
parser = new DefaultParser(new File(fileNameSpace));
NodeList list = parser.getAllTutorials();
assertNotNull(list);

View File

@ -13,76 +13,76 @@ import org.junit.Test;
public class Dom4JParserUnitTest {
final String fileName = "src/test/resources/example.xml";
final String fileName = "src/test/resources/example.xml";
Dom4JParser parser;
Dom4JParser parser;
@Test
public void getRootElementTest() {
parser = new Dom4JParser(new File(fileName));
Element root = parser.getRootElement();
@Test
public void getRootElementTest() {
parser = new Dom4JParser(new File(fileName));
Element root = parser.getRootElement();
assertNotNull(root);
assertTrue(root.elements().size() == 4);
}
assertNotNull(root);
assertTrue(root.elements().size() == 4);
}
@Test
public void getFirstElementListTest() {
parser = new Dom4JParser(new File(fileName));
List<Element> firstList = parser.getFirstElementList();
@Test
public void getFirstElementListTest() {
parser = new Dom4JParser(new File(fileName));
List<Element> firstList = parser.getFirstElementList();
assertNotNull(firstList);
assertTrue(firstList.size() == 4);
assertTrue(firstList.get(0).attributeValue("type").equals("java"));
}
assertNotNull(firstList);
assertTrue(firstList.size() == 4);
assertTrue(firstList.get(0).attributeValue("type").equals("java"));
}
@Test
public void getElementByIdTest() {
parser = new Dom4JParser(new File(fileName));
Node element = parser.getNodeById("03");
@Test
public void getElementByIdTest() {
parser = new Dom4JParser(new File(fileName));
Node element = parser.getNodeById("03");
String type = element.valueOf("@type");
assertEquals("android", type);
}
String type = element.valueOf("@type");
assertEquals("android", type);
}
@Test
public void getElementsListByTitleTest() {
parser = new Dom4JParser(new File(fileName));
Node element = parser.getElementsListByTitle("XML");
@Test
public void getElementsListByTitleTest() {
parser = new Dom4JParser(new File(fileName));
Node element = parser.getElementsListByTitle("XML");
assertEquals("java", element.valueOf("@type"));
assertEquals("02", element.valueOf("@tutId"));
assertEquals("XML", element.selectSingleNode("title").getText());
assertEquals("title", element.selectSingleNode("title").getName());
}
assertEquals("java", element.valueOf("@type"));
assertEquals("02", element.valueOf("@tutId"));
assertEquals("XML", element.selectSingleNode("title").getText());
assertEquals("title", element.selectSingleNode("title").getName());
}
@Test
public void generateModifiedDocumentTest() {
parser = new Dom4JParser(new File(fileName));
parser.generateModifiedDocument();
@Test
public void generateModifiedDocumentTest() {
parser = new Dom4JParser(new File(fileName));
parser.generateModifiedDocument();
File generatedFile = new File("src/test/resources/example_updated.xml");
assertTrue(generatedFile.exists());
File generatedFile = new File("src/test/resources/example_updated.xml");
assertTrue(generatedFile.exists());
parser.setFile(generatedFile);
Node element = parser.getNodeById("02");
parser.setFile(generatedFile);
Node element = parser.getNodeById("02");
assertEquals("XML updated", element.selectSingleNode("title").getText());
assertEquals("XML updated", element.selectSingleNode("title").getText());
}
@Test
public void generateNewDocumentTest() {
parser = new Dom4JParser(new File(fileName));
parser.generateNewDocument();
}
File newFile = new File("src/test/resources/example_new.xml");
assertTrue(newFile.exists());
@Test
public void generateNewDocumentTest() {
parser = new Dom4JParser(new File(fileName));
parser.generateNewDocument();
parser.setFile(newFile);
Node element = parser.getNodeById("01");
File newFile = new File("src/test/resources/example_new.xml");
assertTrue(newFile.exists());
assertEquals("XML with Dom4J", element.selectSingleNode("title").getText());
parser.setFile(newFile);
Node element = parser.getNodeById("01");
}
assertEquals("XML with Dom4J", element.selectSingleNode("title").getText());
}
}

View File

@ -11,28 +11,28 @@ import org.jdom2.Element;
import org.junit.Test;
public class JDomParserUnitTest {
final String fileName = "src/test/resources/example.xml";
JDomParser parser;
@Test
public void getFirstElementListTest() {
parser = new JDomParser(new File(fileName));
List<Element> firstList = parser.getAllTitles();
final String fileName = "src/test/resources/example.xml";
JDomParser parser;
@Test
public void getFirstElementListTest() {
parser = new JDomParser(new File(fileName));
List<Element> firstList = parser.getAllTitles();
assertNotNull(firstList);
assertTrue(firstList.size() == 4);
assertTrue(firstList.get(0).getAttributeValue("type").equals("java"));
}
@Test
public void getElementByIdTest() {
parser = new JDomParser(new File(fileName));
Element el = parser.getNodeById("03");
String type = el.getAttributeValue("type");
assertEquals("android", type);
}
assertNotNull(firstList);
assertTrue(firstList.size() == 4);
assertTrue(firstList.get(0).getAttributeValue("type").equals("java"));
}
@Test
public void getElementByIdTest() {
parser = new JDomParser(new File(fileName));
Element el = parser.getNodeById("03");
String type = el.getAttributeValue("type");
assertEquals("android", type);
}
}

View File

@ -11,34 +11,32 @@ import com.baeldung.xml.binding.Tutorials;
public class JaxbParserUnitTest {
final String fileName = "src/test/resources/example.xml";
final String fileName = "src/test/resources/example.xml";
JaxbParser parser;
@Test
public void getFullDocumentTest(){
parser = new JaxbParser(new File(fileName));
Tutorials tutorials = parser.getFullDocument();
JaxbParser parser;
assertNotNull(tutorials);
assertTrue(tutorials.getTutorial().size() == 4);
assertTrue(tutorials.getTutorial().get(0).getType().equalsIgnoreCase("java"));
}
@Test
public void createNewDocumentTest(){
File newFile = new File("src/test/resources/example_new.xml");
parser = new JaxbParser(newFile);
parser.createNewDocument();
@Test
public void getFullDocumentTest() {
parser = new JaxbParser(new File(fileName));
Tutorials tutorials = parser.getFullDocument();
assertTrue(newFile.exists());
assertNotNull(tutorials);
assertTrue(tutorials.getTutorial().size() == 4);
assertTrue(tutorials.getTutorial().get(0).getType().equalsIgnoreCase("java"));
}
Tutorials tutorials = parser.getFullDocument();
@Test
public void createNewDocumentTest() {
File newFile = new File("src/test/resources/example_new.xml");
parser = new JaxbParser(newFile);
parser.createNewDocument();
assertNotNull(tutorials);
assertTrue(tutorials.getTutorial().size() == 1);
assertTrue(tutorials.getTutorial().get(0).getTitle().equalsIgnoreCase("XML with Jaxb"));
}
assertTrue(newFile.exists());
Tutorials tutorials = parser.getFullDocument();
assertNotNull(tutorials);
assertTrue(tutorials.getTutorial().size() == 1);
assertTrue(tutorials.getTutorial().get(0).getTitle().equalsIgnoreCase("XML with Jaxb"));
}
}

View File

@ -10,13 +10,13 @@ import org.junit.Test;
public class JaxenDemoUnitTest {
final String fileName = "src/test/resources/example.xml";
JaxenDemo jaxenDemo;
@Test
final String fileName = "src/test/resources/example.xml";
JaxenDemo jaxenDemo;
@Test
public void getFirstLevelNodeListTest() {
jaxenDemo = new JaxenDemo(new File(fileName));
jaxenDemo = new JaxenDemo(new File(fileName));
List<?> list = jaxenDemo.getAllTutorial();
assertNotNull(list);

View File

@ -12,17 +12,17 @@ import com.baeldung.xml.binding.Tutorial;
public class StaxParserUnitTest {
final String fileName = "src/test/resources/example.xml";
final String fileName = "src/test/resources/example.xml";
StaxParser parser;
@Test
public void getAllTutorialsTest(){
parser = new StaxParser(new File(fileName));
List<Tutorial> tutorials = parser.getAllTutorial();
assertNotNull(tutorials);
assertTrue(tutorials.size() == 4);
assertTrue(tutorials.get(0).getType().equalsIgnoreCase("java"));
}
StaxParser parser;
@Test
public void getAllTutorialsTest() {
parser = new StaxParser(new File(fileName));
List<Tutorial> tutorials = parser.getAllTutorial();
assertNotNull(tutorials);
assertTrue(tutorials.size() == 4);
assertTrue(tutorials.get(0).getType().equalsIgnoreCase("java"));
}
}

View File

@ -8,24 +8,23 @@ import org.xmlunit.diff.DifferenceEvaluator;
public class IgnoreAttributeDifferenceEvaluator implements DifferenceEvaluator {
private String attributeName;
private String attributeName;
public IgnoreAttributeDifferenceEvaluator(String attributeName) {
this.attributeName = attributeName;
}
public IgnoreAttributeDifferenceEvaluator(String attributeName) {
this.attributeName = attributeName;
}
@Override
public ComparisonResult evaluate(Comparison comparison,
ComparisonResult outcome) {
if (outcome == ComparisonResult.EQUAL)
return outcome;
final Node controlNode = comparison.getControlDetails().getTarget();
if (controlNode instanceof Attr) {
Attr attr = (Attr) controlNode;
if (attr.getName().equals(attributeName)) {
return ComparisonResult.SIMILAR;
}
}
return outcome;
}
@Override
public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) {
if (outcome == ComparisonResult.EQUAL)
return outcome;
final Node controlNode = comparison.getControlDetails().getTarget();
if (controlNode instanceof Attr) {
Attr attr = (Attr) controlNode;
if (attr.getName().equals(attributeName)) {
return ComparisonResult.SIMILAR;
}
}
return outcome;
}
}

View File

@ -26,98 +26,78 @@ import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
import static org.xmlunit.matchers.HasXPathMatcher.hasXPath;
public class XMLUnitTest {
@Test
public void givenWrongXml_whenValidateFailsAgainstXsd_thenCorrect() {
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
v.setSchemaSource(Input.fromStream(
XMLUnitTest.class.getResourceAsStream(
"/students.xsd")).build());
ValidationResult r = v.validateInstance(Input.fromStream(
XMLUnitTest.class.getResourceAsStream(
"/students_with_error.xml")).build());
assertFalse(r.isValid());
}
@Test
public void givenWrongXml_whenValidateFailsAgainstXsd_thenCorrect() {
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
v.setSchemaSource(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students.xsd")).build());
ValidationResult r = v.validateInstance(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students_with_error.xml")).build());
assertFalse(r.isValid());
}
@Test
public void givenXmlWithErrors_whenReturnsValidationProblems_thenCorrect() {
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
v.setSchemaSource(Input.fromStream(
XMLUnitTest.class.getResourceAsStream(
"/students.xsd")).build());
ValidationResult r = v.validateInstance(Input.fromStream(
XMLUnitTest.class.getResourceAsStream(
"/students_with_error.xml")).build());
Iterator<ValidationProblem> probs = r.getProblems().iterator();
int count = 0;
while (probs.hasNext()) {
count++;
probs.next().toString();
}
assertTrue(count > 0);
}
@Test
public void givenXmlWithErrors_whenReturnsValidationProblems_thenCorrect() {
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
v.setSchemaSource(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students.xsd")).build());
ValidationResult r = v.validateInstance(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students_with_error.xml")).build());
Iterator<ValidationProblem> probs = r.getProblems().iterator();
int count = 0;
while (probs.hasNext()) {
count++;
probs.next().toString();
}
assertTrue(count > 0);
}
@Test
public void givenXml_whenValidatesAgainstXsd_thenCorrect() {
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
v.setSchemaSource(Input.fromStream(
XMLUnitTest.class.getResourceAsStream(
"/students.xsd")).build());
ValidationResult r = v.validateInstance(Input.fromStream(
XMLUnitTest.class.getResourceAsStream(
"/students.xml")).build());
Iterator<ValidationProblem> probs = r.getProblems().iterator();
while (probs.hasNext()) {
System.out.println(probs.next().toString());
}
assertTrue(r.isValid());
}
@Test
public void givenXml_whenValidatesAgainstXsd_thenCorrect() {
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
v.setSchemaSource(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students.xsd")).build());
ValidationResult r = v.validateInstance(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students.xml")).build());
Iterator<ValidationProblem> probs = r.getProblems().iterator();
while (probs.hasNext()) {
System.out.println(probs.next().toString());
}
assertTrue(r.isValid());
}
@Test
public void givenXPath_whenAbleToRetrieveNodes_thenCorrect() {
ClassLoader classLoader = getClass().getClassLoader();
@Test
public void givenXPath_whenAbleToRetrieveNodes_thenCorrect() {
ClassLoader classLoader = getClass().getClassLoader();
Iterable<Node> i = new JAXPXPathEngine().selectNodes(
"//teacher",
Input.fromFile(
new File(classLoader.getResource("teachers.xml")
.getFile())).build());
assertNotNull(i);
int count = 0;
for (Iterator<Node> it = i.iterator(); it.hasNext();) {
count++;
Node node = it.next();
assertEquals("teacher", node.getNodeName());
NamedNodeMap map = node.getAttributes();
assertEquals("department", map.item(0).getNodeName());
assertEquals("id", map.item(1).getNodeName());
assertEquals("teacher", node.getNodeName());
}
assertEquals(2, count);
}
Iterable<Node> i = new JAXPXPathEngine().selectNodes("//teacher", Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())).build());
assertNotNull(i);
int count = 0;
for (Iterator<Node> it = i.iterator(); it.hasNext();) {
count++;
Node node = it.next();
assertEquals("teacher", node.getNodeName());
NamedNodeMap map = node.getAttributes();
assertEquals("department", map.item(0).getNodeName());
assertEquals("id", map.item(1).getNodeName());
assertEquals("teacher", node.getNodeName());
}
assertEquals(2, count);
}
@Test
public void givenXmlSource_whenAbleToValidateExistingXPath_thenCorrect() {
ClassLoader classLoader = getClass().getClassLoader();
assertThat(Input.fromFile(new File(classLoader.getResource(
"teachers.xml").getFile())), hasXPath("//teachers"));
assertThat(Input.fromFile(new File(classLoader.getResource(
"teachers.xml").getFile())), hasXPath("//teacher"));
assertThat(Input.fromFile(new File(classLoader.getResource(
"teachers.xml").getFile())), hasXPath("//subject"));
assertThat(Input.fromFile(new File(classLoader.getResource(
"teachers.xml").getFile())), hasXPath("//@department"));
}
@Test
public void givenXmlSource_whenAbleToValidateExistingXPath_thenCorrect() {
ClassLoader classLoader = getClass().getClassLoader();
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), hasXPath("//teachers"));
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), hasXPath("//teacher"));
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), hasXPath("//subject"));
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), hasXPath("//@department"));
}
@Test
public void givenXmlSource_whenFailsToValidateInExistentXPath_thenCorrect() {
ClassLoader classLoader = getClass().getClassLoader();
assertThat(Input.fromFile(new File(classLoader.getResource(
"teachers.xml").getFile())), not(hasXPath("//sujet")));
}
@Test
public void givenXmlSource_whenFailsToValidateInExistentXPath_thenCorrect() {
ClassLoader classLoader = getClass().getClassLoader();
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), not(hasXPath("//sujet")));
}
// NOTE: ignore as this test demonstrates that two XMLs that contain the same data
// NOTE: ignore as this test demonstrates that two XMLs that contain the same data
// will fail the isSimilarTo test.
@Test @Ignore
@Test
@Ignore
public void given2XMLS_whenSimilar_thenCorrect_fails() {
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
@ -128,168 +108,135 @@ public class XMLUnitTest {
public void given2XMLS_whenSimilar_thenCorrect() {
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
assertThat(testXml,isSimilarTo(controlXml).withNodeMatcher(
new DefaultNodeMatcher(ElementSelectors.byName)));
assertThat(testXml, isSimilarTo(controlXml).withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)));
}
@Test
public void given2XMLs_whenSimilarWithDiff_thenCorrect() throws Exception {
String myControlXML = "<struct><int>3</int><boolean>false</boolean></struct>";
String myTestXML = "<struct><boolean>false</boolean><int>3</int></struct>";
@Test
public void given2XMLs_whenSimilarWithDiff_thenCorrect() throws Exception {
String myControlXML = "<struct><int>3</int><boolean>false</boolean></struct>";
String myTestXML = "<struct><boolean>false</boolean><int>3</int></struct>";
Diff myDiffSimilar = DiffBuilder
.compare(myControlXML)
.withTest(myTestXML)
.withNodeMatcher(
new DefaultNodeMatcher(ElementSelectors.byName))
.checkForSimilar().build();
assertFalse("XML similar " + myDiffSimilar.toString(),
myDiffSimilar.hasDifferences());
Diff myDiffSimilar = DiffBuilder.compare(myControlXML).withTest(myTestXML).withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)).checkForSimilar().build();
assertFalse("XML similar " + myDiffSimilar.toString(), myDiffSimilar.hasDifferences());
}
}
@Test
public void given2XMLsWithDifferences_whenTestsSimilarWithDifferenceEvaluator_thenCorrect() {
final String control = "<a><b attr=\"abc\"></b></a>";
final String test = "<a><b attr=\"xyz\"></b></a>";
Diff myDiff = DiffBuilder
.compare(control)
.withTest(test)
.withDifferenceEvaluator(
new IgnoreAttributeDifferenceEvaluator("attr"))
.checkForSimilar().build();
@Test
public void given2XMLsWithDifferences_whenTestsSimilarWithDifferenceEvaluator_thenCorrect() {
final String control = "<a><b attr=\"abc\"></b></a>";
final String test = "<a><b attr=\"xyz\"></b></a>";
Diff myDiff = DiffBuilder.compare(control).withTest(test).withDifferenceEvaluator(new IgnoreAttributeDifferenceEvaluator("attr")).checkForSimilar().build();
assertFalse(myDiff.toString(), myDiff.hasDifferences());
}
assertFalse(myDiff.toString(), myDiff.hasDifferences());
}
@Test
public void given2XMLsWithDifferences_whenTestsDifferentWithoutDifferenceEvaluator_thenCorrect() {
final String control = "<a><b attr=\"abc\"></b></a>";
final String test = "<a><b attr=\"xyz\"></b></a>";
@Test
public void given2XMLsWithDifferences_whenTestsDifferentWithoutDifferenceEvaluator_thenCorrect() {
final String control = "<a><b attr=\"abc\"></b></a>";
final String test = "<a><b attr=\"xyz\"></b></a>";
Diff myDiff = DiffBuilder.compare(control).withTest(test)
.checkForSimilar().build();
Diff myDiff = DiffBuilder.compare(control).withTest(test).checkForSimilar().build();
// assertFalse(myDiff.toString(), myDiff.hasDifferences());
assertTrue(myDiff.toString(), myDiff.hasDifferences());
}
// assertFalse(myDiff.toString(), myDiff.hasDifferences());
assertTrue(myDiff.toString(), myDiff.hasDifferences());
}
@Test
public void given2XMLS_whenSimilarWithCustomElementSelector_thenCorrect() {
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
assertThat(
testXml,
isSimilarTo(controlXml).withNodeMatcher(
new DefaultNodeMatcher(ElementSelectors.byName)));
@Test
public void given2XMLS_whenSimilarWithCustomElementSelector_thenCorrect() {
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
assertThat(testXml, isSimilarTo(controlXml).withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)));
}
}
@Test
public void givenFileSourceAsObject_whenAbleToInput_thenCorrect() {
ClassLoader classLoader = getClass().getClassLoader();
assertThat(Input.from(new File(classLoader.getResource("test.xml").getFile())),
isSimilarTo(Input.from(new File(classLoader.getResource("control.xml").getFile()))));
}
@Test
public void givenFileSourceAsObject_whenAbleToInput_thenCorrect() {
ClassLoader classLoader = getClass().getClassLoader();
assertThat(Input.from(new File(classLoader.getResource("test.xml").getFile())), isSimilarTo(Input.from(new File(classLoader.getResource("control.xml").getFile()))));
}
@Test
public void givenStreamAsSource_whenAbleToInput_thenCorrect() {
assertThat(Input.fromStream(XMLUnitTest.class
.getResourceAsStream("/test.xml")),
isSimilarTo(Input.fromStream(XMLUnitTest.class
.getResourceAsStream("/control.xml"))));
@Test
public void givenStreamAsSource_whenAbleToInput_thenCorrect() {
assertThat(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/test.xml")), isSimilarTo(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/control.xml"))));
}
}
@Test
public void givenStreamAsObject_whenAbleToInput_thenCorrect() {
assertThat(Input.from(XMLUnitTest.class.getResourceAsStream("/test.xml")),
isSimilarTo(Input.from(XMLUnitTest.class.getResourceAsStream("/control.xml"))));
}
@Test
public void givenStreamAsObject_whenAbleToInput_thenCorrect() {
assertThat(Input.from(XMLUnitTest.class.getResourceAsStream("/test.xml")), isSimilarTo(Input.from(XMLUnitTest.class.getResourceAsStream("/control.xml"))));
}
@Test
public void givenStringSourceAsObject_whenAbleToInput_thenCorrect() {
assertThat(
Input.from("<struct><int>3</int><boolean>false</boolean></struct>"),
isSimilarTo(Input
.from("<struct><int>3</int><boolean>false</boolean></struct>")));
}
@Test
public void givenStringSourceAsObject_whenAbleToInput_thenCorrect() {
assertThat(Input.from("<struct><int>3</int><boolean>false</boolean></struct>"), isSimilarTo(Input.from("<struct><int>3</int><boolean>false</boolean></struct>")));
}
@Test
public void givenFileSource_whenAbleToInput_thenCorrect() {
ClassLoader classLoader = getClass().getClassLoader();
String testPath = classLoader.getResource("test.xml").getPath();
String controlPath = classLoader.getResource("control.xml").getPath();
assertThat(Input.fromFile(testPath),
isSimilarTo(Input.fromFile(controlPath)));
}
@Test
public void givenFileSource_whenAbleToInput_thenCorrect() {
ClassLoader classLoader = getClass().getClassLoader();
String testPath = classLoader.getResource("test.xml").getPath();
String controlPath = classLoader.getResource("control.xml").getPath();
assertThat(Input.fromFile(testPath), isSimilarTo(Input.fromFile(controlPath)));
}
@Test
public void givenStringSource_whenAbleToInput_thenCorrect() {
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
assertThat(Input.fromString(testXml),
isSimilarTo(Input.fromString(controlXml)));
@Test
public void givenStringSource_whenAbleToInput_thenCorrect() {
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
assertThat(Input.fromString(testXml), isSimilarTo(Input.fromString(controlXml)));
}
}
@Test
public void givenSource_whenAbleToInput_thenCorrect() {
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
assertThat(Input.fromString(testXml),
isSimilarTo(Input.fromString(controlXml)));
@Test
public void givenSource_whenAbleToInput_thenCorrect() {
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
assertThat(Input.fromString(testXml), isSimilarTo(Input.fromString(controlXml)));
}
}
@Test
public void given2XMLS_whenIdentical_thenCorrect() {
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
assertThat(testXml, isIdenticalTo(controlXml));
@Test
public void given2XMLS_whenIdentical_thenCorrect() {
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
assertThat(testXml, isIdenticalTo(controlXml));
}
}
@Test
public void given2XMLSWithSimilarNodesButDifferentSequence_whenNotIdentical_thenCorrect() {
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
assertThat(testXml, not(isIdenticalTo(controlXml)));
@Test
public void given2XMLSWithSimilarNodesButDifferentSequence_whenNotIdentical_thenCorrect() {
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
assertThat(testXml, not(isIdenticalTo(controlXml)));
}
}
@Test
public void given2XMLS_whenGeneratesDifferences_thenCorrect()
throws Exception {
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
Diff myDiff = DiffBuilder.compare(controlXml).withTest(testXml).build();
Iterator<Difference> iter = myDiff.getDifferences().iterator();
int size = 0;
while (iter.hasNext()) {
iter.next().toString();
size++;
}
assertThat(size, greaterThan(1));
}
@Test
public void given2XMLS_whenGeneratesDifferences_thenCorrect() throws Exception {
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
Diff myDiff = DiffBuilder.compare(controlXml).withTest(testXml).build();
Iterator<Difference> iter = myDiff.getDifferences().iterator();
int size = 0;
while (iter.hasNext()) {
iter.next().toString();
size++;
}
assertThat(size, greaterThan(1));
}
@Test
public void given2XMLS_whenGeneratesOneDifference_thenCorrect()
throws Exception {
String myControlXML = "<struct><int>3</int><boolean>false</boolean></struct>";
String myTestXML = "<struct><boolean>false</boolean><int>3</int></struct>";
Diff myDiff = DiffBuilder
.compare(myControlXML)
.withTest(myTestXML)
.withComparisonController(
ComparisonControllers.StopWhenDifferent).build();
Iterator<Difference> iter = myDiff.getDifferences().iterator();
int size = 0;
while (iter.hasNext()) {
iter.next().toString();
size++;
}
assertThat(size, equalTo(1));
}
@Test
public void given2XMLS_whenGeneratesOneDifference_thenCorrect() throws Exception {
String myControlXML = "<struct><int>3</int><boolean>false</boolean></struct>";
String myTestXML = "<struct><boolean>false</boolean><int>3</int></struct>";
Diff myDiff = DiffBuilder.compare(myControlXML).withTest(myTestXML).withComparisonController(ComparisonControllers.StopWhenDifferent).build();
Iterator<Difference> iter = myDiff.getDifferences().iterator();
int size = 0;
while (iter.hasNext()) {
iter.next().toString();
size++;
}
assertThat(size, equalTo(1));
}
}

View File

@ -40,7 +40,6 @@ public class Customer {
@Override
public String toString() {
return "Customer [firstName=" + firstName + ", lastName=" + lastName
+ ", dob=" + dob + "]";
return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]";
}
}

View File

@ -5,7 +5,6 @@ import com.thoughtworks.xstream.annotations.XStreamOmitField;
import java.util.Date;
@XStreamAlias("customer")
public class CustomerOmitField {
@ -42,9 +41,7 @@ public class CustomerOmitField {
@Override
public String toString() {
return "CustomerOmitAnnotation [firstName=" + firstName + ", lastName="
+ lastName + ", dob=" + dob + "]";
return "CustomerOmitAnnotation [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]";
}
}

View File

@ -39,8 +39,7 @@ public class ContactDetails {
@Override
public String toString() {
return "ContactDetails [mobile=" + mobile + ", landline=" + landline
+ ", contactType=" + contactType + "]";
return "ContactDetails [mobile=" + mobile + ", landline=" + landline + ", contactType=" + contactType + "]";
}
}

View File

@ -50,8 +50,6 @@ public class Customer {
@Override
public String toString() {
return "Customer [firstName=" + firstName + ", lastName=" + lastName
+ ", dob=" + dob + ", contactDetailsList=" + contactDetailsList
+ "]";
return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList + "]";
}
}

View File

@ -39,8 +39,7 @@ public class ContactDetails {
@Override
public String toString() {
return "ContactDetails [mobile=" + mobile + ", landline=" + landline
+ ", contactType=" + contactType + "]";
return "ContactDetails [mobile=" + mobile + ", landline=" + landline + ", contactType=" + contactType + "]";
}
}

View File

@ -52,8 +52,6 @@ public class Customer {
@Override
public String toString() {
return "Customer [firstName=" + firstName + ", lastName=" + lastName
+ ", dob=" + dob + ", contactDetailsList=" + contactDetailsList
+ "]";
return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList + "]";
}
}

View File

@ -39,7 +39,6 @@ public class CustomerAddressDetails {
this.age = age;
}
public List<AddressDetails> getAddressDetails() {
return addressDetails;
}

View File

@ -29,7 +29,7 @@ public class ComplexXmlToObjectCollectionTest {
Customer customer = (Customer) xstream.fromXML(reader);
Assert.assertNotNull(customer);
Assert.assertNotNull(customer.getContactDetailsList());
//System.out.println(customer);
// System.out.println(customer);
} catch (IOException e) {
e.printStackTrace();

View File

@ -29,7 +29,7 @@ public class XmlToObjectIgnoreFieldsTest {
FileReader reader = new FileReader(classLoader.getResource("data-file-ignore-field.xml").getFile());
Customer customer = (Customer) xstream.fromXML(reader);
Assert.assertNotNull(customer);
//System.out.println(customer);
// System.out.println(customer);
} catch (IOException e) {
e.printStackTrace();
}

View File

@ -42,5 +42,4 @@ public class XmlToObjectTest {
Assert.assertNotNull(convertedCustomer);
}
}