Java Code Examples for org.springframework.oxm.jaxb.Jaxb2Marshaller#setClassesToBeBound()

The following examples show how to use org.springframework.oxm.jaxb.Jaxb2Marshaller#setClassesToBeBound() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BatchConfig.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@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;
   }
 
Example 2
Source File: LogInSimpleLoggerTest.java    From eclair with Apache License 2.0 6 votes vote down vote up
@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>");
}
 
Example 3
Source File: ViewResolutionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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")));
}
 
Example 4
Source File: XmlAgentImplITest.java    From cia with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 5
Source File: ViewResolutionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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")));
}
 
Example 6
Source File: ViewResolutionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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")));
}
 
Example 7
Source File: ServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 8
Source File: MarshallingMessageConverterTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Before
public void createMarshaller() throws Exception {
	Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
	marshaller.setClassesToBeBound(MyBean.class);
	marshaller.afterPropertiesSet();

	this.converter = new MarshallingMessageConverter(marshaller);
}
 
Example 9
Source File: JaxbElementWrapperTest.java    From eclair with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 10
Source File: JaxbElementWrapperTest.java    From eclair with Apache License 2.0 4 votes vote down vote up
@Test
public void processEmptyWithRegistry() {
    // given
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setClassesToBeBound(Registry.class);
    JaxbElementWrapper jaxbElementWrapper = new JaxbElementWrapper(marshaller);
    Object input = new Empty();
    // when
    Object processed = jaxbElementWrapper.process(input);
    // then
    assertTrue(processed instanceof JAXBElement);
    assertThat(((JAXBElement) processed).getValue(), is(input));
}
 
Example 11
Source File: JaxbElementWrapperTest.java    From eclair with Apache License 2.0 4 votes vote down vote up
@Test
public void processEmptyRegistry() {
    // given
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setClassesToBeBound(EmptyRegistry.class);

    JaxbElementWrapper jaxbElementWrapper = new JaxbElementWrapper(marshaller);
    Object input = new Empty();
    // when
    Object processed = jaxbElementWrapper.process(input);
    // then
    assertThat(processed, is(input));
}
 
Example 12
Source File: Jaxb2PrinterTest.java    From eclair with Apache License 2.0 4 votes vote down vote up
@Test
public void serializeRoot() {
    // given
    Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
    jaxb2Marshaller.setClassesToBeBound(Root.class);
    Jaxb2Printer jaxb2Printer = new Jaxb2Printer(jaxb2Marshaller);
    Root root = new Root();
    root.setValue("value");
    // when
    String xml = jaxb2Printer.serialize(root);
    // then
    assertThat(xml, is("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><someName><value>value</value></someName>"));
}
 
Example 13
Source File: Jaxb2PrinterTest.java    From eclair with Apache License 2.0 4 votes vote down vote up
@Test(expected = XmlMappingException.class)
public void serializeXmlNotRoot() {
    // given
    Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
    jaxb2Marshaller.setClassesToBeBound(Root.class);
    Jaxb2Printer jaxb2Printer = new Jaxb2Printer(jaxb2Marshaller);
    NotRoot notRoot = new NotRoot();
    notRoot.setValue("value");
    // when
    jaxb2Printer.serialize(notRoot);
    // then expected exception
}
 
Example 14
Source File: Jaxb2PrinterTest.java    From eclair with Apache License 2.0 4 votes vote down vote up
@Test
public void serializeJaxbElement() {
    // given
    Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
    jaxb2Marshaller.setClassesToBeBound(Empty.class);
    Jaxb2Printer jaxb2Printer = new Jaxb2Printer(jaxb2Marshaller);
    Empty empty = new Empty();
    empty.setValue("value");
    JAXBElement<Empty> jaxbElement = new JAXBElement<>(new QName("localPart"), Empty.class, empty);
    // when
    String xml = jaxb2Printer.serialize(jaxbElement);
    // then
    assertThat(xml, is("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><localPart><value>value</value></localPart>"));
}
 
Example 15
Source File: WebMvcConfig.java    From enhanced-pet-clinic with Apache License 2.0 4 votes vote down vote up
@Bean(name = "marshallingXmlViewResolver")
public ViewResolver getMarshallingXmlViewResolver() {
	Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
	marshaller.setClassesToBeBound(new Class[] { Vets.class });
	return new XmlViewResolver(marshaller);
}
 
Example 16
Source File: ViewResolutionTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@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")));
}
 
Example 17
Source File: ViewResolutionTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@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")));
}
 
Example 18
Source File: MarshallingMessageConverterTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Before
public void createMarshaller() throws Exception {
	Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
	marshaller.setClassesToBeBound(MyBean.class);
	marshaller.afterPropertiesSet();

	this.converter = new MarshallingMessageConverter(marshaller);
}
 
Example 19
Source File: ViewResolutionTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@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")));
}
 
Example 20
Source File: MarshallingMessageConverterTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Before
public void createMarshaller() throws Exception {
	Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
	marshaller.setClassesToBeBound(MyBean.class);
	marshaller.afterPropertiesSet();

	this.converter = new MarshallingMessageConverter(marshaller);
}