下面列出了org.springframework.http.converter.xml.MarshallingHttpMessageConverter#org.springframework.oxm.jaxb.Jaxb2Marshaller 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void responseBodyArgMismatch() throws Exception {
initServlet(wac -> {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(A.class, B.class);
try {
marshaller.afterPropertiesSet();
}
catch (Exception ex) {
throw new BeanCreationException(ex.getMessage(), ex);
}
MarshallingHttpMessageConverter messageConverter = new MarshallingHttpMessageConverter(marshaller);
RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
adapterDef.getPropertyValues().add("messageConverters", messageConverter);
wac.registerBeanDefinition("handlerAdapter", adapterDef);
}, RequestBodyArgMismatchController.class);
MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
String requestBody = "<b/>";
request.setContent(requestBody.getBytes("UTF-8"));
request.addHeader("Content-Type", "application/xml; charset=utf-8");
MockHttpServletResponse response = new MockHttpServletResponse();
getServlet().service(request, response);
assertEquals(400, response.getStatus());
}
@Test
public void responseBodyArgMismatch() throws Exception {
initServlet(wac -> {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(A.class, B.class);
try {
marshaller.afterPropertiesSet();
}
catch (Exception ex) {
throw new BeanCreationException(ex.getMessage(), ex);
}
MarshallingHttpMessageConverter messageConverter = new MarshallingHttpMessageConverter(marshaller);
RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
adapterDef.getPropertyValues().add("messageConverters", messageConverter);
wac.registerBeanDefinition("handlerAdapter", adapterDef);
}, RequestBodyArgMismatchController.class);
MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
String requestBody = "<b/>";
request.setContent(requestBody.getBytes("UTF-8"));
request.addHeader("Content-Type", "application/xml; charset=utf-8");
MockHttpServletResponse response = new MockHttpServletResponse();
getServlet().service(request, response);
assertEquals(400, response.getStatus());
}
@Bean
@ConditionalOnSingleCandidate(Jaxb2Marshaller.class)
@ConditionalOnMissingBean(Jaxb2Printer.class)
@Order(100)
public Printer jaxb2Printer(ObjectProvider<Jaxb2Marshaller> jaxb2Marshaller) {
Jaxb2Marshaller marshaller = jaxb2Marshaller.getObject();
return new Jaxb2Printer(marshaller)
.addPreProcessor(new JaxbElementWrapper(marshaller));
}
@Bean
public Jaxb2Marshaller jaxb2Marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Dto.class);
marshaller.setMarshallerProperties(singletonMap(Marshaller.JAXB_FRAGMENT, true));
return marshaller;
}
@Bean
@Order(99)
public Printer maskJaxb2Printer(Jaxb2Marshaller jaxb2Marshaller) {
XPathMasker xPathMasker = new XPathMasker("//s");
xPathMasker.setReplacement("********");
xPathMasker.setOutputProperties(singletonMap(OutputKeys.OMIT_XML_DECLARATION, "yes"));
return new Jaxb2Printer(jaxb2Marshaller)
.addPreProcessor(new JaxbElementWrapper(jaxb2Marshaller))
.addPostProcessor(xPathMasker);
}
private Object wrap(Jaxb2Marshaller jaxb2Marshaller, Object input) {
Class<?> clazz = input.getClass();
Object cached = wrapperMethodCache.get(clazz);
if (nonNull(cached)) {
return cached == EMPTY_METHOD ? input : wrap(input, (Method) cached);
}
Class<?>[] wrapperClasses = findWrapperClasses(jaxb2Marshaller);
if (isNull(wrapperClasses)) {
wrapperMethodCache.put(clazz, EMPTY_METHOD);
return input;
}
Method method = findMethod(wrapperClasses, clazz);
if (isNull(method)) {
wrapperMethodCache.put(clazz, EMPTY_METHOD);
return input;
}
wrapperMethodCache.put(clazz, method);
return wrap(input, method);
}
private Class<?>[] findWrapperClasses(Jaxb2Marshaller jaxb2Marshaller) {
String contextPath = jaxb2Marshaller.getContextPath();
if (!hasText(contextPath)) {
return jaxb2Marshaller.getClassesToBeBound();
}
List<Class<?>> classes = new ArrayList<>();
for (String path : contextPath.split(":")) {
for (Resource resource : pathToResources(path)) {
if (resource.isReadable()) {
classes.add(forName(resource));
}
}
}
return classes.toArray(new Class[classes.size()]);
}
@Test
public void printers() {
// given
Printer inLogPrinter = new Printer() {
@Override
protected String serialize(Object input) {
return "!";
}
};
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Dto.class);
// when
SimpleLogger logger = new SimpleLoggerBuilder()
.method(methodWithParameters)
.parameterNames("s", "i", "dto")
.arguments("s", 1, new Dto())
.levels(DEBUG, OFF, DEBUG)
.printers(nCopies(3, inLogPrinter))
.parameterLog(DEBUG, OFF, DEBUG, new JacksonPrinter(new ObjectMapper()))
.parameterLog(null)
.parameterLog(DEBUG, OFF, DEBUG, new Jaxb2Printer(marshaller))
.effectiveLevel(DEBUG)
.buildAndInvokeAndGet();
// then
verify(logger.getLoggerFacadeFactory().getLoggerFacade(any())).log(DEBUG, "> s=\"s\", i=!, dto=<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><dto><i>0</i></dto>");
}
@Test
public void processEmptySecondEmptyWithRegistryAndWrapperCache() {
// given
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Registry.class);
JaxbElementWrapper jaxbElementWrapper = new JaxbElementWrapper(marshaller);
Object input = new Empty();
Object input2 = new SecondEmpty();
// when
Object processed = jaxbElementWrapper.process(input);
Object processed2 = jaxbElementWrapper.process(input2);
// then
assertTrue(processed instanceof JAXBElement);
assertThat(((JAXBElement) processed).getValue(), is(input));
assertTrue(processed2 instanceof JAXBElement);
assertThat(((JAXBElement) processed2).getValue(), is(input2));
Set<Map.Entry<Class<?>, Object>> wrapperCache = jaxbElementWrapper.getWrapperCache().entrySet();
assertThat(wrapperCache, hasSize(1));
Map.Entry<Class<?>, Object> wrapper = wrapperCache.iterator().next();
assertEquals(Registry.class, wrapper.getKey());
assertThat(wrapper.getValue(), notNullValue());
}
@Bean("writer2")
public ItemWriter<Permanent> xmlWriter() {
StaxEventItemWriter<Permanent> xmlFileWriter = new StaxEventItemWriter<>();
String exportFilePath = "./src/main/resources/emps.xml";
xmlFileWriter.setResource(new FileSystemResource(exportFilePath));
xmlFileWriter.setRootTagName("employees");
Jaxb2Marshaller empMarshaller = new Jaxb2Marshaller();
empMarshaller.setClassesToBeBound(Permanent.class);
xmlFileWriter.setMarshaller(empMarshaller);
System.out.println("marshalling");;
return xmlFileWriter;
}
@Bean
public CustomerClient weatherClient(Jaxb2Marshaller marshaller) {
CustomerClient client = new CustomerClient();
client.setDefaultUri(String.format("%s/v1/customers", customerUri));
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
@Before
public void createMarshaller() throws Exception {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(MyBean.class);
marshaller.afterPropertiesSet();
this.converter = new MarshallingMessageConverter(marshaller);
}
@Test
public void responseBodyArgMismatch() throws ServletException, IOException {
@SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() {
@Override
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(RequestBodyArgMismatchController.class));
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(A.class, B.class);
try {
marshaller.afterPropertiesSet();
}
catch (Exception ex) {
throw new BeanCreationException(ex.getMessage(), ex);
}
MarshallingHttpMessageConverter messageConverter = new MarshallingHttpMessageConverter(marshaller);
RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class);
adapterDef.getPropertyValues().add("messageConverters", messageConverter);
wac.registerBeanDefinition("handlerAdapter", adapterDef);
wac.refresh();
return wac;
}
};
servlet.init(new MockServletConfig());
MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
String requestBody = "<b/>";
request.setContent(requestBody.getBytes("UTF-8"));
request.addHeader("Content-Type", "application/xml; charset=utf-8");
MockHttpServletResponse response = new MockHttpServletResponse();
servlet.service(request, response);
assertEquals(400, response.getStatus());
}
@Test
public void responseBodyArgMismatch() throws ServletException, IOException {
initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
@Override
public void initialize(GenericWebApplicationContext wac) {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(A.class, B.class);
try {
marshaller.afterPropertiesSet();
}
catch (Exception ex) {
throw new BeanCreationException(ex.getMessage(), ex);
}
MarshallingHttpMessageConverter messageConverter = new MarshallingHttpMessageConverter(marshaller);
RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
adapterDef.getPropertyValues().add("messageConverters", messageConverter);
wac.registerBeanDefinition("handlerAdapter", adapterDef);
}
}, RequestBodyArgMismatchController.class);
MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
String requestBody = "<b/>";
request.setContent(requestBody.getBytes("UTF-8"));
request.addHeader("Content-Type", "application/xml; charset=utf-8");
MockHttpServletResponse response = new MockHttpServletResponse();
getServlet().service(request, response);
assertEquals(400, response.getStatus());
}
@Test
public void testXmlOnly() throws Exception {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Person.class);
standaloneSetup(new PersonController()).setSingleView(new MarshallingView(marshaller)).build()
.perform(get("/person/Corea"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
@Test
public void testContentNegotiation() throws Exception {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Person.class);
List<View> viewList = new ArrayList<View>();
viewList.add(new MappingJackson2JsonView());
viewList.add(new MarshallingView(marshaller));
ContentNegotiationManager manager = new ContentNegotiationManager(
new HeaderContentNegotiationStrategy(), new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));
ContentNegotiatingViewResolver cnViewResolver = new ContentNegotiatingViewResolver();
cnViewResolver.setDefaultViews(viewList);
cnViewResolver.setContentNegotiationManager(manager);
cnViewResolver.afterPropertiesSet();
MockMvc mockMvc =
standaloneSetup(new PersonController())
.setViewResolvers(cnViewResolver, new InternalResourceViewResolver())
.build();
mockMvc.perform(get("/person/Corea"))
.andExpect(status().isOk())
.andExpect(model().size(1))
.andExpect(model().attributeExists("person"))
.andExpect(forwardedUrl("person/show"));
mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.person.name").value("Corea"));
mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_XML))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
@Bean
public CustomerClient customerClient(Jaxb2Marshaller marshaller) {
CustomerClient client = new CustomerClient(customerServer);
client.setDefaultUri(customerServer + "ws");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
/**
* Gets a new JAXB marshaller that is aware of our XSD and can perform schema validation. It is also aware of all our auto-generated classes that are in the
* org.finra.herd.model.api.xml package. Note that REST endpoints that use Java objects which are not in this package will not use this marshaller and will
* not get schema validated which is good since they don't have an XSD.
*
* @return the newly created JAXB marshaller.
*/
@Bean
public Jaxb2Marshaller jaxb2Marshaller()
{
try
{
// Create the marshaller that is aware of our Java XSD and it's auto-generated classes.
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setPackagesToScan("org.finra.herd.model.api.xml");
marshaller.setSchemas(resourceResolver.getResources("classpath:herd.xsd"));
// Get the JAXB XML headers from the environment.
String xmlHeaders = configurationHelper.getProperty(ConfigurationValue.JAXB_XML_HEADERS);
// We need to set marshaller properties to reconfigure the XML header.
Map<String, Object> marshallerProperties = new HashMap<>();
marshaller.setMarshallerProperties(marshallerProperties);
// Remove the header that JAXB will generate.
marshallerProperties.put(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
// Specify the new XML headers.
marshallerProperties.put(ConfigurationValue.JAXB_XML_HEADERS.getKey(), xmlHeaders);
// Specify a custom character escape handler to escape XML 1.1 restricted characters.
marshallerProperties.put(MarshallerProperties.CHARACTER_ESCAPE_HANDLER, herdCharacterEscapeHandler);
// Return the marshaller.
return marshaller;
}
catch (Exception ex)
{
// Throw a runtime exception instead of a checked IOException since the XSD file should be contained within our application.
throw new IllegalArgumentException("Unable to create marshaller.", ex);
}
}
public XmlSoccerServiceImpl() {
modelMapper = new ModelMapper();
marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("com.github.pabloo99.xmlsoccer.webservice");
setMarshaller(marshaller);
setUnmarshaller(marshaller);
}
/**
* Unmarshall xml success test.
*
* @throws XmlAgentException
* the xml agent exception
*/
@Test
public void unmarshallXmlSuccessTest() throws XmlAgentException {
final Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setClassesToBeBound(SimpleXml.class);
final SimpleXml simpleXml = (SimpleXml) xmlAgent.unmarshallXml(jaxb2Marshaller, XmlAgentImplITest.class.getResource("/simplexml.xml").toString());
assertEquals(new SimpleXml("abc123"), simpleXml);
}
/**
* Unmarshall xml missing namespace success test.
*
* @throws XmlAgentException
* the xml agent exception
*/
@Test
public void unmarshallXmlMissingNamespaceSuccessTest() throws XmlAgentException {
final Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setClassesToBeBound(SimpleXml.class);
final SimpleXml simpleXml = (SimpleXml) xmlAgent.unmarshallXml(jaxb2Marshaller, XmlAgentImplITest.class.getResource("/simplexml-missing-namespace.xml").toString(),"com.hack23.cia.service.external.common.impl.test",null,null);
assertEquals(new SimpleXml("abc123"), simpleXml);
}
/**
* Unmarshall xml missing namespace and replace success test.
*
* @throws XmlAgentException
* the xml agent exception
*/
@Test
public void unmarshallXmlMissingNamespaceAndReplaceSuccessTest() throws XmlAgentException {
final Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setClassesToBeBound(SimpleXml.class);
final SimpleXml simpleXml = (SimpleXml) xmlAgent.unmarshallXml(jaxb2Marshaller, XmlAgentImplITest.class.getResource("/simplexml-missing-namespace.xml").toString(),"com.hack23.cia.service.external.common.impl.test","abc123","ABC123");
assertEquals(new SimpleXml("ABC123"), simpleXml);
}
@Bean
public CountryClient countryClient(Jaxb2Marshaller marshaller) {
CountryClient client = new CountryClient();
client.setDefaultUri("http://localhost:8080/ws");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
@Bean
public UnmarshallerRepositoryPopulatorFactoryBean repositoryPopulator() {
Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller();
unmarshaller.setClassesToBeBound(Fruit.class);
UnmarshallerRepositoryPopulatorFactoryBean factory = new UnmarshallerRepositoryPopulatorFactoryBean();
factory.setUnmarshaller(unmarshaller);
factory.setResources(new Resource[] { new ClassPathResource("apple-fruit-data.xml"), new ClassPathResource("guava-fruit-data.xml") });
return factory;
}
@Before
public void createMarshaller() throws Exception {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(MyBean.class);
marshaller.afterPropertiesSet();
this.converter = new MarshallingMessageConverter(marshaller);
}
@Test
public void jaxb2ContextPathMarshaller() {
Jaxb2Marshaller jaxb2Marshaller = applicationContext.getBean("jaxb2ContextPathMarshaller", Jaxb2Marshaller.class);
assertNotNull(jaxb2Marshaller);
}
@Test
public void jaxb2ClassesToBeBoundMarshaller() {
Jaxb2Marshaller jaxb2Marshaller = applicationContext.getBean("jaxb2ClassesMarshaller", Jaxb2Marshaller.class);
assertNotNull(jaxb2Marshaller);
}
@Test
public void testXmlOnly() throws Exception {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Person.class);
standaloneSetup(new PersonController()).setSingleView(new MarshallingView(marshaller)).build()
.perform(get("/person/Corea"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
@Test
public void testContentNegotiation() throws Exception {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Person.class);
List<View> viewList = new ArrayList<>();
viewList.add(new MappingJackson2JsonView());
viewList.add(new MarshallingView(marshaller));
ContentNegotiationManager manager = new ContentNegotiationManager(
new HeaderContentNegotiationStrategy(), new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));
ContentNegotiatingViewResolver cnViewResolver = new ContentNegotiatingViewResolver();
cnViewResolver.setDefaultViews(viewList);
cnViewResolver.setContentNegotiationManager(manager);
cnViewResolver.afterPropertiesSet();
MockMvc mockMvc =
standaloneSetup(new PersonController())
.setViewResolvers(cnViewResolver, new InternalResourceViewResolver())
.build();
mockMvc.perform(get("/person/Corea"))
.andExpect(status().isOk())
.andExpect(model().size(1))
.andExpect(model().attributeExists("person"))
.andExpect(forwardedUrl("person/show"));
mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.person.name").value("Corea"));
mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_XML))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
@Bean
public WsClient wsClient(Jaxb2Marshaller marshaller) {
WsClient client = new WsClient();
client.setDefaultUri("http://127.0.0.1:8080/ws/countries.wsdl");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}