formatting work

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

View File

@ -11,7 +11,7 @@ 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

View File

@ -29,7 +29,6 @@ public class SpringController {
carList.add(new Car("Nissan", "Altima")); carList.add(new Car("Nissan", "Altima"));
} }
@RequestMapping(value = "/cars", method = RequestMethod.GET) @RequestMapping(value = "/cars", method = RequestMethod.GET)
public String init(@ModelAttribute("model") ModelMap model) { public String init(@ModelAttribute("model") ModelMap model) {
model.addAttribute("carList", carList); model.addAttribute("carList", carList);
@ -38,8 +37,7 @@ public class SpringController {
@RequestMapping(value = "/add", method = RequestMethod.POST) @RequestMapping(value = "/add", method = RequestMethod.POST)
public String addCar(@ModelAttribute("car") Car car) { public String addCar(@ModelAttribute("car") Car car) {
if (null != car && null != car.getMake() && null != car.getModel() if (null != car && null != car.getMake() && null != car.getModel() && !car.getMake().isEmpty() && !car.getModel().isEmpty()) {
&& !car.getMake().isEmpty() && !car.getModel().isEmpty()) {
carList.add(car); carList.add(car);
} }
return "redirect:/cars"; return "redirect:/cars";

View File

@ -5,7 +5,7 @@ public class Car {
private String make; private String make;
private String model; private String model;
public Car(){ public Car() {
} }

View File

@ -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);
} }
} }

View File

@ -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() {

View File

@ -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);

View File

@ -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

View File

@ -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);
} }
} }

View File

@ -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) {

View File

@ -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);
} }

View File

@ -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();

View File

@ -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);

View File

@ -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();

View File

@ -22,11 +22,9 @@ public class AsyncController {
@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: " log.info("Inside the @Async logic - after the async call: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
+ SecurityContextHolder.getContext().getAuthentication().getPrincipal());
return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
} }

View File

@ -20,14 +20,12 @@ public class AsyncServiceImpl implements AsyncService {
@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;
} }

View File

@ -22,7 +22,7 @@ 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

View File

@ -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();
} }
} }

View File

@ -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
} }
} }

View File

@ -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;

View File

@ -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";

View File

@ -34,7 +34,7 @@ public class MyUserService {
return user; return user;
} }
public void removeUserByUsername(String username){ public void removeUserByUsername(String username) {
myUserDAO.removeUserByUsername(username); myUserDAO.removeUserByUsername(username);
} }

View File

@ -60,7 +60,7 @@ public class CustomUserDetailsServiceIntegrationTest {
} }
} }
@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);
} }
} }

View File

@ -61,8 +61,7 @@ public class Dom4JParser {
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();

View File

@ -12,7 +12,6 @@ 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;
@ -45,7 +44,7 @@ public class JDomParser {
List<Element> node = expr.evaluate(document); List<Element> node = expr.evaluate(document);
return node.get(0); return node.get(0);
} catch (JDOMException | IOException e ) { } catch (JDOMException | IOException e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }

View File

@ -23,7 +23,7 @@ public class JaxenDemo {
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();
@ -53,5 +53,4 @@ public class JaxenDemo {
this.file = file; this.file = file;
} }
} }

View File

@ -94,7 +94,7 @@ public class StaxParser {
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);
} }
} }

View File

@ -12,7 +12,6 @@ public class Tutorial {
private String date; private String date;
private String author; private String author;
public String getTutId() { public String getTutId() {
return tutId; return tutId;
} }
@ -21,37 +20,47 @@ public class Tutorial {
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 @XmlAttribute
public void setType(String type) { public void setType(String type) {
this.type = type; this.type = type;
} }
public String getTitle() { public String getTitle() {
return title; return title;
} }
@XmlElement @XmlElement
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
@XmlElement @XmlElement
public void setDescription(String description) { public void setDescription(String description) {
this.description = description; this.description = description;
} }
public String getDate() { public String getDate() {
return date; return date;
} }
@XmlElement @XmlElement
public void setDate(String date) { public void setDate(String date) {
this.date = date; this.date = date;
} }
public String getAuthor() { public String getAuthor() {
return author; return author;
} }
@XmlElement @XmlElement
public void setAuthor(String author) { public void setAuthor(String author) {
this.author = author; this.author = author;

View File

@ -19,5 +19,4 @@ public class Tutorials {
this.tutorial = tutorial; this.tutorial = tutorial;
} }
} }

View File

@ -53,7 +53,7 @@ public class DefaultParserUnitTest {
} }
@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++) {
@ -70,7 +70,7 @@ public class DefaultParserUnitTest {
} }
@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);

View File

@ -11,13 +11,12 @@ 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 @Test
public void getFullDocumentTest(){ public void getFullDocumentTest() {
parser = new JaxbParser(new File(fileName)); parser = new JaxbParser(new File(fileName));
Tutorials tutorials = parser.getFullDocument(); Tutorials tutorials = parser.getFullDocument();
@ -27,12 +26,11 @@ public class JaxbParserUnitTest {
} }
@Test @Test
public void createNewDocumentTest(){ public void createNewDocumentTest() {
File newFile = new File("src/test/resources/example_new.xml"); File newFile = new File("src/test/resources/example_new.xml");
parser = new JaxbParser(newFile); parser = new JaxbParser(newFile);
parser.createNewDocument(); parser.createNewDocument();
assertTrue(newFile.exists()); assertTrue(newFile.exists());
Tutorials tutorials = parser.getFullDocument(); Tutorials tutorials = parser.getFullDocument();

View File

@ -17,7 +17,7 @@ public class StaxParserUnitTest {
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();

View File

@ -15,8 +15,7 @@ public class IgnoreAttributeDifferenceEvaluator implements DifferenceEvaluator {
} }
@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();

View File

@ -29,24 +29,16 @@ 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());
ValidationResult r = v.validateInstance(Input.fromStream(
XMLUnitTest.class.getResourceAsStream(
"/students_with_error.xml")).build());
assertFalse(r.isValid()); 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());
ValidationResult r = v.validateInstance(Input.fromStream(
XMLUnitTest.class.getResourceAsStream(
"/students_with_error.xml")).build());
Iterator<ValidationProblem> probs = r.getProblems().iterator(); Iterator<ValidationProblem> probs = r.getProblems().iterator();
int count = 0; int count = 0;
while (probs.hasNext()) { while (probs.hasNext()) {
@ -59,12 +51,8 @@ public class XMLUnitTest {
@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());
ValidationResult r = v.validateInstance(Input.fromStream(
XMLUnitTest.class.getResourceAsStream(
"/students.xml")).build());
Iterator<ValidationProblem> probs = r.getProblems().iterator(); Iterator<ValidationProblem> probs = r.getProblems().iterator();
while (probs.hasNext()) { while (probs.hasNext()) {
System.out.println(probs.next().toString()); System.out.println(probs.next().toString());
@ -76,11 +64,7 @@ public class XMLUnitTest {
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",
Input.fromFile(
new File(classLoader.getResource("teachers.xml")
.getFile())).build());
assertNotNull(i); assertNotNull(i);
int count = 0; int count = 0;
for (Iterator<Node> it = i.iterator(); it.hasNext();) { for (Iterator<Node> it = i.iterator(); it.hasNext();) {
@ -98,26 +82,22 @@ public class XMLUnitTest {
@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,8 +108,7 @@ 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
@ -137,14 +116,8 @@ public class XMLUnitTest {
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());
} }
@ -152,12 +125,7 @@ public class XMLUnitTest {
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());
} }
@ -167,8 +135,7 @@ public class XMLUnitTest {
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());
@ -178,41 +145,30 @@ public class XMLUnitTest {
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
@ -220,16 +176,14 @@ public class XMLUnitTest {
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)));
} }
@ -237,8 +191,7 @@ public class XMLUnitTest {
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)));
} }
@ -259,8 +212,7 @@ public class XMLUnitTest {
} }
@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();
@ -274,15 +226,10 @@ public class XMLUnitTest {
} }
@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 Diff myDiff = DiffBuilder.compare(myControlXML).withTest(myTestXML).withComparisonController(ComparisonControllers.StopWhenDifferent).build();
.compare(myControlXML)
.withTest(myTestXML)
.withComparisonController(
ComparisonControllers.StopWhenDifferent).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()) {

View File

@ -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 + "]";
} }
} }

View File

@ -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 + "]";
} }
} }

View File

@ -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 + "]";
} }
} }

View File

@ -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
+ "]";
} }
} }

View File

@ -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 + "]";
} }
} }

View File

@ -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
+ "]";
} }
} }

View File

@ -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;
} }

View File

@ -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();

View File

@ -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();
} }

View File

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