formatting work
This commit is contained in:
parent
034cde6e20
commit
966e53a85b
@ -11,7 +11,7 @@ import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
|
||||
|
||||
@EnableWebMvc
|
||||
@Configuration
|
||||
@ComponentScan({"com.baeldung.freemarker"})
|
||||
@ComponentScan({ "com.baeldung.freemarker" })
|
||||
public class SpringWebConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
|
@ -29,7 +29,6 @@ public class SpringController {
|
||||
carList.add(new Car("Nissan", "Altima"));
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(value = "/cars", method = RequestMethod.GET)
|
||||
public String init(@ModelAttribute("model") ModelMap model) {
|
||||
model.addAttribute("carList", carList);
|
||||
@ -38,8 +37,7 @@ public class SpringController {
|
||||
|
||||
@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()) {
|
||||
if (null != car && null != car.getMake() && null != car.getModel() && !car.getMake().isEmpty() && !car.getModel().isEmpty()) {
|
||||
carList.add(car);
|
||||
}
|
||||
return "redirect:/cars";
|
||||
|
@ -5,7 +5,7 @@ public class Car {
|
||||
private String make;
|
||||
private String model;
|
||||
|
||||
public Car(){
|
||||
public Car() {
|
||||
|
||||
}
|
||||
|
||||
|
@ -19,21 +19,13 @@ public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAda
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.inMemoryAuthentication()
|
||||
.withUser("user1").password("user1Pass")
|
||||
.authorities("ROLE_USER");
|
||||
auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests()
|
||||
.antMatchers("/securityNone").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.httpBasic()
|
||||
.authenticationEntryPoint(authenticationEntryPoint);
|
||||
http.authorizeRequests().antMatchers("/securityNone").permitAll().anyRequest().authenticated().and().httpBasic().authenticationEntryPoint(authenticationEntryPoint);
|
||||
|
||||
http.addFilterAfter(new CustomFilter(),
|
||||
BasicAuthenticationFilter.class);
|
||||
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
|
||||
}
|
||||
}
|
||||
|
@ -5,7 +5,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("org.baeldung.security")
|
||||
//@ImportResource({ "classpath:webSecurityConfig.xml" })
|
||||
// @ImportResource({ "classpath:webSecurityConfig.xml" })
|
||||
public class SecSecurityConfig {
|
||||
|
||||
public SecSecurityConfig() {
|
||||
|
@ -9,8 +9,7 @@ import org.springframework.context.annotation.FilterType;
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan(excludeFilters =
|
||||
@ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.voter.*"))
|
||||
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.voter.*"))
|
||||
public class Application extends SpringBootServletInitializer {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
|
@ -15,7 +15,7 @@ import javax.persistence.ManyToOne;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name="user_table")
|
||||
@Table(name = "user_table")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
|
@ -21,13 +21,6 @@ public class MinuteBasedVoter implements AccessDecisionVoter {
|
||||
|
||||
@Override
|
||||
public int vote(Authentication authentication, Object object, Collection collection) {
|
||||
return authentication
|
||||
.getAuthorities()
|
||||
.stream()
|
||||
.map(GrantedAuthority::getAuthority)
|
||||
.filter(r -> "ROLE_USER".equals(r) && LocalDateTime.now().getMinute() % 2 != 0)
|
||||
.findAny()
|
||||
.map(s -> ACCESS_DENIED)
|
||||
.orElseGet(() -> ACCESS_ABSTAIN);
|
||||
return authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).filter(r -> "ROLE_USER".equals(r) && LocalDateTime.now().getMinute() % 2 != 0).findAny().map(s -> ACCESS_DENIED).orElseGet(() -> ACCESS_ABSTAIN);
|
||||
}
|
||||
}
|
||||
|
@ -8,7 +8,7 @@ import org.springframework.context.annotation.FilterType;
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan(basePackages = {"org.baeldung.voter"})
|
||||
@ComponentScan(basePackages = { "org.baeldung.voter" })
|
||||
public class VoterApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
@ -24,10 +24,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
// @formatter: off
|
||||
auth.inMemoryAuthentication()
|
||||
.withUser("user").password("pass").roles("USER")
|
||||
.and()
|
||||
.withUser("admin").password("pass").roles("ADMIN");
|
||||
auth.inMemoryAuthentication().withUser("user").password("pass").roles("USER").and().withUser("admin").password("pass").roles("ADMIN");
|
||||
// @formatter: on
|
||||
}
|
||||
|
||||
@ -36,33 +33,15 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
// @formatter: off
|
||||
http
|
||||
// needed so our login could work
|
||||
.csrf()
|
||||
.disable()
|
||||
.authorizeRequests()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.accessDecisionManager(accessDecisionManager())
|
||||
.antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER")
|
||||
.and()
|
||||
.formLogin()
|
||||
.permitAll()
|
||||
.and()
|
||||
.logout()
|
||||
.permitAll()
|
||||
.deleteCookies("JSESSIONID")
|
||||
.logoutSuccessUrl("/login");
|
||||
.csrf().disable().authorizeRequests().anyRequest().authenticated().accessDecisionManager(accessDecisionManager()).antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER").and().formLogin().permitAll().and().logout().permitAll()
|
||||
.deleteCookies("JSESSIONID").logoutSuccessUrl("/login");
|
||||
// @formatter: on
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AccessDecisionManager accessDecisionManager() {
|
||||
// @formatter: off
|
||||
List<AccessDecisionVoter<? extends Object>> decisionVoters =
|
||||
Arrays.asList(
|
||||
new WebExpressionVoter(),
|
||||
new RoleVoter(),
|
||||
new AuthenticatedVoter(),
|
||||
new MinuteBasedVoter());
|
||||
List<AccessDecisionVoter<? extends Object>> decisionVoters = Arrays.asList(new WebExpressionVoter(), new RoleVoter(), new AuthenticatedVoter(), new MinuteBasedVoter());
|
||||
// @formatter: on
|
||||
return new UnanimousBased(decisionVoters);
|
||||
}
|
||||
|
@ -7,7 +7,7 @@ import org.springframework.context.annotation.ImportResource;
|
||||
* Created by ambrusadrianz on 09/10/2016.
|
||||
*/
|
||||
@Configuration
|
||||
@ImportResource({"classpath:spring-security.xml"})
|
||||
@ImportResource({ "classpath:spring-security.xml" })
|
||||
public class XmlSecurityConfig {
|
||||
public XmlSecurityConfig() {
|
||||
super();
|
||||
|
@ -15,6 +15,7 @@ public class MyUserLiveTest {
|
||||
|
||||
private final MyUser userJohn = new MyUser("john", "doe", "john@doe.com", 11);
|
||||
private String URL_PREFIX = "http://localhost:8082/spring-security-rest-full/auth/api/myusers";
|
||||
|
||||
@Test
|
||||
public void whenGettingListOfUsers_thenCorrect() {
|
||||
final Response response = givenAuth().get(URL_PREFIX);
|
||||
|
@ -16,11 +16,11 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationFa
|
||||
@ComponentScan("org.baeldung.security")
|
||||
public class SecurityJavaConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
// @Autowired
|
||||
// private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
|
||||
// @Autowired
|
||||
// private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
|
||||
|
||||
// @Autowired
|
||||
// private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
|
||||
// @Autowired
|
||||
// private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
|
||||
|
||||
public SecurityJavaConfig() {
|
||||
super();
|
||||
|
@ -22,11 +22,9 @@ public class AsyncController {
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/async")
|
||||
@ResponseBody
|
||||
public Object standardProcessing() throws Exception {
|
||||
log.info("Outside the @Async logic - before the async call: "
|
||||
+ SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
||||
log.info("Outside the @Async logic - before the async call: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
||||
asyncService.asyncCall();
|
||||
log.info("Inside the @Async logic - after the async call: "
|
||||
+ SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
||||
log.info("Inside the @Async logic - after the async call: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
||||
return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
}
|
||||
|
||||
|
@ -20,14 +20,12 @@ public class AsyncServiceImpl implements AsyncService {
|
||||
|
||||
@Override
|
||||
public Callable<Boolean> checkIfPrincipalPropagated() {
|
||||
Object before
|
||||
= SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
Object before = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
log.info("Before new thread: " + before);
|
||||
|
||||
return new Callable<Boolean>() {
|
||||
public Boolean call() throws Exception {
|
||||
Object after
|
||||
= SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
Object after = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
log.info("New thread: " + after);
|
||||
return before == after;
|
||||
}
|
||||
|
@ -22,7 +22,7 @@ import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class})
|
||||
@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class })
|
||||
public class AsyncControllerTest {
|
||||
|
||||
@Autowired
|
||||
|
@ -13,17 +13,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth
|
||||
.inMemoryAuthentication()
|
||||
.withUser("admin").password("password").roles("ADMIN");
|
||||
auth.inMemoryAuthentication().withUser("admin").password("password").roles("ADMIN");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.httpBasic().and()
|
||||
.authorizeRequests()
|
||||
.antMatchers("/").hasRole("ADMIN")
|
||||
.anyRequest().authenticated();
|
||||
http.httpBasic().and().authorizeRequests().antMatchers("/").hasRole("ADMIN").anyRequest().authenticated();
|
||||
}
|
||||
}
|
||||
|
@ -42,10 +42,10 @@ public class SessionControllerTest {
|
||||
@Test
|
||||
public void testRedisControlsSession() {
|
||||
ResponseEntity<String> result = testRestTemplateWithAuth.getForEntity(testUrl, String.class);
|
||||
assertEquals("hello admin", result.getBody()); //login worked
|
||||
assertEquals("hello admin", result.getBody()); // login worked
|
||||
|
||||
Set<String> redisResult = jedis.keys("*");
|
||||
assertTrue(redisResult.size() > 0); //redis is populated with session data
|
||||
assertTrue(redisResult.size() > 0); // redis is populated with session data
|
||||
|
||||
String sessionCookie = result.getHeaders().get("Set-Cookie").get(0).split(";")[0];
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
@ -53,12 +53,12 @@ public class SessionControllerTest {
|
||||
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
|
||||
|
||||
result = testRestTemplate.exchange(testUrl, HttpMethod.GET, httpEntity, String.class);
|
||||
assertEquals("hello admin", result.getBody()); //access with session works worked
|
||||
assertEquals("hello admin", result.getBody()); // access with session works worked
|
||||
|
||||
jedis.flushAll(); //clear all keys in redis
|
||||
jedis.flushAll(); // clear all keys in redis
|
||||
|
||||
result = testRestTemplate.exchange(testUrl, HttpMethod.GET, httpEntity, String.class);
|
||||
assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());//access denied after sessions are removed in redis
|
||||
assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());// access denied after sessions are removed in redis
|
||||
|
||||
}
|
||||
}
|
@ -18,7 +18,7 @@ import java.util.concurrent.Executors;
|
||||
@Configuration
|
||||
@EnableAsync
|
||||
@EnableScheduling
|
||||
public class ThreadConfig extends AsyncConfigurerSupport implements SchedulingConfigurer{
|
||||
public class ThreadConfig extends AsyncConfigurerSupport implements SchedulingConfigurer {
|
||||
|
||||
@Autowired
|
||||
private BeanFactory beanFactory;
|
||||
|
@ -25,8 +25,7 @@ public class UserController {
|
||||
myUserService.registerNewUserAccount(accountDto);
|
||||
model.addAttribute("message", "Registration successful");
|
||||
return "index";
|
||||
}
|
||||
catch(final Exception exc){
|
||||
} catch (final Exception exc) {
|
||||
model.addAttribute("message", "Registration failed");
|
||||
|
||||
return "index";
|
||||
|
@ -34,7 +34,7 @@ public class MyUserService {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void removeUserByUsername(String username){
|
||||
public void removeUserByUsername(String username) {
|
||||
myUserDAO.removeUserByUsername(username);
|
||||
}
|
||||
|
||||
|
@ -60,7 +60,7 @@ public class CustomUserDetailsServiceIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test (expected = BadCredentialsException.class)
|
||||
@Test(expected = BadCredentialsException.class)
|
||||
public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() {
|
||||
try {
|
||||
MyUserDto userDTO = new MyUserDto();
|
||||
@ -69,15 +69,13 @@ public class CustomUserDetailsServiceIntegrationTest {
|
||||
|
||||
try {
|
||||
myUserService.registerNewUserAccount(userDTO);
|
||||
}
|
||||
catch (Exception exc) {
|
||||
} catch (Exception exc) {
|
||||
LOG.log(Level.SEVERE, "Error creating account");
|
||||
}
|
||||
|
||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD);
|
||||
Authentication authentication = authenticationProvider.authenticate(auth);
|
||||
}
|
||||
finally {
|
||||
} finally {
|
||||
myUserService.removeUserByUsername(USERNAME);
|
||||
}
|
||||
}
|
||||
|
@ -61,8 +61,7 @@ public class Dom4JParser {
|
||||
try {
|
||||
SAXReader reader = new SAXReader();
|
||||
Document document = reader.read(file);
|
||||
List<Node> elements = document
|
||||
.selectNodes("//tutorial[descendant::title[text()=" + "'" + name + "'" + "]]");
|
||||
List<Node> elements = document.selectNodes("//tutorial[descendant::title[text()=" + "'" + name + "'" + "]]");
|
||||
return elements.get(0);
|
||||
} catch (DocumentException e) {
|
||||
e.printStackTrace();
|
||||
|
@ -12,7 +12,6 @@ import org.jdom2.input.SAXBuilder;
|
||||
import org.jdom2.xpath.XPathExpression;
|
||||
import org.jdom2.xpath.XPathFactory;
|
||||
|
||||
|
||||
public class JDomParser {
|
||||
|
||||
private File file;
|
||||
@ -45,7 +44,7 @@ public class JDomParser {
|
||||
List<Element> node = expr.evaluate(document);
|
||||
|
||||
return node.get(0);
|
||||
} catch (JDOMException | IOException e ) {
|
||||
} catch (JDOMException | IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
|
@ -23,7 +23,7 @@ public class JaxenDemo {
|
||||
this.file = file;
|
||||
}
|
||||
|
||||
public List getAllTutorial(){
|
||||
public List getAllTutorial() {
|
||||
try {
|
||||
FileInputStream fileIS = new FileInputStream(this.getFile());
|
||||
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
|
||||
@ -53,5 +53,4 @@ public class JaxenDemo {
|
||||
this.file = file;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -94,7 +94,7 @@ public class StaxParser {
|
||||
case XMLStreamConstants.END_ELEMENT:
|
||||
EndElement endElement = event.asEndElement();
|
||||
if (endElement.getName().getLocalPart().equalsIgnoreCase("tutorial")) {
|
||||
if(current != null){
|
||||
if (current != null) {
|
||||
tutorials.add(current);
|
||||
}
|
||||
}
|
||||
|
@ -12,7 +12,6 @@ public class Tutorial {
|
||||
private String date;
|
||||
private String author;
|
||||
|
||||
|
||||
public String getTutId() {
|
||||
return tutId;
|
||||
}
|
||||
@ -21,37 +20,47 @@ public class Tutorial {
|
||||
public void setTutId(String tutId) {
|
||||
this.tutId = tutId;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
@XmlAttribute
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
@XmlElement
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
@XmlElement
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
@XmlElement
|
||||
public void setDate(String date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
@XmlElement
|
||||
public void setAuthor(String author) {
|
||||
this.author = author;
|
||||
|
@ -19,5 +19,4 @@ public class Tutorials {
|
||||
this.tutorial = tutorial;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -53,7 +53,7 @@ public class DefaultParserUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getNodeListByDateTest(){
|
||||
public void getNodeListByDateTest() {
|
||||
parser = new DefaultParser(new File(fileName));
|
||||
NodeList list = parser.getNodeListByTitle("04022016");
|
||||
for (int i = 0; null != list && i < list.getLength(); i++) {
|
||||
@ -70,7 +70,7 @@ public class DefaultParserUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getNodeListWithNamespaceTest(){
|
||||
public void getNodeListWithNamespaceTest() {
|
||||
parser = new DefaultParser(new File(fileNameSpace));
|
||||
NodeList list = parser.getAllTutorials();
|
||||
assertNotNull(list);
|
||||
|
@ -11,13 +11,12 @@ import com.baeldung.xml.binding.Tutorials;
|
||||
|
||||
public class JaxbParserUnitTest {
|
||||
|
||||
|
||||
final String fileName = "src/test/resources/example.xml";
|
||||
|
||||
JaxbParser parser;
|
||||
|
||||
@Test
|
||||
public void getFullDocumentTest(){
|
||||
public void getFullDocumentTest() {
|
||||
parser = new JaxbParser(new File(fileName));
|
||||
Tutorials tutorials = parser.getFullDocument();
|
||||
|
||||
@ -27,12 +26,11 @@ public class JaxbParserUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createNewDocumentTest(){
|
||||
public void createNewDocumentTest() {
|
||||
File newFile = new File("src/test/resources/example_new.xml");
|
||||
parser = new JaxbParser(newFile);
|
||||
parser.createNewDocument();
|
||||
|
||||
|
||||
assertTrue(newFile.exists());
|
||||
|
||||
Tutorials tutorials = parser.getFullDocument();
|
||||
|
@ -17,7 +17,7 @@ public class StaxParserUnitTest {
|
||||
StaxParser parser;
|
||||
|
||||
@Test
|
||||
public void getAllTutorialsTest(){
|
||||
public void getAllTutorialsTest() {
|
||||
parser = new StaxParser(new File(fileName));
|
||||
List<Tutorial> tutorials = parser.getAllTutorial();
|
||||
|
||||
|
@ -15,8 +15,7 @@ public class IgnoreAttributeDifferenceEvaluator implements DifferenceEvaluator {
|
||||
}
|
||||
|
||||
@Override
|
||||
public ComparisonResult evaluate(Comparison comparison,
|
||||
ComparisonResult outcome) {
|
||||
public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) {
|
||||
if (outcome == ComparisonResult.EQUAL)
|
||||
return outcome;
|
||||
final Node controlNode = comparison.getControlDetails().getTarget();
|
||||
|
@ -29,24 +29,16 @@ public class XMLUnitTest {
|
||||
@Test
|
||||
public void givenWrongXml_whenValidateFailsAgainstXsd_thenCorrect() {
|
||||
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
|
||||
v.setSchemaSource(Input.fromStream(
|
||||
XMLUnitTest.class.getResourceAsStream(
|
||||
"/students.xsd")).build());
|
||||
ValidationResult r = v.validateInstance(Input.fromStream(
|
||||
XMLUnitTest.class.getResourceAsStream(
|
||||
"/students_with_error.xml")).build());
|
||||
v.setSchemaSource(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students.xsd")).build());
|
||||
ValidationResult r = v.validateInstance(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students_with_error.xml")).build());
|
||||
assertFalse(r.isValid());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXmlWithErrors_whenReturnsValidationProblems_thenCorrect() {
|
||||
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
|
||||
v.setSchemaSource(Input.fromStream(
|
||||
XMLUnitTest.class.getResourceAsStream(
|
||||
"/students.xsd")).build());
|
||||
ValidationResult r = v.validateInstance(Input.fromStream(
|
||||
XMLUnitTest.class.getResourceAsStream(
|
||||
"/students_with_error.xml")).build());
|
||||
v.setSchemaSource(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students.xsd")).build());
|
||||
ValidationResult r = v.validateInstance(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students_with_error.xml")).build());
|
||||
Iterator<ValidationProblem> probs = r.getProblems().iterator();
|
||||
int count = 0;
|
||||
while (probs.hasNext()) {
|
||||
@ -59,12 +51,8 @@ public class XMLUnitTest {
|
||||
@Test
|
||||
public void givenXml_whenValidatesAgainstXsd_thenCorrect() {
|
||||
Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
|
||||
v.setSchemaSource(Input.fromStream(
|
||||
XMLUnitTest.class.getResourceAsStream(
|
||||
"/students.xsd")).build());
|
||||
ValidationResult r = v.validateInstance(Input.fromStream(
|
||||
XMLUnitTest.class.getResourceAsStream(
|
||||
"/students.xml")).build());
|
||||
v.setSchemaSource(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students.xsd")).build());
|
||||
ValidationResult r = v.validateInstance(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/students.xml")).build());
|
||||
Iterator<ValidationProblem> probs = r.getProblems().iterator();
|
||||
while (probs.hasNext()) {
|
||||
System.out.println(probs.next().toString());
|
||||
@ -76,11 +64,7 @@ public class XMLUnitTest {
|
||||
public void givenXPath_whenAbleToRetrieveNodes_thenCorrect() {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
|
||||
Iterable<Node> i = new JAXPXPathEngine().selectNodes(
|
||||
"//teacher",
|
||||
Input.fromFile(
|
||||
new File(classLoader.getResource("teachers.xml")
|
||||
.getFile())).build());
|
||||
Iterable<Node> i = new JAXPXPathEngine().selectNodes("//teacher", Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())).build());
|
||||
assertNotNull(i);
|
||||
int count = 0;
|
||||
for (Iterator<Node> it = i.iterator(); it.hasNext();) {
|
||||
@ -98,26 +82,22 @@ public class XMLUnitTest {
|
||||
@Test
|
||||
public void givenXmlSource_whenAbleToValidateExistingXPath_thenCorrect() {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource(
|
||||
"teachers.xml").getFile())), hasXPath("//teachers"));
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource(
|
||||
"teachers.xml").getFile())), hasXPath("//teacher"));
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource(
|
||||
"teachers.xml").getFile())), hasXPath("//subject"));
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource(
|
||||
"teachers.xml").getFile())), hasXPath("//@department"));
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), hasXPath("//teachers"));
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), hasXPath("//teacher"));
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), hasXPath("//subject"));
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), hasXPath("//@department"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXmlSource_whenFailsToValidateInExistentXPath_thenCorrect() {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource(
|
||||
"teachers.xml").getFile())), not(hasXPath("//sujet")));
|
||||
assertThat(Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())), not(hasXPath("//sujet")));
|
||||
}
|
||||
|
||||
// NOTE: ignore as this test demonstrates that two XMLs that contain the same data
|
||||
// will fail the isSimilarTo test.
|
||||
@Test @Ignore
|
||||
@Test
|
||||
@Ignore
|
||||
public void given2XMLS_whenSimilar_thenCorrect_fails() {
|
||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||
@ -128,8 +108,7 @@ public class XMLUnitTest {
|
||||
public void given2XMLS_whenSimilar_thenCorrect() {
|
||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||
assertThat(testXml,isSimilarTo(controlXml).withNodeMatcher(
|
||||
new DefaultNodeMatcher(ElementSelectors.byName)));
|
||||
assertThat(testXml, isSimilarTo(controlXml).withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -137,14 +116,8 @@ public class XMLUnitTest {
|
||||
String myControlXML = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String myTestXML = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||
|
||||
Diff myDiffSimilar = DiffBuilder
|
||||
.compare(myControlXML)
|
||||
.withTest(myTestXML)
|
||||
.withNodeMatcher(
|
||||
new DefaultNodeMatcher(ElementSelectors.byName))
|
||||
.checkForSimilar().build();
|
||||
assertFalse("XML similar " + myDiffSimilar.toString(),
|
||||
myDiffSimilar.hasDifferences());
|
||||
Diff myDiffSimilar = DiffBuilder.compare(myControlXML).withTest(myTestXML).withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)).checkForSimilar().build();
|
||||
assertFalse("XML similar " + myDiffSimilar.toString(), myDiffSimilar.hasDifferences());
|
||||
|
||||
}
|
||||
|
||||
@ -152,12 +125,7 @@ public class XMLUnitTest {
|
||||
public void given2XMLsWithDifferences_whenTestsSimilarWithDifferenceEvaluator_thenCorrect() {
|
||||
final String control = "<a><b attr=\"abc\"></b></a>";
|
||||
final String test = "<a><b attr=\"xyz\"></b></a>";
|
||||
Diff myDiff = DiffBuilder
|
||||
.compare(control)
|
||||
.withTest(test)
|
||||
.withDifferenceEvaluator(
|
||||
new IgnoreAttributeDifferenceEvaluator("attr"))
|
||||
.checkForSimilar().build();
|
||||
Diff myDiff = DiffBuilder.compare(control).withTest(test).withDifferenceEvaluator(new IgnoreAttributeDifferenceEvaluator("attr")).checkForSimilar().build();
|
||||
|
||||
assertFalse(myDiff.toString(), myDiff.hasDifferences());
|
||||
}
|
||||
@ -167,8 +135,7 @@ public class XMLUnitTest {
|
||||
final String control = "<a><b attr=\"abc\"></b></a>";
|
||||
final String test = "<a><b attr=\"xyz\"></b></a>";
|
||||
|
||||
Diff myDiff = DiffBuilder.compare(control).withTest(test)
|
||||
.checkForSimilar().build();
|
||||
Diff myDiff = DiffBuilder.compare(control).withTest(test).checkForSimilar().build();
|
||||
|
||||
// assertFalse(myDiff.toString(), myDiff.hasDifferences());
|
||||
assertTrue(myDiff.toString(), myDiff.hasDifferences());
|
||||
@ -178,41 +145,30 @@ public class XMLUnitTest {
|
||||
public void given2XMLS_whenSimilarWithCustomElementSelector_thenCorrect() {
|
||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||
assertThat(
|
||||
testXml,
|
||||
isSimilarTo(controlXml).withNodeMatcher(
|
||||
new DefaultNodeMatcher(ElementSelectors.byName)));
|
||||
assertThat(testXml, isSimilarTo(controlXml).withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileSourceAsObject_whenAbleToInput_thenCorrect() {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
assertThat(Input.from(new File(classLoader.getResource("test.xml").getFile())),
|
||||
isSimilarTo(Input.from(new File(classLoader.getResource("control.xml").getFile()))));
|
||||
assertThat(Input.from(new File(classLoader.getResource("test.xml").getFile())), isSimilarTo(Input.from(new File(classLoader.getResource("control.xml").getFile()))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStreamAsSource_whenAbleToInput_thenCorrect() {
|
||||
assertThat(Input.fromStream(XMLUnitTest.class
|
||||
.getResourceAsStream("/test.xml")),
|
||||
isSimilarTo(Input.fromStream(XMLUnitTest.class
|
||||
.getResourceAsStream("/control.xml"))));
|
||||
assertThat(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/test.xml")), isSimilarTo(Input.fromStream(XMLUnitTest.class.getResourceAsStream("/control.xml"))));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStreamAsObject_whenAbleToInput_thenCorrect() {
|
||||
assertThat(Input.from(XMLUnitTest.class.getResourceAsStream("/test.xml")),
|
||||
isSimilarTo(Input.from(XMLUnitTest.class.getResourceAsStream("/control.xml"))));
|
||||
assertThat(Input.from(XMLUnitTest.class.getResourceAsStream("/test.xml")), isSimilarTo(Input.from(XMLUnitTest.class.getResourceAsStream("/control.xml"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringSourceAsObject_whenAbleToInput_thenCorrect() {
|
||||
assertThat(
|
||||
Input.from("<struct><int>3</int><boolean>false</boolean></struct>"),
|
||||
isSimilarTo(Input
|
||||
.from("<struct><int>3</int><boolean>false</boolean></struct>")));
|
||||
assertThat(Input.from("<struct><int>3</int><boolean>false</boolean></struct>"), isSimilarTo(Input.from("<struct><int>3</int><boolean>false</boolean></struct>")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -220,16 +176,14 @@ public class XMLUnitTest {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
String testPath = classLoader.getResource("test.xml").getPath();
|
||||
String controlPath = classLoader.getResource("control.xml").getPath();
|
||||
assertThat(Input.fromFile(testPath),
|
||||
isSimilarTo(Input.fromFile(controlPath)));
|
||||
assertThat(Input.fromFile(testPath), isSimilarTo(Input.fromFile(controlPath)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringSource_whenAbleToInput_thenCorrect() {
|
||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
assertThat(Input.fromString(testXml),
|
||||
isSimilarTo(Input.fromString(controlXml)));
|
||||
assertThat(Input.fromString(testXml), isSimilarTo(Input.fromString(controlXml)));
|
||||
|
||||
}
|
||||
|
||||
@ -237,8 +191,7 @@ public class XMLUnitTest {
|
||||
public void givenSource_whenAbleToInput_thenCorrect() {
|
||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String testXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
assertThat(Input.fromString(testXml),
|
||||
isSimilarTo(Input.fromString(controlXml)));
|
||||
assertThat(Input.fromString(testXml), isSimilarTo(Input.fromString(controlXml)));
|
||||
|
||||
}
|
||||
|
||||
@ -259,8 +212,7 @@ public class XMLUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2XMLS_whenGeneratesDifferences_thenCorrect()
|
||||
throws Exception {
|
||||
public void given2XMLS_whenGeneratesDifferences_thenCorrect() throws Exception {
|
||||
String controlXml = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String testXml = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||
Diff myDiff = DiffBuilder.compare(controlXml).withTest(testXml).build();
|
||||
@ -274,15 +226,10 @@ public class XMLUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2XMLS_whenGeneratesOneDifference_thenCorrect()
|
||||
throws Exception {
|
||||
public void given2XMLS_whenGeneratesOneDifference_thenCorrect() throws Exception {
|
||||
String myControlXML = "<struct><int>3</int><boolean>false</boolean></struct>";
|
||||
String myTestXML = "<struct><boolean>false</boolean><int>3</int></struct>";
|
||||
Diff myDiff = DiffBuilder
|
||||
.compare(myControlXML)
|
||||
.withTest(myTestXML)
|
||||
.withComparisonController(
|
||||
ComparisonControllers.StopWhenDifferent).build();
|
||||
Diff myDiff = DiffBuilder.compare(myControlXML).withTest(myTestXML).withComparisonController(ComparisonControllers.StopWhenDifferent).build();
|
||||
Iterator<Difference> iter = myDiff.getDifferences().iterator();
|
||||
int size = 0;
|
||||
while (iter.hasNext()) {
|
||||
|
@ -40,7 +40,6 @@ public class Customer {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [firstName=" + firstName + ", lastName=" + lastName
|
||||
+ ", dob=" + dob + "]";
|
||||
return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]";
|
||||
}
|
||||
}
|
||||
|
@ -5,7 +5,6 @@ import com.thoughtworks.xstream.annotations.XStreamOmitField;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
|
||||
@XStreamAlias("customer")
|
||||
public class CustomerOmitField {
|
||||
|
||||
@ -42,9 +41,7 @@ public class CustomerOmitField {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CustomerOmitAnnotation [firstName=" + firstName + ", lastName="
|
||||
+ lastName + ", dob=" + dob + "]";
|
||||
return "CustomerOmitAnnotation [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -39,8 +39,7 @@ public class ContactDetails {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ContactDetails [mobile=" + mobile + ", landline=" + landline
|
||||
+ ", contactType=" + contactType + "]";
|
||||
return "ContactDetails [mobile=" + mobile + ", landline=" + landline + ", contactType=" + contactType + "]";
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -50,8 +50,6 @@ public class Customer {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [firstName=" + firstName + ", lastName=" + lastName
|
||||
+ ", dob=" + dob + ", contactDetailsList=" + contactDetailsList
|
||||
+ "]";
|
||||
return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList + "]";
|
||||
}
|
||||
}
|
||||
|
@ -39,8 +39,7 @@ public class ContactDetails {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ContactDetails [mobile=" + mobile + ", landline=" + landline
|
||||
+ ", contactType=" + contactType + "]";
|
||||
return "ContactDetails [mobile=" + mobile + ", landline=" + landline + ", contactType=" + contactType + "]";
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -52,8 +52,6 @@ public class Customer {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [firstName=" + firstName + ", lastName=" + lastName
|
||||
+ ", dob=" + dob + ", contactDetailsList=" + contactDetailsList
|
||||
+ "]";
|
||||
return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList + "]";
|
||||
}
|
||||
}
|
||||
|
@ -39,7 +39,6 @@ public class CustomerAddressDetails {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
|
||||
public List<AddressDetails> getAddressDetails() {
|
||||
return addressDetails;
|
||||
}
|
||||
|
@ -29,7 +29,7 @@ public class ComplexXmlToObjectCollectionTest {
|
||||
Customer customer = (Customer) xstream.fromXML(reader);
|
||||
Assert.assertNotNull(customer);
|
||||
Assert.assertNotNull(customer.getContactDetailsList());
|
||||
//System.out.println(customer);
|
||||
// System.out.println(customer);
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
|
@ -29,7 +29,7 @@ public class XmlToObjectIgnoreFieldsTest {
|
||||
FileReader reader = new FileReader(classLoader.getResource("data-file-ignore-field.xml").getFile());
|
||||
Customer customer = (Customer) xstream.fromXML(reader);
|
||||
Assert.assertNotNull(customer);
|
||||
//System.out.println(customer);
|
||||
// System.out.println(customer);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
@ -42,5 +42,4 @@ public class XmlToObjectTest {
|
||||
Assert.assertNotNull(convertedCustomer);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user