formatting work
This commit is contained in:
parent
034cde6e20
commit
966e53a85b
@ -11,28 +11,28 @@ import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
|
|||||||
|
|
||||||
@EnableWebMvc
|
@EnableWebMvc
|
||||||
@Configuration
|
@Configuration
|
||||||
@ComponentScan({"com.baeldung.freemarker"})
|
@ComponentScan({ "com.baeldung.freemarker" })
|
||||||
public class SpringWebConfig extends WebMvcConfigurerAdapter {
|
public class SpringWebConfig extends WebMvcConfigurerAdapter {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||||
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
|
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public FreeMarkerViewResolver freemarkerViewResolver() {
|
public FreeMarkerViewResolver freemarkerViewResolver() {
|
||||||
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
|
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
|
||||||
resolver.setCache(true);
|
resolver.setCache(true);
|
||||||
resolver.setPrefix("");
|
resolver.setPrefix("");
|
||||||
resolver.setSuffix(".ftl");
|
resolver.setSuffix(".ftl");
|
||||||
return resolver;
|
return resolver;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public FreeMarkerConfigurer freemarkerConfig() {
|
public FreeMarkerConfigurer freemarkerConfig() {
|
||||||
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
|
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
|
||||||
freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/ftl/");
|
freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/ftl/");
|
||||||
return freeMarkerConfigurer;
|
return freeMarkerConfigurer;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -4,19 +4,19 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche
|
|||||||
|
|
||||||
public class WebConfiguration extends AbstractAnnotationConfigDispatcherServletInitializer {
|
public class WebConfiguration extends AbstractAnnotationConfigDispatcherServletInitializer {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected Class<?>[] getServletConfigClasses() {
|
protected Class<?>[] getServletConfigClasses() {
|
||||||
return new Class[] { SpringWebConfig.class };
|
return new Class[] { SpringWebConfig.class };
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected String[] getServletMappings() {
|
protected String[] getServletMappings() {
|
||||||
return new String[] { "/" };
|
return new String[] { "/" };
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected Class<?>[] getRootConfigClasses() {
|
protected Class<?>[] getRootConfigClasses() {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -16,33 +16,31 @@ import com.baeldung.freemarker.model.Car;
|
|||||||
@Controller
|
@Controller
|
||||||
public class SpringController {
|
public class SpringController {
|
||||||
|
|
||||||
private static List<Car> carList = new ArrayList<Car>();
|
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"));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
@RequestMapping(value = "/", method = RequestMethod.GET)
|
||||||
|
public String home(Locale locale, Model model) {
|
||||||
|
return "redirect:/cars";
|
||||||
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/cars", method = RequestMethod.GET)
|
static {
|
||||||
public String init(@ModelAttribute("model") ModelMap model) {
|
carList.add(new Car("Honda", "Civic"));
|
||||||
model.addAttribute("carList", carList);
|
carList.add(new Car("Toyota", "Camry"));
|
||||||
return "index";
|
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";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -2,32 +2,32 @@ package com.baeldung.freemarker.model;
|
|||||||
|
|
||||||
public class Car {
|
public class Car {
|
||||||
|
|
||||||
private String make;
|
private String make;
|
||||||
private String model;
|
private String model;
|
||||||
|
|
||||||
public Car(){
|
public Car() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Car(String make, String model) {
|
public Car(String make, String model) {
|
||||||
this.make = make;
|
this.make = make;
|
||||||
this.model = model;
|
this.model = model;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getMake() {
|
public String getMake() {
|
||||||
return make;
|
return make;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setMake(String make) {
|
public void setMake(String make) {
|
||||||
this.make = make;
|
this.make = make;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getModel() {
|
public String getModel() {
|
||||||
return model;
|
return model;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setModel(String model) {
|
public void setModel(String model) {
|
||||||
this.model = model;
|
this.model = model;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -19,21 +19,13 @@ public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAda
|
|||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||||
auth.inMemoryAuthentication()
|
auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER");
|
||||||
.withUser("user1").password("user1Pass")
|
|
||||||
.authorities("ROLE_USER");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
http.authorizeRequests()
|
http.authorizeRequests().antMatchers("/securityNone").permitAll().anyRequest().authenticated().and().httpBasic().authenticationEntryPoint(authenticationEntryPoint);
|
||||||
.antMatchers("/securityNone").permitAll()
|
|
||||||
.anyRequest().authenticated()
|
|
||||||
.and()
|
|
||||||
.httpBasic()
|
|
||||||
.authenticationEntryPoint(authenticationEntryPoint);
|
|
||||||
|
|
||||||
http.addFilterAfter(new CustomFilter(),
|
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
|
||||||
BasicAuthenticationFilter.class);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,7 +5,7 @@ import org.springframework.context.annotation.Configuration;
|
|||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@ComponentScan("org.baeldung.security")
|
@ComponentScan("org.baeldung.security")
|
||||||
//@ImportResource({ "classpath:webSecurityConfig.xml" })
|
// @ImportResource({ "classpath:webSecurityConfig.xml" })
|
||||||
public class SecSecurityConfig {
|
public class SecSecurityConfig {
|
||||||
|
|
||||||
public SecSecurityConfig() {
|
public SecSecurityConfig() {
|
||||||
|
@ -9,8 +9,7 @@ import org.springframework.context.annotation.FilterType;
|
|||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableAutoConfiguration
|
@EnableAutoConfiguration
|
||||||
@ComponentScan(excludeFilters =
|
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.voter.*"))
|
||||||
@ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.voter.*"))
|
|
||||||
public class Application extends SpringBootServletInitializer {
|
public class Application extends SpringBootServletInitializer {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(Application.class, args);
|
SpringApplication.run(Application.class, args);
|
||||||
|
@ -7,7 +7,7 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
public interface UserRepository extends JpaRepository<User, Long> {
|
public interface UserRepository extends JpaRepository<User, Long> {
|
||||||
|
|
||||||
User findByUsername(final String username);
|
User findByUsername(final String username);
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
void removeUserByUsername(String username);
|
void removeUserByUsername(String username);
|
||||||
|
|
||||||
|
@ -15,7 +15,7 @@ import javax.persistence.ManyToOne;
|
|||||||
import javax.persistence.Table;
|
import javax.persistence.Table;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name="user_table")
|
@Table(name = "user_table")
|
||||||
public class User {
|
public class User {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
|
@ -21,13 +21,6 @@ public class MinuteBasedVoter implements AccessDecisionVoter {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int vote(Authentication authentication, Object object, Collection collection) {
|
public int vote(Authentication authentication, Object object, Collection collection) {
|
||||||
return authentication
|
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);
|
||||||
.getAuthorities()
|
|
||||||
.stream()
|
|
||||||
.map(GrantedAuthority::getAuthority)
|
|
||||||
.filter(r -> "ROLE_USER".equals(r) && LocalDateTime.now().getMinute() % 2 != 0)
|
|
||||||
.findAny()
|
|
||||||
.map(s -> ACCESS_DENIED)
|
|
||||||
.orElseGet(() -> ACCESS_ABSTAIN);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,7 @@ import org.springframework.context.annotation.FilterType;
|
|||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableAutoConfiguration
|
@EnableAutoConfiguration
|
||||||
@ComponentScan(basePackages = {"org.baeldung.voter"})
|
@ComponentScan(basePackages = { "org.baeldung.voter" })
|
||||||
public class VoterApplication {
|
public class VoterApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
@ -24,10 +24,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
|||||||
@Autowired
|
@Autowired
|
||||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||||
// @formatter: off
|
// @formatter: off
|
||||||
auth.inMemoryAuthentication()
|
auth.inMemoryAuthentication().withUser("user").password("pass").roles("USER").and().withUser("admin").password("pass").roles("ADMIN");
|
||||||
.withUser("user").password("pass").roles("USER")
|
|
||||||
.and()
|
|
||||||
.withUser("admin").password("pass").roles("ADMIN");
|
|
||||||
// @formatter: on
|
// @formatter: on
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,33 +33,15 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
|||||||
// @formatter: off
|
// @formatter: off
|
||||||
http
|
http
|
||||||
// needed so our login could work
|
// needed so our login could work
|
||||||
.csrf()
|
.csrf().disable().authorizeRequests().anyRequest().authenticated().accessDecisionManager(accessDecisionManager()).antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER").and().formLogin().permitAll().and().logout().permitAll()
|
||||||
.disable()
|
.deleteCookies("JSESSIONID").logoutSuccessUrl("/login");
|
||||||
.authorizeRequests()
|
|
||||||
.anyRequest()
|
|
||||||
.authenticated()
|
|
||||||
.accessDecisionManager(accessDecisionManager())
|
|
||||||
.antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER")
|
|
||||||
.and()
|
|
||||||
.formLogin()
|
|
||||||
.permitAll()
|
|
||||||
.and()
|
|
||||||
.logout()
|
|
||||||
.permitAll()
|
|
||||||
.deleteCookies("JSESSIONID")
|
|
||||||
.logoutSuccessUrl("/login");
|
|
||||||
// @formatter: on
|
// @formatter: on
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public AccessDecisionManager accessDecisionManager() {
|
public AccessDecisionManager accessDecisionManager() {
|
||||||
// @formatter: off
|
// @formatter: off
|
||||||
List<AccessDecisionVoter<? extends Object>> decisionVoters =
|
List<AccessDecisionVoter<? extends Object>> decisionVoters = Arrays.asList(new WebExpressionVoter(), new RoleVoter(), new AuthenticatedVoter(), new MinuteBasedVoter());
|
||||||
Arrays.asList(
|
|
||||||
new WebExpressionVoter(),
|
|
||||||
new RoleVoter(),
|
|
||||||
new AuthenticatedVoter(),
|
|
||||||
new MinuteBasedVoter());
|
|
||||||
// @formatter: on
|
// @formatter: on
|
||||||
return new UnanimousBased(decisionVoters);
|
return new UnanimousBased(decisionVoters);
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,7 @@ import org.springframework.context.annotation.ImportResource;
|
|||||||
* Created by ambrusadrianz on 09/10/2016.
|
* Created by ambrusadrianz on 09/10/2016.
|
||||||
*/
|
*/
|
||||||
@Configuration
|
@Configuration
|
||||||
@ImportResource({"classpath:spring-security.xml"})
|
@ImportResource({ "classpath:spring-security.xml" })
|
||||||
public class XmlSecurityConfig {
|
public class XmlSecurityConfig {
|
||||||
public XmlSecurityConfig() {
|
public XmlSecurityConfig() {
|
||||||
super();
|
super();
|
||||||
|
@ -15,6 +15,7 @@ public class MyUserLiveTest {
|
|||||||
|
|
||||||
private final MyUser userJohn = new MyUser("john", "doe", "john@doe.com", 11);
|
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";
|
private String URL_PREFIX = "http://localhost:8082/spring-security-rest-full/auth/api/myusers";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGettingListOfUsers_thenCorrect() {
|
public void whenGettingListOfUsers_thenCorrect() {
|
||||||
final Response response = givenAuth().get(URL_PREFIX);
|
final Response response = givenAuth().get(URL_PREFIX);
|
||||||
|
@ -16,11 +16,11 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationFa
|
|||||||
@ComponentScan("org.baeldung.security")
|
@ComponentScan("org.baeldung.security")
|
||||||
public class SecurityJavaConfig extends WebSecurityConfigurerAdapter {
|
public class SecurityJavaConfig extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
// @Autowired
|
// @Autowired
|
||||||
// private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
|
// private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
|
||||||
|
|
||||||
// @Autowired
|
// @Autowired
|
||||||
// private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
|
// private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
|
||||||
|
|
||||||
public SecurityJavaConfig() {
|
public SecurityJavaConfig() {
|
||||||
super();
|
super();
|
||||||
|
@ -20,7 +20,7 @@ public class WebConfig extends WebMvcConfigurerAdapter {
|
|||||||
public WebConfig() {
|
public WebConfig() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
|
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
|
||||||
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
|
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
|
||||||
|
@ -14,26 +14,24 @@ import org.springframework.web.bind.annotation.ResponseBody;
|
|||||||
@Controller
|
@Controller
|
||||||
public class AsyncController {
|
public class AsyncController {
|
||||||
|
|
||||||
private static final Logger log = Logger.getLogger(AsyncService.class);
|
private static final Logger log = Logger.getLogger(AsyncService.class);
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private AsyncService asyncService;
|
private AsyncService asyncService;
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.GET, value = "/async")
|
@RequestMapping(method = RequestMethod.GET, value = "/async")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public Object standardProcessing() throws Exception {
|
public Object standardProcessing() throws Exception {
|
||||||
log.info("Outside the @Async logic - before the async call: "
|
log.info("Outside the @Async logic - before the async call: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
||||||
+ SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
asyncService.asyncCall();
|
||||||
asyncService.asyncCall();
|
log.info("Inside the @Async logic - after the async call: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
||||||
log.info("Inside the @Async logic - after the async call: "
|
return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||||
+ SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
}
|
||||||
return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
|
||||||
}
|
@RequestMapping(method = RequestMethod.GET, value = "/async2")
|
||||||
|
@ResponseBody
|
||||||
@RequestMapping(method = RequestMethod.GET, value = "/async2")
|
public Callable<Boolean> springMVCAsyncTest() {
|
||||||
@ResponseBody
|
return asyncService.checkIfPrincipalPropagated();
|
||||||
public Callable<Boolean> springMVCAsyncTest() {
|
}
|
||||||
return asyncService.checkIfPrincipalPropagated();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -3,9 +3,9 @@ package org.baeldung.web.service;
|
|||||||
import java.util.concurrent.Callable;
|
import java.util.concurrent.Callable;
|
||||||
|
|
||||||
public interface AsyncService {
|
public interface AsyncService {
|
||||||
|
|
||||||
void asyncCall();
|
void asyncCall();
|
||||||
|
|
||||||
Callable<Boolean> checkIfPrincipalPropagated();
|
Callable<Boolean> checkIfPrincipalPropagated();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -10,27 +10,25 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
public class AsyncServiceImpl implements AsyncService {
|
public class AsyncServiceImpl implements AsyncService {
|
||||||
|
|
||||||
private static final Logger log = Logger.getLogger(AsyncService.class);
|
private static final Logger log = Logger.getLogger(AsyncService.class);
|
||||||
|
|
||||||
@Async
|
@Async
|
||||||
@Override
|
@Override
|
||||||
public void asyncCall() {
|
public void asyncCall() {
|
||||||
log.info("Inside the @Async logic: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
log.info("Inside the @Async logic: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Callable<Boolean> checkIfPrincipalPropagated() {
|
public Callable<Boolean> checkIfPrincipalPropagated() {
|
||||||
Object before
|
Object before = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||||
= SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
log.info("Before new thread: " + before);
|
||||||
log.info("Before new thread: " + before);
|
|
||||||
|
|
||||||
return new Callable<Boolean>() {
|
return new Callable<Boolean>() {
|
||||||
public Boolean call() throws Exception {
|
public Boolean call() throws Exception {
|
||||||
Object after
|
Object after = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||||
= SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
log.info("New thread: " + after);
|
||||||
log.info("New thread: " + after);
|
return before == after;
|
||||||
return before == after;
|
}
|
||||||
}
|
};
|
||||||
};
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -22,27 +22,27 @@ import org.springframework.web.context.WebApplicationContext;
|
|||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@WebAppConfiguration
|
@WebAppConfiguration
|
||||||
@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class})
|
@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class })
|
||||||
public class AsyncControllerTest {
|
public class AsyncControllerTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
WebApplicationContext wac;
|
WebApplicationContext wac;
|
||||||
@Autowired
|
@Autowired
|
||||||
MockHttpSession session;
|
MockHttpSession session;
|
||||||
|
|
||||||
@Mock
|
|
||||||
AsyncController controller;
|
|
||||||
|
|
||||||
private MockMvc mockMvc;
|
@Mock
|
||||||
|
AsyncController controller;
|
||||||
|
|
||||||
@Before
|
private MockMvc mockMvc;
|
||||||
public void setup() {
|
|
||||||
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Before
|
||||||
public void testAsync() throws Exception {
|
public void setup() {
|
||||||
mockMvc.perform(MockMvcRequestBuilders.get("/async")).andExpect(status().is5xxServerError());
|
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testAsync() throws Exception {
|
||||||
|
mockMvc.perform(MockMvcRequestBuilders.get("/async")).andExpect(status().is5xxServerError());
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -10,10 +10,10 @@ import org.springframework.web.multipart.commons.CommonsMultipartResolver;
|
|||||||
@ComponentScan({ "org.baeldung.web" })
|
@ComponentScan({ "org.baeldung.web" })
|
||||||
public class TestConfig {
|
public class TestConfig {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public MultipartResolver multipartResolver() {
|
public MultipartResolver multipartResolver() {
|
||||||
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
|
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
|
||||||
return multipartResolver;
|
return multipartResolver;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -13,17 +13,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
|||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||||
auth
|
auth.inMemoryAuthentication().withUser("admin").password("password").roles("ADMIN");
|
||||||
.inMemoryAuthentication()
|
|
||||||
.withUser("admin").password("password").roles("ADMIN");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
http
|
http.httpBasic().and().authorizeRequests().antMatchers("/").hasRole("ADMIN").anyRequest().authenticated();
|
||||||
.httpBasic().and()
|
|
||||||
.authorizeRequests()
|
|
||||||
.antMatchers("/").hasRole("ADMIN")
|
|
||||||
.anyRequest().authenticated();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -42,10 +42,10 @@ public class SessionControllerTest {
|
|||||||
@Test
|
@Test
|
||||||
public void testRedisControlsSession() {
|
public void testRedisControlsSession() {
|
||||||
ResponseEntity<String> result = testRestTemplateWithAuth.getForEntity(testUrl, String.class);
|
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("*");
|
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];
|
String sessionCookie = result.getHeaders().get("Set-Cookie").get(0).split(";")[0];
|
||||||
HttpHeaders headers = new HttpHeaders();
|
HttpHeaders headers = new HttpHeaders();
|
||||||
@ -53,12 +53,12 @@ public class SessionControllerTest {
|
|||||||
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
|
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
|
||||||
|
|
||||||
result = testRestTemplate.exchange(testUrl, HttpMethod.GET, httpEntity, String.class);
|
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);
|
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
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -18,7 +18,7 @@ import java.util.concurrent.Executors;
|
|||||||
@Configuration
|
@Configuration
|
||||||
@EnableAsync
|
@EnableAsync
|
||||||
@EnableScheduling
|
@EnableScheduling
|
||||||
public class ThreadConfig extends AsyncConfigurerSupport implements SchedulingConfigurer{
|
public class ThreadConfig extends AsyncConfigurerSupport implements SchedulingConfigurer {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private BeanFactory beanFactory;
|
private BeanFactory beanFactory;
|
||||||
|
@ -47,71 +47,71 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application
|
|||||||
this.applicationContext = applicationContext;
|
this.applicationContext = applicationContext;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public ViewResolver htmlViewResolver() {
|
public ViewResolver htmlViewResolver() {
|
||||||
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
|
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
|
||||||
resolver.setTemplateEngine(templateEngine(htmlTemplateResolver()));
|
resolver.setTemplateEngine(templateEngine(htmlTemplateResolver()));
|
||||||
resolver.setContentType("text/html");
|
resolver.setContentType("text/html");
|
||||||
resolver.setCharacterEncoding("UTF-8");
|
resolver.setCharacterEncoding("UTF-8");
|
||||||
resolver.setViewNames(ArrayUtil.array("*.html"));
|
resolver.setViewNames(ArrayUtil.array("*.html"));
|
||||||
return resolver;
|
return resolver;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public ViewResolver javascriptViewResolver() {
|
public ViewResolver javascriptViewResolver() {
|
||||||
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
|
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
|
||||||
resolver.setTemplateEngine(templateEngine(javascriptTemplateResolver()));
|
resolver.setTemplateEngine(templateEngine(javascriptTemplateResolver()));
|
||||||
resolver.setContentType("application/javascript");
|
resolver.setContentType("application/javascript");
|
||||||
resolver.setCharacterEncoding("UTF-8");
|
resolver.setCharacterEncoding("UTF-8");
|
||||||
resolver.setViewNames(ArrayUtil.array("*.js"));
|
resolver.setViewNames(ArrayUtil.array("*.js"));
|
||||||
return resolver;
|
return resolver;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public ViewResolver plainViewResolver() {
|
public ViewResolver plainViewResolver() {
|
||||||
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
|
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
|
||||||
resolver.setTemplateEngine(templateEngine(plainTemplateResolver()));
|
resolver.setTemplateEngine(templateEngine(plainTemplateResolver()));
|
||||||
resolver.setContentType("text/plain");
|
resolver.setContentType("text/plain");
|
||||||
resolver.setCharacterEncoding("UTF-8");
|
resolver.setCharacterEncoding("UTF-8");
|
||||||
resolver.setViewNames(ArrayUtil.array("*.txt"));
|
resolver.setViewNames(ArrayUtil.array("*.txt"));
|
||||||
return resolver;
|
return resolver;
|
||||||
}
|
}
|
||||||
|
|
||||||
private TemplateEngine templateEngine(ITemplateResolver templateResolver) {
|
private TemplateEngine templateEngine(ITemplateResolver templateResolver) {
|
||||||
SpringTemplateEngine engine = new SpringTemplateEngine();
|
SpringTemplateEngine engine = new SpringTemplateEngine();
|
||||||
engine.addDialect(new LayoutDialect(new GroupingStrategy()));
|
engine.addDialect(new LayoutDialect(new GroupingStrategy()));
|
||||||
engine.addDialect(new Java8TimeDialect());
|
engine.addDialect(new Java8TimeDialect());
|
||||||
engine.setTemplateResolver(templateResolver);
|
engine.setTemplateResolver(templateResolver);
|
||||||
engine.setTemplateEngineMessageSource(messageSource());
|
engine.setTemplateEngineMessageSource(messageSource());
|
||||||
return engine;
|
return engine;
|
||||||
}
|
}
|
||||||
|
|
||||||
private ITemplateResolver htmlTemplateResolver() {
|
private ITemplateResolver htmlTemplateResolver() {
|
||||||
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
|
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
|
||||||
resolver.setApplicationContext(applicationContext);
|
resolver.setApplicationContext(applicationContext);
|
||||||
resolver.setPrefix("/WEB-INF/views/");
|
resolver.setPrefix("/WEB-INF/views/");
|
||||||
resolver.setCacheable(false);
|
resolver.setCacheable(false);
|
||||||
resolver.setTemplateMode(TemplateMode.HTML);
|
resolver.setTemplateMode(TemplateMode.HTML);
|
||||||
return resolver;
|
return resolver;
|
||||||
}
|
}
|
||||||
|
|
||||||
private ITemplateResolver javascriptTemplateResolver() {
|
private ITemplateResolver javascriptTemplateResolver() {
|
||||||
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
|
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
|
||||||
resolver.setApplicationContext(applicationContext);
|
resolver.setApplicationContext(applicationContext);
|
||||||
resolver.setPrefix("/WEB-INF/js/");
|
resolver.setPrefix("/WEB-INF/js/");
|
||||||
resolver.setCacheable(false);
|
resolver.setCacheable(false);
|
||||||
resolver.setTemplateMode(TemplateMode.JAVASCRIPT);
|
resolver.setTemplateMode(TemplateMode.JAVASCRIPT);
|
||||||
return resolver;
|
return resolver;
|
||||||
}
|
}
|
||||||
|
|
||||||
private ITemplateResolver plainTemplateResolver() {
|
private ITemplateResolver plainTemplateResolver() {
|
||||||
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
|
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
|
||||||
resolver.setApplicationContext(applicationContext);
|
resolver.setApplicationContext(applicationContext);
|
||||||
resolver.setPrefix("/WEB-INF/txt/");
|
resolver.setPrefix("/WEB-INF/txt/");
|
||||||
resolver.setCacheable(false);
|
resolver.setCacheable(false);
|
||||||
resolver.setTemplateMode(TemplateMode.TEXT);
|
resolver.setTemplateMode(TemplateMode.TEXT);
|
||||||
return resolver;
|
return resolver;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@Description("Spring Message Resolver")
|
@Description("Spring Message Resolver")
|
||||||
@ -121,7 +121,7 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application
|
|||||||
return messageSource;
|
return messageSource;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public LocaleResolver localeResolver() {
|
public LocaleResolver localeResolver() {
|
||||||
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
|
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
|
||||||
localeResolver.setDefaultLocale(new Locale("en"));
|
localeResolver.setDefaultLocale(new Locale("en"));
|
||||||
@ -140,12 +140,12 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application
|
|||||||
registry.addInterceptor(localeChangeInterceptor());
|
registry.addInterceptor(localeChangeInterceptor());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||||
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/");
|
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Description("Custom Conversion Service")
|
@Description("Custom Conversion Service")
|
||||||
public void addFormatters(FormatterRegistry registry) {
|
public void addFormatters(FormatterRegistry registry) {
|
||||||
registry.addFormatter(new NameFormatter());
|
registry.addFormatter(new NameFormatter());
|
||||||
|
@ -13,13 +13,13 @@ import org.springframework.web.bind.annotation.RequestMethod;
|
|||||||
@Controller
|
@Controller
|
||||||
public class DatesController {
|
public class DatesController {
|
||||||
|
|
||||||
@RequestMapping(value = "/dates", method = RequestMethod.GET)
|
@RequestMapping(value = "/dates", method = RequestMethod.GET)
|
||||||
public String getInfo(Model model) {
|
public String getInfo(Model model) {
|
||||||
model.addAttribute("standardDate", new Date());
|
model.addAttribute("standardDate", new Date());
|
||||||
model.addAttribute("localDateTime", LocalDateTime.now());
|
model.addAttribute("localDateTime", LocalDateTime.now());
|
||||||
model.addAttribute("localDate", LocalDate.now());
|
model.addAttribute("localDate", LocalDate.now());
|
||||||
model.addAttribute("timestamp", Instant.now());
|
model.addAttribute("timestamp", Instant.now());
|
||||||
return "dates.html";
|
return "dates.html";
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -31,24 +31,24 @@ import com.baeldung.thymeleaf.config.WebMVCSecurity;
|
|||||||
@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class })
|
@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class })
|
||||||
public class ExpressionUtilityObjectsControllerIntegrationTest {
|
public class ExpressionUtilityObjectsControllerIntegrationTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
WebApplicationContext wac;
|
WebApplicationContext wac;
|
||||||
@Autowired
|
@Autowired
|
||||||
MockHttpSession session;
|
MockHttpSession session;
|
||||||
|
|
||||||
private MockMvc mockMvc;
|
private MockMvc mockMvc;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private Filter springSecurityFilterChain;
|
private Filter springSecurityFilterChain;
|
||||||
|
|
||||||
protected RequestPostProcessor testUser() {
|
protected RequestPostProcessor testUser() {
|
||||||
return user("user1").password("user1Pass").roles("USER");
|
return user("user1").password("user1Pass").roles("USER");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup() {
|
public void setup() {
|
||||||
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
|
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetObjects() throws Exception {
|
public void testGetObjects() throws Exception {
|
||||||
|
@ -25,8 +25,7 @@ public class UserController {
|
|||||||
myUserService.registerNewUserAccount(accountDto);
|
myUserService.registerNewUserAccount(accountDto);
|
||||||
model.addAttribute("message", "Registration successful");
|
model.addAttribute("message", "Registration successful");
|
||||||
return "index";
|
return "index";
|
||||||
}
|
} catch (final Exception exc) {
|
||||||
catch(final Exception exc){
|
|
||||||
model.addAttribute("message", "Registration failed");
|
model.addAttribute("message", "Registration failed");
|
||||||
|
|
||||||
return "index";
|
return "index";
|
||||||
|
@ -29,7 +29,7 @@ public class MyUserDAO {
|
|||||||
entityManager.persist(user);
|
entityManager.persist(user);
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void removeUserByUsername(String username) {
|
public void removeUserByUsername(String username) {
|
||||||
final Query query = entityManager.createQuery("delete from MyUser where username=:username");
|
final Query query = entityManager.createQuery("delete from MyUser where username=:username");
|
||||||
query.setParameter("username", username);
|
query.setParameter("username", username);
|
||||||
|
@ -33,8 +33,8 @@ public class MyUserService {
|
|||||||
final MyUser user = myUserDAO.findByUsername(username);
|
final MyUser user = myUserDAO.findByUsername(username);
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void removeUserByUsername(String username){
|
public void removeUserByUsername(String username) {
|
||||||
myUserDAO.removeUserByUsername(username);
|
myUserDAO.removeUserByUsername(username);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -17,7 +17,7 @@ public class MyUserDto {
|
|||||||
public void setUsername(final String username) {
|
public void setUsername(final String username) {
|
||||||
this.username = username;
|
this.username = username;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getPassword() {
|
public String getPassword() {
|
||||||
return password;
|
return password;
|
||||||
}
|
}
|
||||||
|
@ -59,8 +59,8 @@ public class CustomUserDetailsServiceIntegrationTest {
|
|||||||
myUserService.removeUserByUsername(USERNAME);
|
myUserService.removeUserByUsername(USERNAME);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test (expected = BadCredentialsException.class)
|
@Test(expected = BadCredentialsException.class)
|
||||||
public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() {
|
public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() {
|
||||||
try {
|
try {
|
||||||
MyUserDto userDTO = new MyUserDto();
|
MyUserDto userDTO = new MyUserDto();
|
||||||
@ -69,15 +69,13 @@ public class CustomUserDetailsServiceIntegrationTest {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
myUserService.registerNewUserAccount(userDTO);
|
myUserService.registerNewUserAccount(userDTO);
|
||||||
}
|
} catch (Exception exc) {
|
||||||
catch (Exception exc) {
|
|
||||||
LOG.log(Level.SEVERE, "Error creating account");
|
LOG.log(Level.SEVERE, "Error creating account");
|
||||||
}
|
}
|
||||||
|
|
||||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD);
|
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD);
|
||||||
Authentication authentication = authenticationProvider.authenticate(auth);
|
Authentication authentication = authenticationProvider.authenticate(auth);
|
||||||
}
|
} finally {
|
||||||
finally {
|
|
||||||
myUserService.removeUserByUsername(USERNAME);
|
myUserService.removeUserByUsername(USERNAME);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,7 +20,7 @@ import org.w3c.dom.NodeList;
|
|||||||
import org.xml.sax.SAXException;
|
import org.xml.sax.SAXException;
|
||||||
|
|
||||||
public class DefaultParser {
|
public class DefaultParser {
|
||||||
|
|
||||||
private File file;
|
private File file;
|
||||||
|
|
||||||
public DefaultParser(File file) {
|
public DefaultParser(File file) {
|
||||||
@ -69,7 +69,7 @@ public class DefaultParser {
|
|||||||
}
|
}
|
||||||
return node;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
public NodeList getNodeListByTitle(String name) {
|
public NodeList getNodeListByTitle(String name) {
|
||||||
NodeList nodeList = null;
|
NodeList nodeList = null;
|
||||||
try {
|
try {
|
||||||
@ -125,11 +125,11 @@ public class DefaultParser {
|
|||||||
DocumentBuilder builder = builderFactory.newDocumentBuilder();
|
DocumentBuilder builder = builderFactory.newDocumentBuilder();
|
||||||
|
|
||||||
Document xmlDocument = builder.parse(this.getFile());
|
Document xmlDocument = builder.parse(this.getFile());
|
||||||
|
|
||||||
this.clean(xmlDocument);
|
this.clean(xmlDocument);
|
||||||
|
|
||||||
XPath xPath = XPathFactory.newInstance().newXPath();
|
XPath xPath = XPathFactory.newInstance().newXPath();
|
||||||
|
|
||||||
xPath.setNamespaceContext(new NamespaceContext() {
|
xPath.setNamespaceContext(new NamespaceContext() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -17,115 +17,114 @@ import org.dom4j.io.XMLWriter;
|
|||||||
|
|
||||||
public class Dom4JParser {
|
public class Dom4JParser {
|
||||||
|
|
||||||
private File file;
|
private File file;
|
||||||
|
|
||||||
public Dom4JParser(File file) {
|
public Dom4JParser(File file) {
|
||||||
this.file = file;
|
this.file = file;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Element getRootElement() {
|
public Element getRootElement() {
|
||||||
try {
|
try {
|
||||||
SAXReader reader = new SAXReader();
|
SAXReader reader = new SAXReader();
|
||||||
Document document = reader.read(file);
|
Document document = reader.read(file);
|
||||||
return document.getRootElement();
|
return document.getRootElement();
|
||||||
} catch (DocumentException e) {
|
} catch (DocumentException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Element> getFirstElementList() {
|
public List<Element> getFirstElementList() {
|
||||||
try {
|
try {
|
||||||
SAXReader reader = new SAXReader();
|
SAXReader reader = new SAXReader();
|
||||||
Document document = reader.read(file);
|
Document document = reader.read(file);
|
||||||
return document.getRootElement().elements();
|
return document.getRootElement().elements();
|
||||||
} catch (DocumentException e) {
|
} catch (DocumentException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Node getNodeById(String id) {
|
public Node getNodeById(String id) {
|
||||||
try {
|
try {
|
||||||
SAXReader reader = new SAXReader();
|
SAXReader reader = new SAXReader();
|
||||||
Document document = reader.read(file);
|
Document document = reader.read(file);
|
||||||
List<Node> elements = document.selectNodes("//*[@tutId='" + id + "']");
|
List<Node> elements = document.selectNodes("//*[@tutId='" + id + "']");
|
||||||
return elements.get(0);
|
return elements.get(0);
|
||||||
} catch (DocumentException e) {
|
} catch (DocumentException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Node getElementsListByTitle(String name) {
|
public Node getElementsListByTitle(String name) {
|
||||||
try {
|
try {
|
||||||
SAXReader reader = new SAXReader();
|
SAXReader reader = new SAXReader();
|
||||||
Document document = reader.read(file);
|
Document document = reader.read(file);
|
||||||
List<Node> elements = document
|
List<Node> elements = document.selectNodes("//tutorial[descendant::title[text()=" + "'" + name + "'" + "]]");
|
||||||
.selectNodes("//tutorial[descendant::title[text()=" + "'" + name + "'" + "]]");
|
return elements.get(0);
|
||||||
return elements.get(0);
|
} catch (DocumentException e) {
|
||||||
} catch (DocumentException e) {
|
e.printStackTrace();
|
||||||
e.printStackTrace();
|
return null;
|
||||||
return null;
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public void generateModifiedDocument() {
|
public void generateModifiedDocument() {
|
||||||
try {
|
try {
|
||||||
SAXReader reader = new SAXReader();
|
SAXReader reader = new SAXReader();
|
||||||
Document document = reader.read(file);
|
Document document = reader.read(file);
|
||||||
List<Node> nodes = document.selectNodes("/tutorials/tutorial");
|
List<Node> nodes = document.selectNodes("/tutorials/tutorial");
|
||||||
for (Node node : nodes) {
|
for (Node node : nodes) {
|
||||||
Element element = (Element) node;
|
Element element = (Element) node;
|
||||||
Iterator<Element> iterator = element.elementIterator("title");
|
Iterator<Element> iterator = element.elementIterator("title");
|
||||||
while (iterator.hasNext()) {
|
while (iterator.hasNext()) {
|
||||||
Element title = (Element) iterator.next();
|
Element title = (Element) iterator.next();
|
||||||
title.setText(title.getText() + " updated");
|
title.setText(title.getText() + " updated");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_updated.xml")));
|
XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_updated.xml")));
|
||||||
writer.write(document);
|
writer.write(document);
|
||||||
writer.close();
|
writer.close();
|
||||||
} catch (DocumentException e) {
|
} catch (DocumentException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
// TODO Auto-generated catch block
|
// TODO Auto-generated catch block
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void generateNewDocument() {
|
public void generateNewDocument() {
|
||||||
try {
|
try {
|
||||||
Document document = DocumentHelper.createDocument();
|
Document document = DocumentHelper.createDocument();
|
||||||
Element root = document.addElement("XMLTutorials");
|
Element root = document.addElement("XMLTutorials");
|
||||||
Element tutorialElement = root.addElement("tutorial").addAttribute("tutId", "01");
|
Element tutorialElement = root.addElement("tutorial").addAttribute("tutId", "01");
|
||||||
tutorialElement.addAttribute("type", "xml");
|
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();
|
OutputFormat format = OutputFormat.createPrettyPrint();
|
||||||
XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_new.xml")), format);
|
XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_new.xml")), format);
|
||||||
writer.write(document);
|
writer.write(document);
|
||||||
writer.close();
|
writer.close();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
// TODO Auto-generated catch block
|
// TODO Auto-generated catch block
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public File getFile() {
|
public File getFile() {
|
||||||
return file;
|
return file;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFile(File file) {
|
public void setFile(File file) {
|
||||||
this.file = file;
|
this.file = file;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -12,51 +12,50 @@ import org.jdom2.input.SAXBuilder;
|
|||||||
import org.jdom2.xpath.XPathExpression;
|
import org.jdom2.xpath.XPathExpression;
|
||||||
import org.jdom2.xpath.XPathFactory;
|
import org.jdom2.xpath.XPathFactory;
|
||||||
|
|
||||||
|
|
||||||
public class JDomParser {
|
public class JDomParser {
|
||||||
|
|
||||||
private File file;
|
private File file;
|
||||||
|
|
||||||
public JDomParser(File file) {
|
public JDomParser(File file) {
|
||||||
this.file = file;
|
this.file = file;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Element> getAllTitles() {
|
public List<Element> getAllTitles() {
|
||||||
try {
|
try {
|
||||||
SAXBuilder builder = new SAXBuilder();
|
SAXBuilder builder = new SAXBuilder();
|
||||||
Document doc = builder.build(this.getFile());
|
Document doc = builder.build(this.getFile());
|
||||||
Element tutorials = doc.getRootElement();
|
Element tutorials = doc.getRootElement();
|
||||||
List<Element> titles = tutorials.getChildren("tutorial");
|
List<Element> titles = tutorials.getChildren("tutorial");
|
||||||
return titles;
|
return titles;
|
||||||
} catch (JDOMException | IOException e) {
|
} catch (JDOMException | IOException e) {
|
||||||
// TODO Auto-generated catch block
|
// TODO Auto-generated catch block
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
return null;
|
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 File getFile() {
|
public Element getNodeById(String id) {
|
||||||
return file;
|
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) {
|
return node.get(0);
|
||||||
this.file = file;
|
} catch (JDOMException | IOException e) {
|
||||||
}
|
e.printStackTrace();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public File getFile() {
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFile(File file) {
|
||||||
|
this.file = file;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -13,56 +13,56 @@ import com.baeldung.xml.binding.Tutorials;
|
|||||||
|
|
||||||
public class JaxbParser {
|
public class JaxbParser {
|
||||||
|
|
||||||
private File file;
|
private File file;
|
||||||
|
|
||||||
public JaxbParser(File file) {
|
public JaxbParser(File file) {
|
||||||
this.file = file;
|
this.file = file;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Tutorials getFullDocument() {
|
public Tutorials getFullDocument() {
|
||||||
try {
|
try {
|
||||||
JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class);
|
JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class);
|
||||||
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
|
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
|
||||||
Tutorials tutorials = (Tutorials) jaxbUnmarshaller.unmarshal(this.getFile());
|
Tutorials tutorials = (Tutorials) jaxbUnmarshaller.unmarshal(this.getFile());
|
||||||
return tutorials;
|
return tutorials;
|
||||||
} catch (JAXBException e) {
|
} catch (JAXBException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void createNewDocument() {
|
public void createNewDocument() {
|
||||||
Tutorials tutorials = new Tutorials();
|
Tutorials tutorials = new Tutorials();
|
||||||
tutorials.setTutorial(new ArrayList<Tutorial>());
|
tutorials.setTutorial(new ArrayList<Tutorial>());
|
||||||
Tutorial tut = new Tutorial();
|
Tutorial tut = new Tutorial();
|
||||||
tut.setTutId("01");
|
tut.setTutId("01");
|
||||||
tut.setType("XML");
|
tut.setType("XML");
|
||||||
tut.setTitle("XML with Jaxb");
|
tut.setTitle("XML with Jaxb");
|
||||||
tut.setDescription("XML Binding with Jaxb");
|
tut.setDescription("XML Binding with Jaxb");
|
||||||
tut.setDate("04/02/2015");
|
tut.setDate("04/02/2015");
|
||||||
tut.setAuthor("Jaxb author");
|
tut.setAuthor("Jaxb author");
|
||||||
tutorials.getTutorial().add(tut);
|
tutorials.getTutorial().add(tut);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class);
|
JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class);
|
||||||
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
|
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) {
|
} catch (JAXBException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public File getFile() {
|
public File getFile() {
|
||||||
return file;
|
return file;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFile(File file) {
|
public void setFile(File file) {
|
||||||
this.file = file;
|
this.file = file;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -17,13 +17,13 @@ import org.xml.sax.SAXException;
|
|||||||
|
|
||||||
public class JaxenDemo {
|
public class JaxenDemo {
|
||||||
|
|
||||||
private File file;
|
private File file;
|
||||||
|
|
||||||
public JaxenDemo(File file) {
|
public JaxenDemo(File file) {
|
||||||
this.file = file;
|
this.file = file;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List getAllTutorial(){
|
public List getAllTutorial() {
|
||||||
try {
|
try {
|
||||||
FileInputStream fileIS = new FileInputStream(this.getFile());
|
FileInputStream fileIS = new FileInputStream(this.getFile());
|
||||||
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
|
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
|
||||||
@ -33,25 +33,24 @@ public class JaxenDemo {
|
|||||||
Document xmlDocument = builder.parse(fileIS);
|
Document xmlDocument = builder.parse(fileIS);
|
||||||
|
|
||||||
String expression = "/tutorials/tutorial";
|
String expression = "/tutorials/tutorial";
|
||||||
|
|
||||||
XPath path = new DOMXPath(expression);
|
XPath path = new DOMXPath(expression);
|
||||||
List result = path.selectNodes(xmlDocument);
|
List result = path.selectNodes(xmlDocument);
|
||||||
return result;
|
return result;
|
||||||
|
|
||||||
} catch (SAXException | IOException | ParserConfigurationException | JaxenException e) {
|
} catch (SAXException | IOException | ParserConfigurationException | JaxenException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
return null;
|
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -21,100 +21,100 @@ import com.baeldung.xml.binding.Tutorial;
|
|||||||
|
|
||||||
public class StaxParser {
|
public class StaxParser {
|
||||||
|
|
||||||
private File file;
|
private File file;
|
||||||
|
|
||||||
public StaxParser(File file) {
|
public StaxParser(File file) {
|
||||||
this.file = file;
|
this.file = file;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Tutorial> getAllTutorial() {
|
public List<Tutorial> getAllTutorial() {
|
||||||
boolean bTitle = false;
|
boolean bTitle = false;
|
||||||
boolean bDescription = false;
|
boolean bDescription = false;
|
||||||
boolean bDate = false;
|
boolean bDate = false;
|
||||||
boolean bAuthor = false;
|
boolean bAuthor = false;
|
||||||
List<Tutorial> tutorials = new ArrayList<Tutorial>();
|
List<Tutorial> tutorials = new ArrayList<Tutorial>();
|
||||||
try {
|
try {
|
||||||
XMLInputFactory factory = XMLInputFactory.newInstance();
|
XMLInputFactory factory = XMLInputFactory.newInstance();
|
||||||
XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(this.getFile()));
|
XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(this.getFile()));
|
||||||
Tutorial current = null;
|
Tutorial current = null;
|
||||||
while (eventReader.hasNext()) {
|
while (eventReader.hasNext()) {
|
||||||
XMLEvent event = eventReader.nextEvent();
|
XMLEvent event = eventReader.nextEvent();
|
||||||
switch (event.getEventType()) {
|
switch (event.getEventType()) {
|
||||||
case XMLStreamConstants.START_ELEMENT:
|
case XMLStreamConstants.START_ELEMENT:
|
||||||
StartElement startElement = event.asStartElement();
|
StartElement startElement = event.asStartElement();
|
||||||
String qName = startElement.getName().getLocalPart();
|
String qName = startElement.getName().getLocalPart();
|
||||||
if (qName.equalsIgnoreCase("tutorial")) {
|
if (qName.equalsIgnoreCase("tutorial")) {
|
||||||
current = new Tutorial();
|
current = new Tutorial();
|
||||||
Iterator<Attribute> attributes = startElement.getAttributes();
|
Iterator<Attribute> attributes = startElement.getAttributes();
|
||||||
while (attributes.hasNext()) {
|
while (attributes.hasNext()) {
|
||||||
Attribute currentAt = attributes.next();
|
Attribute currentAt = attributes.next();
|
||||||
if (currentAt.getName().toString().equalsIgnoreCase("tutId")) {
|
if (currentAt.getName().toString().equalsIgnoreCase("tutId")) {
|
||||||
current.setTutId(currentAt.getValue());
|
current.setTutId(currentAt.getValue());
|
||||||
} else if (currentAt.getName().toString().equalsIgnoreCase("type")) {
|
} else if (currentAt.getName().toString().equalsIgnoreCase("type")) {
|
||||||
current.setType(currentAt.getValue());
|
current.setType(currentAt.getValue());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (qName.equalsIgnoreCase("title")) {
|
} else if (qName.equalsIgnoreCase("title")) {
|
||||||
bTitle = true;
|
bTitle = true;
|
||||||
} else if (qName.equalsIgnoreCase("description")) {
|
} else if (qName.equalsIgnoreCase("description")) {
|
||||||
bDescription = true;
|
bDescription = true;
|
||||||
} else if (qName.equalsIgnoreCase("date")) {
|
} else if (qName.equalsIgnoreCase("date")) {
|
||||||
bDate = true;
|
bDate = true;
|
||||||
} else if (qName.equalsIgnoreCase("author")) {
|
} else if (qName.equalsIgnoreCase("author")) {
|
||||||
bAuthor = true;
|
bAuthor = true;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case XMLStreamConstants.CHARACTERS:
|
case XMLStreamConstants.CHARACTERS:
|
||||||
Characters characters = event.asCharacters();
|
Characters characters = event.asCharacters();
|
||||||
if (bTitle) {
|
if (bTitle) {
|
||||||
if (current != null) {
|
if (current != null) {
|
||||||
current.setTitle(characters.getData());
|
current.setTitle(characters.getData());
|
||||||
}
|
}
|
||||||
bTitle = false;
|
bTitle = false;
|
||||||
}
|
}
|
||||||
if (bDescription) {
|
if (bDescription) {
|
||||||
if (current != null) {
|
if (current != null) {
|
||||||
current.setDescription(characters.getData());
|
current.setDescription(characters.getData());
|
||||||
}
|
}
|
||||||
bDescription = false;
|
bDescription = false;
|
||||||
}
|
}
|
||||||
if (bDate) {
|
if (bDate) {
|
||||||
if (current != null) {
|
if (current != null) {
|
||||||
current.setDate(characters.getData());
|
current.setDate(characters.getData());
|
||||||
}
|
}
|
||||||
bDate = false;
|
bDate = false;
|
||||||
}
|
}
|
||||||
if (bAuthor) {
|
if (bAuthor) {
|
||||||
if (current != null) {
|
if (current != null) {
|
||||||
current.setAuthor(characters.getData());
|
current.setAuthor(characters.getData());
|
||||||
}
|
}
|
||||||
bAuthor = false;
|
bAuthor = false;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case XMLStreamConstants.END_ELEMENT:
|
case XMLStreamConstants.END_ELEMENT:
|
||||||
EndElement endElement = event.asEndElement();
|
EndElement endElement = event.asEndElement();
|
||||||
if (endElement.getName().getLocalPart().equalsIgnoreCase("tutorial")) {
|
if (endElement.getName().getLocalPart().equalsIgnoreCase("tutorial")) {
|
||||||
if(current != null){
|
if (current != null) {
|
||||||
tutorials.add(current);
|
tutorials.add(current);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (FileNotFoundException | XMLStreamException e) {
|
} catch (FileNotFoundException | XMLStreamException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
return tutorials;
|
return tutorials;
|
||||||
}
|
}
|
||||||
|
|
||||||
public File getFile() {
|
public File getFile() {
|
||||||
return file;
|
return file;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFile(File file) {
|
public void setFile(File file) {
|
||||||
this.file = file;
|
this.file = file;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -5,55 +5,64 @@ import javax.xml.bind.annotation.XmlElement;
|
|||||||
|
|
||||||
public class Tutorial {
|
public class Tutorial {
|
||||||
|
|
||||||
private String tutId;
|
private String tutId;
|
||||||
private String type;
|
private String type;
|
||||||
private String title;
|
private String title;
|
||||||
private String description;
|
private String description;
|
||||||
private String date;
|
private String date;
|
||||||
private String author;
|
private String author;
|
||||||
|
|
||||||
|
public String getTutId() {
|
||||||
public String getTutId() {
|
return tutId;
|
||||||
return tutId;
|
}
|
||||||
}
|
|
||||||
|
@XmlAttribute
|
||||||
@XmlAttribute
|
public void setTutId(String tutId) {
|
||||||
public void setTutId(String tutId) {
|
this.tutId = tutId;
|
||||||
this.tutId = tutId;
|
}
|
||||||
}
|
|
||||||
public String getType() {
|
public String getType() {
|
||||||
return type;
|
return type;
|
||||||
}
|
}
|
||||||
@XmlAttribute
|
|
||||||
public void setType(String type) {
|
@XmlAttribute
|
||||||
this.type = type;
|
public void setType(String type) {
|
||||||
}
|
this.type = type;
|
||||||
public String getTitle() {
|
}
|
||||||
return title;
|
|
||||||
}
|
public String getTitle() {
|
||||||
@XmlElement
|
return title;
|
||||||
public void setTitle(String title) {
|
}
|
||||||
this.title = title;
|
|
||||||
}
|
@XmlElement
|
||||||
public String getDescription() {
|
public void setTitle(String title) {
|
||||||
return description;
|
this.title = title;
|
||||||
}
|
}
|
||||||
@XmlElement
|
|
||||||
public void setDescription(String description) {
|
public String getDescription() {
|
||||||
this.description = description;
|
return description;
|
||||||
}
|
}
|
||||||
public String getDate() {
|
|
||||||
return date;
|
@XmlElement
|
||||||
}
|
public void setDescription(String description) {
|
||||||
@XmlElement
|
this.description = description;
|
||||||
public void setDate(String date) {
|
}
|
||||||
this.date = date;
|
|
||||||
}
|
public String getDate() {
|
||||||
public String getAuthor() {
|
return date;
|
||||||
return author;
|
}
|
||||||
}
|
|
||||||
@XmlElement
|
@XmlElement
|
||||||
public void setAuthor(String author) {
|
public void setDate(String date) {
|
||||||
this.author = author;
|
this.date = date;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getAuthor() {
|
||||||
|
return author;
|
||||||
|
}
|
||||||
|
|
||||||
|
@XmlElement
|
||||||
|
public void setAuthor(String author) {
|
||||||
|
this.author = author;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,16 +8,15 @@ import javax.xml.bind.annotation.XmlRootElement;
|
|||||||
@XmlRootElement
|
@XmlRootElement
|
||||||
public class Tutorials {
|
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,7 @@ import org.w3c.dom.NodeList;
|
|||||||
public class DefaultParserUnitTest {
|
public class DefaultParserUnitTest {
|
||||||
|
|
||||||
final String fileName = "src/test/resources/example.xml";
|
final String fileName = "src/test/resources/example.xml";
|
||||||
|
|
||||||
final String fileNameSpace = "src/test/resources/example_namespace.xml";
|
final String fileNameSpace = "src/test/resources/example_namespace.xml";
|
||||||
|
|
||||||
DefaultParser parser;
|
DefaultParser parser;
|
||||||
@ -51,9 +51,9 @@ public class DefaultParserUnitTest {
|
|||||||
String type = node.getAttributes().getNamedItem("type").getNodeValue();
|
String type = node.getAttributes().getNamedItem("type").getNodeValue();
|
||||||
assertEquals("android", type);
|
assertEquals("android", type);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getNodeListByDateTest(){
|
public void getNodeListByDateTest() {
|
||||||
parser = new DefaultParser(new File(fileName));
|
parser = new DefaultParser(new File(fileName));
|
||||||
NodeList list = parser.getNodeListByTitle("04022016");
|
NodeList list = parser.getNodeListByTitle("04022016");
|
||||||
for (int i = 0; null != list && i < list.getLength(); i++) {
|
for (int i = 0; null != list && i < list.getLength(); i++) {
|
||||||
@ -68,9 +68,9 @@ public class DefaultParserUnitTest {
|
|||||||
assertEquals("SpringAuthor", nod.getLastChild().getTextContent());
|
assertEquals("SpringAuthor", nod.getLastChild().getTextContent());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getNodeListWithNamespaceTest(){
|
public void getNodeListWithNamespaceTest() {
|
||||||
parser = new DefaultParser(new File(fileNameSpace));
|
parser = new DefaultParser(new File(fileNameSpace));
|
||||||
NodeList list = parser.getAllTutorials();
|
NodeList list = parser.getAllTutorials();
|
||||||
assertNotNull(list);
|
assertNotNull(list);
|
||||||
|
@ -13,76 +13,76 @@ import org.junit.Test;
|
|||||||
|
|
||||||
public class Dom4JParserUnitTest {
|
public class Dom4JParserUnitTest {
|
||||||
|
|
||||||
final String fileName = "src/test/resources/example.xml";
|
final String fileName = "src/test/resources/example.xml";
|
||||||
|
|
||||||
Dom4JParser parser;
|
Dom4JParser parser;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getRootElementTest() {
|
public void getRootElementTest() {
|
||||||
parser = new Dom4JParser(new File(fileName));
|
parser = new Dom4JParser(new File(fileName));
|
||||||
Element root = parser.getRootElement();
|
Element root = parser.getRootElement();
|
||||||
|
|
||||||
assertNotNull(root);
|
assertNotNull(root);
|
||||||
assertTrue(root.elements().size() == 4);
|
assertTrue(root.elements().size() == 4);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getFirstElementListTest() {
|
public void getFirstElementListTest() {
|
||||||
parser = new Dom4JParser(new File(fileName));
|
parser = new Dom4JParser(new File(fileName));
|
||||||
List<Element> firstList = parser.getFirstElementList();
|
List<Element> firstList = parser.getFirstElementList();
|
||||||
|
|
||||||
assertNotNull(firstList);
|
assertNotNull(firstList);
|
||||||
assertTrue(firstList.size() == 4);
|
assertTrue(firstList.size() == 4);
|
||||||
assertTrue(firstList.get(0).attributeValue("type").equals("java"));
|
assertTrue(firstList.get(0).attributeValue("type").equals("java"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getElementByIdTest() {
|
public void getElementByIdTest() {
|
||||||
parser = new Dom4JParser(new File(fileName));
|
parser = new Dom4JParser(new File(fileName));
|
||||||
Node element = parser.getNodeById("03");
|
Node element = parser.getNodeById("03");
|
||||||
|
|
||||||
String type = element.valueOf("@type");
|
String type = element.valueOf("@type");
|
||||||
assertEquals("android", type);
|
assertEquals("android", type);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getElementsListByTitleTest() {
|
public void getElementsListByTitleTest() {
|
||||||
parser = new Dom4JParser(new File(fileName));
|
parser = new Dom4JParser(new File(fileName));
|
||||||
Node element = parser.getElementsListByTitle("XML");
|
Node element = parser.getElementsListByTitle("XML");
|
||||||
|
|
||||||
assertEquals("java", element.valueOf("@type"));
|
assertEquals("java", element.valueOf("@type"));
|
||||||
assertEquals("02", element.valueOf("@tutId"));
|
assertEquals("02", element.valueOf("@tutId"));
|
||||||
assertEquals("XML", element.selectSingleNode("title").getText());
|
assertEquals("XML", element.selectSingleNode("title").getText());
|
||||||
assertEquals("title", element.selectSingleNode("title").getName());
|
assertEquals("title", element.selectSingleNode("title").getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void generateModifiedDocumentTest() {
|
public void generateModifiedDocumentTest() {
|
||||||
parser = new Dom4JParser(new File(fileName));
|
parser = new Dom4JParser(new File(fileName));
|
||||||
parser.generateModifiedDocument();
|
parser.generateModifiedDocument();
|
||||||
|
|
||||||
File generatedFile = new File("src/test/resources/example_updated.xml");
|
File generatedFile = new File("src/test/resources/example_updated.xml");
|
||||||
assertTrue(generatedFile.exists());
|
assertTrue(generatedFile.exists());
|
||||||
|
|
||||||
parser.setFile(generatedFile);
|
parser.setFile(generatedFile);
|
||||||
Node element = parser.getNodeById("02");
|
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");
|
@Test
|
||||||
assertTrue(newFile.exists());
|
public void generateNewDocumentTest() {
|
||||||
|
parser = new Dom4JParser(new File(fileName));
|
||||||
|
parser.generateNewDocument();
|
||||||
|
|
||||||
parser.setFile(newFile);
|
File newFile = new File("src/test/resources/example_new.xml");
|
||||||
Node element = parser.getNodeById("01");
|
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());
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -11,28 +11,28 @@ import org.jdom2.Element;
|
|||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class JDomParserUnitTest {
|
public class JDomParserUnitTest {
|
||||||
|
|
||||||
final String fileName = "src/test/resources/example.xml";
|
|
||||||
|
|
||||||
JDomParser parser;
|
final String fileName = "src/test/resources/example.xml";
|
||||||
|
|
||||||
@Test
|
JDomParser parser;
|
||||||
public void getFirstElementListTest() {
|
|
||||||
parser = new JDomParser(new File(fileName));
|
@Test
|
||||||
List<Element> firstList = parser.getAllTitles();
|
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -11,34 +11,32 @@ import com.baeldung.xml.binding.Tutorials;
|
|||||||
|
|
||||||
public class JaxbParserUnitTest {
|
public class JaxbParserUnitTest {
|
||||||
|
|
||||||
|
final String fileName = "src/test/resources/example.xml";
|
||||||
final String fileName = "src/test/resources/example.xml";
|
|
||||||
|
|
||||||
JaxbParser parser;
|
JaxbParser parser;
|
||||||
|
|
||||||
@Test
|
|
||||||
public void getFullDocumentTest(){
|
|
||||||
parser = new JaxbParser(new File(fileName));
|
|
||||||
Tutorials tutorials = parser.getFullDocument();
|
|
||||||
|
|
||||||
assertNotNull(tutorials);
|
@Test
|
||||||
assertTrue(tutorials.getTutorial().size() == 4);
|
public void getFullDocumentTest() {
|
||||||
assertTrue(tutorials.getTutorial().get(0).getType().equalsIgnoreCase("java"));
|
parser = new JaxbParser(new File(fileName));
|
||||||
}
|
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(newFile.exists());
|
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(newFile.exists());
|
||||||
assertTrue(tutorials.getTutorial().size() == 1);
|
|
||||||
assertTrue(tutorials.getTutorial().get(0).getTitle().equalsIgnoreCase("XML with Jaxb"));
|
Tutorials tutorials = parser.getFullDocument();
|
||||||
}
|
|
||||||
|
assertNotNull(tutorials);
|
||||||
|
assertTrue(tutorials.getTutorial().size() == 1);
|
||||||
|
assertTrue(tutorials.getTutorial().get(0).getTitle().equalsIgnoreCase("XML with Jaxb"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -10,13 +10,13 @@ import org.junit.Test;
|
|||||||
|
|
||||||
public class JaxenDemoUnitTest {
|
public class JaxenDemoUnitTest {
|
||||||
|
|
||||||
final String fileName = "src/test/resources/example.xml";
|
final String fileName = "src/test/resources/example.xml";
|
||||||
|
|
||||||
JaxenDemo jaxenDemo;
|
JaxenDemo jaxenDemo;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getFirstLevelNodeListTest() {
|
public void getFirstLevelNodeListTest() {
|
||||||
jaxenDemo = new JaxenDemo(new File(fileName));
|
jaxenDemo = new JaxenDemo(new File(fileName));
|
||||||
List<?> list = jaxenDemo.getAllTutorial();
|
List<?> list = jaxenDemo.getAllTutorial();
|
||||||
|
|
||||||
assertNotNull(list);
|
assertNotNull(list);
|
||||||
|
@ -12,17 +12,17 @@ import com.baeldung.xml.binding.Tutorial;
|
|||||||
|
|
||||||
public class StaxParserUnitTest {
|
public class StaxParserUnitTest {
|
||||||
|
|
||||||
final String fileName = "src/test/resources/example.xml";
|
final String fileName = "src/test/resources/example.xml";
|
||||||
|
|
||||||
StaxParser parser;
|
StaxParser parser;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getAllTutorialsTest(){
|
public void getAllTutorialsTest() {
|
||||||
parser = new StaxParser(new File(fileName));
|
parser = new StaxParser(new File(fileName));
|
||||||
List<Tutorial> tutorials = parser.getAllTutorial();
|
List<Tutorial> tutorials = parser.getAllTutorial();
|
||||||
|
|
||||||
assertNotNull(tutorials);
|
assertNotNull(tutorials);
|
||||||
assertTrue(tutorials.size() == 4);
|
assertTrue(tutorials.size() == 4);
|
||||||
assertTrue(tutorials.get(0).getType().equalsIgnoreCase("java"));
|
assertTrue(tutorials.get(0).getType().equalsIgnoreCase("java"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,24 +8,23 @@ import org.xmlunit.diff.DifferenceEvaluator;
|
|||||||
|
|
||||||
public class IgnoreAttributeDifferenceEvaluator implements DifferenceEvaluator {
|
public class IgnoreAttributeDifferenceEvaluator implements DifferenceEvaluator {
|
||||||
|
|
||||||
private String attributeName;
|
private String attributeName;
|
||||||
|
|
||||||
public IgnoreAttributeDifferenceEvaluator(String attributeName) {
|
public IgnoreAttributeDifferenceEvaluator(String attributeName) {
|
||||||
this.attributeName = attributeName;
|
this.attributeName = attributeName;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ComparisonResult evaluate(Comparison comparison,
|
public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) {
|
||||||
ComparisonResult outcome) {
|
if (outcome == ComparisonResult.EQUAL)
|
||||||
if (outcome == ComparisonResult.EQUAL)
|
return outcome;
|
||||||
return outcome;
|
final Node controlNode = comparison.getControlDetails().getTarget();
|
||||||
final Node controlNode = comparison.getControlDetails().getTarget();
|
if (controlNode instanceof Attr) {
|
||||||
if (controlNode instanceof Attr) {
|
Attr attr = (Attr) controlNode;
|
||||||
Attr attr = (Attr) controlNode;
|
if (attr.getName().equals(attributeName)) {
|
||||||
if (attr.getName().equals(attributeName)) {
|
return ComparisonResult.SIMILAR;
|
||||||
return ComparisonResult.SIMILAR;
|
}
|
||||||
}
|
}
|
||||||
}
|
return outcome;
|
||||||
return outcome;
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -26,98 +26,78 @@ import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
|
|||||||
import static org.xmlunit.matchers.HasXPathMatcher.hasXPath;
|
import static org.xmlunit.matchers.HasXPathMatcher.hasXPath;
|
||||||
|
|
||||||
public class XMLUnitTest {
|
public class XMLUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void givenWrongXml_whenValidateFailsAgainstXsd_thenCorrect() {
|
public void givenWrongXml_whenValidateFailsAgainstXsd_thenCorrect() {
|
||||||
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
|
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
|
||||||
v.setSchemaSource(Input.fromStream(
|
v.setSchemaSource(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students.xsd")).build());
|
||||||
XMLUnitTest.class.getResourceAsStream(
|
ValidationResult r = v.validateInstance(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students_with_error.xml")).build());
|
||||||
"/students.xsd")).build());
|
assertFalse(r.isValid());
|
||||||
ValidationResult r = v.validateInstance(Input.fromStream(
|
}
|
||||||
XMLUnitTest.class.getResourceAsStream(
|
|
||||||
"/students_with_error.xml")).build());
|
|
||||||
assertFalse(r.isValid());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenXmlWithErrors_whenReturnsValidationProblems_thenCorrect() {
|
public void givenXmlWithErrors_whenReturnsValidationProblems_thenCorrect() {
|
||||||
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
|
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
|
||||||
v.setSchemaSource(Input.fromStream(
|
v.setSchemaSource(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students.xsd")).build());
|
||||||
XMLUnitTest.class.getResourceAsStream(
|
ValidationResult r = v.validateInstance(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students_with_error.xml")).build());
|
||||||
"/students.xsd")).build());
|
Iterator<ValidationProblem> probs = r.getProblems().iterator();
|
||||||
ValidationResult r = v.validateInstance(Input.fromStream(
|
int count = 0;
|
||||||
XMLUnitTest.class.getResourceAsStream(
|
while (probs.hasNext()) {
|
||||||
"/students_with_error.xml")).build());
|
count++;
|
||||||
Iterator<ValidationProblem> probs = r.getProblems().iterator();
|
probs.next().toString();
|
||||||
int count = 0;
|
}
|
||||||
while (probs.hasNext()) {
|
assertTrue(count > 0);
|
||||||
count++;
|
}
|
||||||
probs.next().toString();
|
|
||||||
}
|
|
||||||
assertTrue(count > 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenXml_whenValidatesAgainstXsd_thenCorrect() {
|
public void givenXml_whenValidatesAgainstXsd_thenCorrect() {
|
||||||
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
|
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
|
||||||
v.setSchemaSource(Input.fromStream(
|
v.setSchemaSource(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students.xsd")).build());
|
||||||
XMLUnitTest.class.getResourceAsStream(
|
ValidationResult r = v.validateInstance(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students.xml")).build());
|
||||||
"/students.xsd")).build());
|
Iterator<ValidationProblem> probs = r.getProblems().iterator();
|
||||||
ValidationResult r = v.validateInstance(Input.fromStream(
|
while (probs.hasNext()) {
|
||||||
XMLUnitTest.class.getResourceAsStream(
|
System.out.println(probs.next().toString());
|
||||||
"/students.xml")).build());
|
}
|
||||||
Iterator<ValidationProblem> probs = r.getProblems().iterator();
|
assertTrue(r.isValid());
|
||||||
while (probs.hasNext()) {
|
}
|
||||||
System.out.println(probs.next().toString());
|
|
||||||
}
|
|
||||||
assertTrue(r.isValid());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenXPath_whenAbleToRetrieveNodes_thenCorrect() {
|
public void givenXPath_whenAbleToRetrieveNodes_thenCorrect() {
|
||||||
ClassLoader classLoader = getClass().getClassLoader();
|
ClassLoader classLoader = getClass().getClassLoader();
|
||||||
|
|
||||||
Iterable<Node> i = new JAXPXPathEngine().selectNodes(
|
Iterable<Node> i = new JAXPXPathEngine().selectNodes("//teacher", Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())).build());
|
||||||
"//teacher",
|
assertNotNull(i);
|
||||||
Input.fromFile(
|
int count = 0;
|
||||||
new File(classLoader.getResource("teachers.xml")
|
for (Iterator<Node> it = i.iterator(); it.hasNext();) {
|
||||||
.getFile())).build());
|
count++;
|
||||||
assertNotNull(i);
|
Node node = it.next();
|
||||||
int count = 0;
|
assertEquals("teacher", node.getNodeName());
|
||||||
for (Iterator<Node> it = i.iterator(); it.hasNext();) {
|
NamedNodeMap map = node.getAttributes();
|
||||||
count++;
|
assertEquals("department", map.item(0).getNodeName());
|
||||||
Node node = it.next();
|
assertEquals("id", map.item(1).getNodeName());
|
||||||
assertEquals("teacher", node.getNodeName());
|
assertEquals("teacher", node.getNodeName());
|
||||||
NamedNodeMap map = node.getAttributes();
|
}
|
||||||
assertEquals("department", map.item(0).getNodeName());
|
assertEquals(2, count);
|
||||||
assertEquals("id", map.item(1).getNodeName());
|
}
|
||||||
assertEquals("teacher", node.getNodeName());
|
|
||||||
}
|
|
||||||
assertEquals(2, count);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenXmlSource_whenAbleToValidateExistingXPath_thenCorrect() {
|
public void givenXmlSource_whenAbleToValidateExistingXPath_thenCorrect() {
|
||||||
ClassLoader classLoader = getClass().getClassLoader();
|
ClassLoader classLoader = getClass().getClassLoader();
|
||||||
assertThat(Input.fromFile(new File(classLoader.getResource(
|
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), hasXPath("//teachers"));
|
||||||
"teachers.xml").getFile())), hasXPath("//teachers"));
|
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), hasXPath("//teacher"));
|
||||||
assertThat(Input.fromFile(new File(classLoader.getResource(
|
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), hasXPath("//subject"));
|
||||||
"teachers.xml").getFile())), hasXPath("//teacher"));
|
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), hasXPath("//@department"));
|
||||||
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
|
@Test
|
||||||
public void givenXmlSource_whenFailsToValidateInExistentXPath_thenCorrect() {
|
public void givenXmlSource_whenFailsToValidateInExistentXPath_thenCorrect() {
|
||||||
ClassLoader classLoader = getClass().getClassLoader();
|
ClassLoader classLoader = getClass().getClassLoader();
|
||||||
assertThat(Input.fromFile(new File(classLoader.getResource(
|
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), not(hasXPath("//sujet")));
|
||||||
"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.
|
// will fail the isSimilarTo test.
|
||||||
@Test @Ignore
|
@Test
|
||||||
|
@Ignore
|
||||||
public void given2XMLS_whenSimilar_thenCorrect_fails() {
|
public void given2XMLS_whenSimilar_thenCorrect_fails() {
|
||||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||||
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||||
@ -128,168 +108,135 @@ public class XMLUnitTest {
|
|||||||
public void given2XMLS_whenSimilar_thenCorrect() {
|
public void given2XMLS_whenSimilar_thenCorrect() {
|
||||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||||
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||||
assertThat(testXml,isSimilarTo(controlXml).withNodeMatcher(
|
assertThat(testXml, isSimilarTo(controlXml).withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)));
|
||||||
new DefaultNodeMatcher(ElementSelectors.byName)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void given2XMLs_whenSimilarWithDiff_thenCorrect() throws Exception {
|
public void given2XMLs_whenSimilarWithDiff_thenCorrect() throws Exception {
|
||||||
String myControlXML = "<struct><int>3</int><boolean>false</boolean></struct>";
|
String myControlXML = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||||
String myTestXML = "<struct><boolean>false</boolean><int>3</int></struct>";
|
String myTestXML = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||||
|
|
||||||
Diff myDiffSimilar = DiffBuilder
|
Diff myDiffSimilar = DiffBuilder.compare(myControlXML).withTest(myTestXML).withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)).checkForSimilar().build();
|
||||||
.compare(myControlXML)
|
assertFalse("XML similar " + myDiffSimilar.toString(), myDiffSimilar.hasDifferences());
|
||||||
.withTest(myTestXML)
|
|
||||||
.withNodeMatcher(
|
|
||||||
new DefaultNodeMatcher(ElementSelectors.byName))
|
|
||||||
.checkForSimilar().build();
|
|
||||||
assertFalse("XML similar " + myDiffSimilar.toString(),
|
|
||||||
myDiffSimilar.hasDifferences());
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void given2XMLsWithDifferences_whenTestsSimilarWithDifferenceEvaluator_thenCorrect() {
|
public void given2XMLsWithDifferences_whenTestsSimilarWithDifferenceEvaluator_thenCorrect() {
|
||||||
final String control = "<a><b attr=\"abc\"></b></a>";
|
final String control = "<a><b attr=\"abc\"></b></a>";
|
||||||
final String test = "<a><b attr=\"xyz\"></b></a>";
|
final String test = "<a><b attr=\"xyz\"></b></a>";
|
||||||
Diff myDiff = DiffBuilder
|
Diff myDiff = DiffBuilder.compare(control).withTest(test).withDifferenceEvaluator(new IgnoreAttributeDifferenceEvaluator("attr")).checkForSimilar().build();
|
||||||
.compare(control)
|
|
||||||
.withTest(test)
|
|
||||||
.withDifferenceEvaluator(
|
|
||||||
new IgnoreAttributeDifferenceEvaluator("attr"))
|
|
||||||
.checkForSimilar().build();
|
|
||||||
|
|
||||||
assertFalse(myDiff.toString(), myDiff.hasDifferences());
|
assertFalse(myDiff.toString(), myDiff.hasDifferences());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void given2XMLsWithDifferences_whenTestsDifferentWithoutDifferenceEvaluator_thenCorrect() {
|
public void given2XMLsWithDifferences_whenTestsDifferentWithoutDifferenceEvaluator_thenCorrect() {
|
||||||
final String control = "<a><b attr=\"abc\"></b></a>";
|
final String control = "<a><b attr=\"abc\"></b></a>";
|
||||||
final String test = "<a><b attr=\"xyz\"></b></a>";
|
final String test = "<a><b attr=\"xyz\"></b></a>";
|
||||||
|
|
||||||
Diff myDiff = DiffBuilder.compare(control).withTest(test)
|
Diff myDiff = DiffBuilder.compare(control).withTest(test).checkForSimilar().build();
|
||||||
.checkForSimilar().build();
|
|
||||||
|
|
||||||
// assertFalse(myDiff.toString(), myDiff.hasDifferences());
|
// assertFalse(myDiff.toString(), myDiff.hasDifferences());
|
||||||
assertTrue(myDiff.toString(), myDiff.hasDifferences());
|
assertTrue(myDiff.toString(), myDiff.hasDifferences());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void given2XMLS_whenSimilarWithCustomElementSelector_thenCorrect() {
|
public void given2XMLS_whenSimilarWithCustomElementSelector_thenCorrect() {
|
||||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||||
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||||
assertThat(
|
assertThat(testXml, isSimilarTo(controlXml).withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)));
|
||||||
testXml,
|
|
||||||
isSimilarTo(controlXml).withNodeMatcher(
|
|
||||||
new DefaultNodeMatcher(ElementSelectors.byName)));
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFileSourceAsObject_whenAbleToInput_thenCorrect() {
|
public void givenFileSourceAsObject_whenAbleToInput_thenCorrect() {
|
||||||
ClassLoader classLoader = getClass().getClassLoader();
|
ClassLoader classLoader = getClass().getClassLoader();
|
||||||
assertThat(Input.from(new File(classLoader.getResource("test.xml").getFile())),
|
assertThat(Input.from(new File(classLoader.getResource("test.xml").getFile())), isSimilarTo(Input.from(new File(classLoader.getResource("control.xml").getFile()))));
|
||||||
isSimilarTo(Input.from(new File(classLoader.getResource("control.xml").getFile()))));
|
}
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStreamAsSource_whenAbleToInput_thenCorrect() {
|
public void givenStreamAsSource_whenAbleToInput_thenCorrect() {
|
||||||
assertThat(Input.fromStream(XMLUnitTest.class
|
assertThat(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/test.xml")), isSimilarTo(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/control.xml"))));
|
||||||
.getResourceAsStream("/test.xml")),
|
|
||||||
isSimilarTo(Input.fromStream(XMLUnitTest.class
|
|
||||||
.getResourceAsStream("/control.xml"))));
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStreamAsObject_whenAbleToInput_thenCorrect() {
|
public void givenStreamAsObject_whenAbleToInput_thenCorrect() {
|
||||||
assertThat(Input.from(XMLUnitTest.class.getResourceAsStream("/test.xml")),
|
assertThat(Input.from(XMLUnitTest.class.getResourceAsStream("/test.xml")), isSimilarTo(Input.from(XMLUnitTest.class.getResourceAsStream("/control.xml"))));
|
||||||
isSimilarTo(Input.from(XMLUnitTest.class.getResourceAsStream("/control.xml"))));
|
}
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStringSourceAsObject_whenAbleToInput_thenCorrect() {
|
public void givenStringSourceAsObject_whenAbleToInput_thenCorrect() {
|
||||||
assertThat(
|
assertThat(Input.from("<struct><int>3</int><boolean>false</boolean></struct>"), isSimilarTo(Input.from("<struct><int>3</int><boolean>false</boolean></struct>")));
|
||||||
Input.from("<struct><int>3</int><boolean>false</boolean></struct>"),
|
}
|
||||||
isSimilarTo(Input
|
|
||||||
.from("<struct><int>3</int><boolean>false</boolean></struct>")));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFileSource_whenAbleToInput_thenCorrect() {
|
public void givenFileSource_whenAbleToInput_thenCorrect() {
|
||||||
ClassLoader classLoader = getClass().getClassLoader();
|
ClassLoader classLoader = getClass().getClassLoader();
|
||||||
String testPath = classLoader.getResource("test.xml").getPath();
|
String testPath = classLoader.getResource("test.xml").getPath();
|
||||||
String controlPath = classLoader.getResource("control.xml").getPath();
|
String controlPath = classLoader.getResource("control.xml").getPath();
|
||||||
assertThat(Input.fromFile(testPath),
|
assertThat(Input.fromFile(testPath), isSimilarTo(Input.fromFile(controlPath)));
|
||||||
isSimilarTo(Input.fromFile(controlPath)));
|
}
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStringSource_whenAbleToInput_thenCorrect() {
|
public void givenStringSource_whenAbleToInput_thenCorrect() {
|
||||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||||
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||||
assertThat(Input.fromString(testXml),
|
assertThat(Input.fromString(testXml), isSimilarTo(Input.fromString(controlXml)));
|
||||||
isSimilarTo(Input.fromString(controlXml)));
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenSource_whenAbleToInput_thenCorrect() {
|
public void givenSource_whenAbleToInput_thenCorrect() {
|
||||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||||
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||||
assertThat(Input.fromString(testXml),
|
assertThat(Input.fromString(testXml), isSimilarTo(Input.fromString(controlXml)));
|
||||||
isSimilarTo(Input.fromString(controlXml)));
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void given2XMLS_whenIdentical_thenCorrect() {
|
public void given2XMLS_whenIdentical_thenCorrect() {
|
||||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||||
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||||
assertThat(testXml, isIdenticalTo(controlXml));
|
assertThat(testXml, isIdenticalTo(controlXml));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void given2XMLSWithSimilarNodesButDifferentSequence_whenNotIdentical_thenCorrect() {
|
public void given2XMLSWithSimilarNodesButDifferentSequence_whenNotIdentical_thenCorrect() {
|
||||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||||
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||||
assertThat(testXml, not(isIdenticalTo(controlXml)));
|
assertThat(testXml, not(isIdenticalTo(controlXml)));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void given2XMLS_whenGeneratesDifferences_thenCorrect()
|
public void given2XMLS_whenGeneratesDifferences_thenCorrect() throws Exception {
|
||||||
throws Exception {
|
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||||
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
Diff myDiff = DiffBuilder.compare(controlXml).withTest(testXml).build();
|
||||||
Diff myDiff = DiffBuilder.compare(controlXml).withTest(testXml).build();
|
Iterator<Difference> iter = myDiff.getDifferences().iterator();
|
||||||
Iterator<Difference> iter = myDiff.getDifferences().iterator();
|
int size = 0;
|
||||||
int size = 0;
|
while (iter.hasNext()) {
|
||||||
while (iter.hasNext()) {
|
iter.next().toString();
|
||||||
iter.next().toString();
|
size++;
|
||||||
size++;
|
}
|
||||||
}
|
assertThat(size, greaterThan(1));
|
||||||
assertThat(size, greaterThan(1));
|
}
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void given2XMLS_whenGeneratesOneDifference_thenCorrect()
|
public void given2XMLS_whenGeneratesOneDifference_thenCorrect() throws Exception {
|
||||||
throws Exception {
|
String myControlXML = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||||
String myControlXML = "<struct><int>3</int><boolean>false</boolean></struct>";
|
String myTestXML = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||||
String myTestXML = "<struct><boolean>false</boolean><int>3</int></struct>";
|
Diff myDiff = DiffBuilder.compare(myControlXML).withTest(myTestXML).withComparisonController(ComparisonControllers.StopWhenDifferent).build();
|
||||||
Diff myDiff = DiffBuilder
|
Iterator<Difference> iter = myDiff.getDifferences().iterator();
|
||||||
.compare(myControlXML)
|
int size = 0;
|
||||||
.withTest(myTestXML)
|
while (iter.hasNext()) {
|
||||||
.withComparisonController(
|
iter.next().toString();
|
||||||
ComparisonControllers.StopWhenDifferent).build();
|
size++;
|
||||||
Iterator<Difference> iter = myDiff.getDifferences().iterator();
|
}
|
||||||
int size = 0;
|
assertThat(size, equalTo(1));
|
||||||
while (iter.hasNext()) {
|
}
|
||||||
iter.next().toString();
|
|
||||||
size++;
|
|
||||||
}
|
|
||||||
assertThat(size, equalTo(1));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -40,7 +40,6 @@ public class Customer {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Customer [firstName=" + firstName + ", lastName=" + lastName
|
return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]";
|
||||||
+ ", dob=" + dob + "]";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,7 +5,6 @@ import com.thoughtworks.xstream.annotations.XStreamOmitField;
|
|||||||
|
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
|
|
||||||
@XStreamAlias("customer")
|
@XStreamAlias("customer")
|
||||||
public class CustomerOmitField {
|
public class CustomerOmitField {
|
||||||
|
|
||||||
@ -42,9 +41,7 @@ public class CustomerOmitField {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "CustomerOmitAnnotation [firstName=" + firstName + ", lastName="
|
return "CustomerOmitAnnotation [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]";
|
||||||
+ lastName + ", dob=" + dob + "]";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -39,8 +39,7 @@ public class ContactDetails {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "ContactDetails [mobile=" + mobile + ", landline=" + landline
|
return "ContactDetails [mobile=" + mobile + ", landline=" + landline + ", contactType=" + contactType + "]";
|
||||||
+ ", contactType=" + contactType + "]";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -50,8 +50,6 @@ public class Customer {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Customer [firstName=" + firstName + ", lastName=" + lastName
|
return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList + "]";
|
||||||
+ ", dob=" + dob + ", contactDetailsList=" + contactDetailsList
|
|
||||||
+ "]";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -39,8 +39,7 @@ public class ContactDetails {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "ContactDetails [mobile=" + mobile + ", landline=" + landline
|
return "ContactDetails [mobile=" + mobile + ", landline=" + landline + ", contactType=" + contactType + "]";
|
||||||
+ ", contactType=" + contactType + "]";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -52,8 +52,6 @@ public class Customer {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Customer [firstName=" + firstName + ", lastName=" + lastName
|
return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList + "]";
|
||||||
+ ", dob=" + dob + ", contactDetailsList=" + contactDetailsList
|
|
||||||
+ "]";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -39,7 +39,6 @@ public class CustomerAddressDetails {
|
|||||||
this.age = age;
|
this.age = age;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public List<AddressDetails> getAddressDetails() {
|
public List<AddressDetails> getAddressDetails() {
|
||||||
return addressDetails;
|
return addressDetails;
|
||||||
}
|
}
|
||||||
|
@ -29,7 +29,7 @@ public class ComplexXmlToObjectCollectionTest {
|
|||||||
Customer customer = (Customer) xstream.fromXML(reader);
|
Customer customer = (Customer) xstream.fromXML(reader);
|
||||||
Assert.assertNotNull(customer);
|
Assert.assertNotNull(customer);
|
||||||
Assert.assertNotNull(customer.getContactDetailsList());
|
Assert.assertNotNull(customer.getContactDetailsList());
|
||||||
//System.out.println(customer);
|
// System.out.println(customer);
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
|
@ -29,7 +29,7 @@ public class XmlToObjectIgnoreFieldsTest {
|
|||||||
FileReader reader = new FileReader(classLoader.getResource("data-file-ignore-field.xml").getFile());
|
FileReader reader = new FileReader(classLoader.getResource("data-file-ignore-field.xml").getFile());
|
||||||
Customer customer = (Customer) xstream.fromXML(reader);
|
Customer customer = (Customer) xstream.fromXML(reader);
|
||||||
Assert.assertNotNull(customer);
|
Assert.assertNotNull(customer);
|
||||||
//System.out.println(customer);
|
// System.out.println(customer);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
@ -42,5 +42,4 @@ public class XmlToObjectTest {
|
|||||||
Assert.assertNotNull(convertedCustomer);
|
Assert.assertNotNull(convertedCustomer);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user