org.springframework.http.converter.xml.MarshallingHttpMessageConverter#org.springframework.oxm.jaxb.Jaxb2Marshaller源码实例Demo

下面列出了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());
}
 
源代码3 项目: eclair   文件: EclairAutoConfiguration.java
@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));
}
 
源代码4 项目: eclair   文件: ExampleTest.java
@Bean
public Jaxb2Marshaller jaxb2Marshaller() {
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setClassesToBeBound(Dto.class);
    marshaller.setMarshallerProperties(singletonMap(Marshaller.JAXB_FRAGMENT, true));
    return marshaller;
}
 
源代码5 项目: eclair   文件: ExampleTest.java
@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);
}
 
源代码6 项目: eclair   文件: JaxbElementWrapper.java
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);
}
 
源代码7 项目: eclair   文件: JaxbElementWrapper.java
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()]);
}
 
源代码8 项目: eclair   文件: LogInSimpleLoggerTest.java
@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>");
}
 
源代码9 项目: eclair   文件: JaxbElementWrapperTest.java
@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());
}
 
源代码10 项目: Spring-5.0-Cookbook   文件: BatchConfig.java
@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;
}
 
源代码18 项目: herd   文件: RestSpringModuleConfig.java
/**
 * 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);
    }
}
 
源代码19 项目: xmlsoccer   文件: XmlSoccerServiceImpl.java
public XmlSoccerServiceImpl() {
    modelMapper = new ModelMapper();
    marshaller = new Jaxb2Marshaller();
    marshaller.setContextPath("com.github.pabloo99.xmlsoccer.webservice");
    setMarshaller(marshaller);
    setUnmarshaller(marshaller);
}
 
源代码20 项目: cia   文件: XmlAgentImplITest.java
/**
 * 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);
}
 
源代码21 项目: cia   文件: XmlAgentImplITest.java
/**
 * 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);
}
 
源代码22 项目: cia   文件: XmlAgentImplITest.java
/**
 * 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);
}
 
源代码23 项目: tutorials   文件: CountryClientConfig.java
@Bean
public CountryClient countryClient(Jaxb2Marshaller marshaller) {
        CountryClient client = new CountryClient();
        client.setDefaultUri("http://localhost:8080/ws");
        client.setMarshaller(marshaller);
        client.setUnmarshaller(marshaller);
        return client;
}
 
源代码24 项目: tutorials   文件: JpaPopulators.java
@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);
}
 
源代码28 项目: spring-analysis-note   文件: ViewResolutionTests.java
@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")));
}
 
源代码29 项目: spring-analysis-note   文件: ViewResolutionTests.java
@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")));
}
 
源代码30 项目: springboot-learn   文件: WSConfig.java
@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;
}