com.fasterxml.jackson.dataformat.xml.XmlMapper Java Examples

The following examples show how to use com.fasterxml.jackson.dataformat.xml.XmlMapper. 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: FunctionConfiguration.java    From blog-tutorials with MIT License 8 votes vote down vote up
@Bean
public Function<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> processXmlOrder() {
  return value -> {
    try {
      ObjectMapper objectMapper = new XmlMapper();
      Order order = objectMapper.readValue(value.getBody(), Order.class);
      logger.info("Successfully deserialized XML order '{}'", order);

      // ... processing Order
      order.setProcessed(true);

      APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
      responseEvent.setStatusCode(201);
      responseEvent.setHeaders(Map.of("Content-Type", "application/xml"));
      responseEvent.setBody(objectMapper.writeValueAsString(order));
      return responseEvent;
    } catch (IOException e) {
      e.printStackTrace();
      return new APIGatewayProxyResponseEvent().withStatusCode(500);
    }
  };
}
 
Example #2
Source File: ConfigurationTest.java    From maven-git-versioning-extension with MIT License 6 votes vote down vote up
@Test
void xmlUnmarshaller_commitConfigOnly() throws IOException {
    // given
    String configXml = "" +
            "<gitVersioning>\n" +
            "    <commit>\n" +
            "        <versionFormat>commit1-format</versionFormat>\n" +
            "    </commit>\n" +
            "</gitVersioning>\n";

    // when
    Configuration config = new XmlMapper()
            .readValue(configXml, Configuration.class);

    // then
    assertAll(
            () -> assertThat(config.commit)
                    .satisfies(commitConfig -> assertThat(commitConfig.versionFormat).isEqualTo("commit1-format")),
            () -> assertThat(config.branch).isEmpty(),
            () -> assertThat(config.tag).isEmpty()
            );
}
 
Example #3
Source File: AbstractJobParametersDeserializer.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public T deserialize( JsonParser p, DeserializationContext ctxt ) throws IOException
{
    final ObjectCodec oc = p.getCodec();
    final JsonNode jsonNode;

    if ( oc instanceof XmlMapper )
    {
        jsonNode = createJsonNode( p, ctxt );
        return objectMapper.treeToValue( jsonNode, overrideClass );
    }
    else
    {
        jsonNode = oc.readTree( p );
        // original object mapper must be used since it may have different serialization settings
        return oc.treeToValue( jsonNode, overrideClass );
    }
}
 
Example #4
Source File: JacksonSingleton.java    From wisdom with Apache License 2.0 6 votes vote down vote up
private void applyMapperConfiguration(ObjectMapper mapper, XmlMapper xml) {
    Configuration conf = null;

    // Check for test.
    if (configuration != null) {
        conf = configuration.getConfiguration("jackson");
    }

    if (conf == null) {
        LOGGER.info("Using default (Wisdom) configuration of Jackson");
        LOGGER.info("FAIL_ON_UNKNOWN_PROPERTIES is disabled");
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        xml.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    } else {
        LOGGER.info("Applying custom configuration on Jackson mapper");
        Set<String> keys = conf.asMap().keySet();
        for (String key : keys) {
            setFeature(mapper, xml, key, conf.getBoolean(key));
        }
    }
}
 
Example #5
Source File: VeeamClient.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private String findDCHierarchy(final String vmwareDcName) {
    LOG.debug("Trying to find hierarchy ID for vmware datacenter: " + vmwareDcName);

    try {
        final HttpResponse response = get("/hierarchyRoots");
        checkResponseOK(response);
        final ObjectMapper objectMapper = new XmlMapper();
        final EntityReferences references = objectMapper.readValue(response.getEntity().getContent(), EntityReferences.class);
        for (final Ref ref : references.getRefs()) {
            if (ref.getName().equals(vmwareDcName) && ref.getType().equals("HierarchyRootReference")) {
                return ref.getUid();
            }
        }
    } catch (final IOException e) {
        LOG.error("Failed to list Veeam jobs due to:", e);
        checkResponseTimeOut(e);
    }
    throw new CloudRuntimeException("Failed to find hierarchy reference for VMware datacenter " + vmwareDcName + " in Veeam, please ask administrator to check Veeam B&R manager configuration");
}
 
Example #6
Source File: MappingJackson2XmlViewTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void renderWithCustomSerializerLocatedByFactory() throws Exception {
	SerializerFactory factory = new DelegatingSerializerFactory(null);
	XmlMapper mapper = new XmlMapper();
	mapper.setSerializerFactory(factory);
	view.setObjectMapper(mapper);

	Object bean = new TestBeanSimple();
	Map<String, Object> model = new HashMap<>();
	model.put("foo", bean);

	view.render(model, request, response);

	String result = response.getContentAsString();
	assertTrue(result.length() > 0);
	assertTrue(result.contains("custom</testBeanSimple>"));

	validateResult();
}
 
Example #7
Source File: XMLExporter.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void exportStream(OutputStream outputStream, Iterator<T> iterator) throws IOException, ClassNotFoundException, IllegalAccessException {
    JacksonXmlModule module = new JacksonXmlModule();
    module.setDefaultUseWrapper(false);
    XmlMapper xmlMapper = new XmlMapper(module);
    XmlFactory factory = new XmlFactory();
    ToXmlGenerator generator = factory.createGenerator(outputStream);

    generator.setCodec(xmlMapper);
    generator.writeRaw("<xml>");

    while (iterator.hasNext()) {

        generator.writeRaw(xmlMapper.writeValueAsString(iterator.next()));
    }
    generator.writeRaw("</xml>");

    generator.flush();
}
 
Example #8
Source File: ResponseWithExceptionTestIT.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyApiExceptionAsXml() throws IOException {
    try {
        final Map<String, String> headerParams = Collections.singletonMap(HttpHeaders.ACCEPT,
                MediaType.APPLICATION_XML);
        client.invokeAPI("/throwApiException", "GET", new HashMap<String, String>(), null,
                headerParams, null, null, null, new String[0]);
        Assert.fail("Exception was expected!");
    } catch (ApiException e) {
        final Response.Status expected = Response.Status.CONFLICT;
        Assert.assertEquals(e.getCode(), expected.getStatusCode());
        final ApiError error = new XmlMapper().readValue(e.getMessage(), ApiError.class);
        Assert.assertEquals(error.getCode(), expected.getStatusCode());
        Assert.assertEquals(error.getMessage(), expected.getReasonPhrase());
    }
}
 
Example #9
Source File: XMLSerializeDeserializeUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenJavaDeserializedFromXmlFile_thenCorrect() throws IOException {
    XmlMapper xmlMapper = new XmlMapper();

    String xml = "<person><firstName>Rohan</firstName><lastName>Daye</lastName><phoneNumbers><phoneNumbers>9911034731</phoneNumbers><phoneNumbers>9911033478</phoneNumbers></phoneNumbers><address><address><streetNumber>1</streetNumber><streetName>Name1</streetName><city>City1</city></address><address><streetNumber>2</streetNumber><streetName>Name2</streetName><city>City2</city></address></address></person>";
    Person value = xmlMapper.readValue(xml, Person.class);

    assertTrue(value.getAddress()
        .get(0)
        .getCity()
        .equalsIgnoreCase("city1")
        && value.getAddress()
            .get(1)
            .getCity()
            .equalsIgnoreCase("city2"));
}
 
Example #10
Source File: Allure1Plugin.java    From allure2 with Apache License 2.0 5 votes vote down vote up
public Allure1Plugin() {
    final SimpleModule module = new XmlParserModule()
            .addDeserializer(ru.yandex.qatools.allure.model.Status.class, new StatusDeserializer());
    xmlMapper = new XmlMapper()
            .configure(USE_WRAPPER_NAME_AS_PROPERTY_NAME, true)
            .setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()))
            .registerModule(module);
}
 
Example #11
Source File: XML.java    From nifi-swagger-client with Apache License 2.0 5 votes vote down vote up
private  <T> T readError(String error, Type returnType) throws ApiException {
    try {
        // Fallback processing when failed to parse XML form response body:
        //   return the response body string directly for the String return type;
        //   parse response body into date or datetime for the Date return type.
        if (returnType.equals(String.class))
            return (T) error;
        XmlMapper xmlMapper = new XmlMapper();
        ErrorResponse value = xmlMapper.readValue(error, ErrorResponse.class);
        throw new ApiException(Integer.valueOf(value.getStatus()), value.getStatusText());
    } catch (NumberFormatException | IOException ea) {
       throw new ApiException(error);
    }
}
 
Example #12
Source File: RestTemplateBasicLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException {
    final RestTemplate template = new RestTemplate();
    final ResponseEntity<String> response = template.getForEntity(fooResourceUrl + "/1", String.class);

    final ObjectMapper mapper = new XmlMapper();
    final JsonNode root = mapper.readTree(response.getBody());
    final JsonNode name = root.path("name");
    assertThat(name.asText(), notNullValue());
}
 
Example #13
Source File: ConfigFileReader.java    From streamline with Apache License 2.0 5 votes vote down vote up
private Map<String, String> readConfigFromHadoopXmlType(InputStream configFileStream) throws IOException {
    ObjectReader reader = new XmlMapper().reader();
    HadoopXml hadoopXml = reader.forType(HadoopXml.class).readValue(configFileStream);

    Map<String, String> configMap = new HashMap<>();
    for (HadoopXml.HadoopXmlProperty property : hadoopXml.getProperties()) {
        configMap.put(property.getName(), property.getValue());
    }

    return configMap;
}
 
Example #14
Source File: WebMvcConfigurationSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void requestMappingHandlerAdapter() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
	List<HttpMessageConverter<?>> converters = adapter.getMessageConverters();
	assertEquals(9, converters.size());
	for(HttpMessageConverter<?> converter : converters) {
		if (converter instanceof AbstractJackson2HttpMessageConverter) {
			ObjectMapper objectMapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper();
			assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
			assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
			assertFalse(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
			if (converter instanceof MappingJackson2XmlHttpMessageConverter) {
				assertEquals(XmlMapper.class, objectMapper.getClass());
			}
		}
	}

	ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
	assertNotNull(initializer);

	ConversionService conversionService = initializer.getConversionService();
	assertNotNull(conversionService);
	assertTrue(conversionService instanceof FormattingConversionService);

	Validator validator = initializer.getValidator();
	assertNotNull(validator);
	assertTrue(validator instanceof LocalValidatorFactoryBean);

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
	@SuppressWarnings("unchecked")
	List<Object> bodyAdvice = (List<Object>) fieldAccessor.getPropertyValue("requestResponseBodyAdvice");
	assertEquals(2, bodyAdvice.size());
	assertEquals(JsonViewRequestBodyAdvice.class, bodyAdvice.get(0).getClass());
	assertEquals(JsonViewResponseBodyAdvice.class, bodyAdvice.get(1).getClass());
}
 
Example #15
Source File: Jackson2ObjectMapperBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public ObjectMapper create() {
	XMLInputFactory inputFactory = XMLInputFactory.newInstance();
	inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
	inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
	inputFactory.setXMLResolver(NO_OP_XML_RESOLVER);
	return new XmlMapper(inputFactory);
}
 
Example #16
Source File: MappingJackson2XmlHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a new {@code MappingJackson2XmlHttpMessageConverter} with a custom {@link ObjectMapper}
 * (must be a {@link XmlMapper} instance).
 * You can use {@link Jackson2ObjectMapperBuilder} to build it easily.
 * @see Jackson2ObjectMapperBuilder#xml()
 */
public MappingJackson2XmlHttpMessageConverter(ObjectMapper objectMapper) {
	super(objectMapper, new MediaType("application", "xml", DEFAULT_CHARSET),
			new MediaType("text", "xml", DEFAULT_CHARSET),
			new MediaType("application", "*+xml", DEFAULT_CHARSET));
	Assert.isAssignable(XmlMapper.class, objectMapper.getClass());
}
 
Example #17
Source File: Jackson2ObjectMapperBuilderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void createXmlMapper() {
	Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json().indentOutput(true);
	ObjectMapper jsonObjectMapper = builder.build();
	ObjectMapper xmlObjectMapper = builder.createXmlMapper(true).build();
	assertTrue(jsonObjectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT));
	assertTrue(xmlObjectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT));
	assertTrue(xmlObjectMapper.getClass().isAssignableFrom(XmlMapper.class));
}
 
Example #18
Source File: Jackson2ObjectMapperFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void setObjectMapper() {
	this.factory.setObjectMapper(new XmlMapper());
	this.factory.afterPropertiesSet();

	assertNotNull(this.factory.getObject());
	assertTrue(this.factory.isSingleton());
	assertEquals(XmlMapper.class, this.factory.getObjectType());
}
 
Example #19
Source File: BasicSerializableRepository.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public String toXML(T t) {
    String xml = "";
    if (t != null) {
        sessionFactory.getCurrentSession().refresh(t);
        final XmlMapper mapper = createXMLMapper();
        try {
            xml = mapper.writeValueAsString(t);
        } catch (JsonProcessingException e) {
            log.warn("Could not serialize to xml", e);
            xml = "";
        }
    }
    return xml;
}
 
Example #20
Source File: BeerOrderTest.java    From spring-cloud-contract-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldProcessBeerOrder() throws Exception {
	//remove::start[]
	XmlMapper xmlMapper = new XmlMapper();
	this.mockMvc.perform(MockMvcRequestBuilders.post("/order")
			.contentType(MediaType.APPLICATION_XML)
			.content(xmlMapper
					.writeValueAsString(new BeerOrder(new BigDecimal("123"), Arrays
							.asList("abc", "def", "ghi")))))
			.andExpect(status().isOk());
	//remove::end[]
}
 
Example #21
Source File: FilteringJacksonXMLProvider.java    From ameba with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected XMLEndpointConfig _configForWriting(final XmlMapper mapper, final Annotation[] annotations,
                                              final Class<?> defaultView) {

    return super._configForWriting(
            (XmlMapper) JacksonUtils.configFilterIntrospector(mapper)
            , annotations, defaultView);
}
 
Example #22
Source File: XMLSerializeDeserializeUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenJavaSerializedToXmlFileWithCapitalizedField_thenCorrect() throws IOException {
    XmlMapper xmlMapper = new XmlMapper();
    xmlMapper.writeValue(new File("target/simple_bean_capitalized.xml"), new SimpleBeanForCapitalizedFields());
    File file = new File("target/simple_bean_capitalized.xml");
    assertNotNull(file);
}
 
Example #23
Source File: ErrorMap.java    From syndesis with Apache License 2.0 5 votes vote down vote up
/**
 * Performs best effort to parse the rawMsg. If all parsers fail it returns the raw message.
 *
 * @return the underlying error message.
 */
public static String from(String rawMsg) {
    if (rawMsg.matches("^\\s*\\<.*")) {
        return parseWith(rawMsg, new XmlMapper());
    }
    if (rawMsg.matches("^\\s*\\{.*")) {
        return parseWith(rawMsg, new ObjectMapper());
    }
    return rawMsg;
}
 
Example #24
Source File: XMLSerializeDeserializeUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenJavaSerializedToXmlFile_thenCorrect() throws IOException {
    XmlMapper xmlMapper = new XmlMapper();
    xmlMapper.writeValue(new File("target/simple_bean.xml"), new SimpleBean());
    File file = new File("target/simple_bean.xml");
    assertNotNull(file);
}
 
Example #25
Source File: T.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
@Test
public void t9() throws JsonProcessingException {
	UnifiedOrder order = new UnifiedOrder();
	order.setAppid("1");
	 XmlMapper xmlMapper = new XmlMapper();
	 xmlMapper.setSerializationInclusion(Include.NON_NULL);
	String writeValueAsString = xmlMapper.writeValueAsString(order);
	 System.out.println(writeValueAsString);
	 UnifiedOrder xmlToBean = WxUtils.xmlToBean(writeValueAsString, UnifiedOrder.class);
	 System.out.println(JSON.toJSONString(xmlToBean));
}
 
Example #26
Source File: S3ProxyHandler.java    From s3proxy with Apache License 2.0 5 votes vote down vote up
private static void handleSetContainerAcl(HttpServletRequest request,
        HttpServletResponse response, InputStream is, BlobStore blobStore,
        String containerName) throws IOException, S3Exception {
    ContainerAccess access;

    String cannedAcl = request.getHeader(AwsHttpHeaders.ACL);
    if (cannedAcl == null || "private".equalsIgnoreCase(cannedAcl)) {
        access = ContainerAccess.PRIVATE;
    } else if ("public-read".equalsIgnoreCase(cannedAcl)) {
        access = ContainerAccess.PUBLIC_READ;
    } else if (CANNED_ACLS.contains(cannedAcl)) {
        throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED);
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    PushbackInputStream pis = new PushbackInputStream(is);
    int ch = pis.read();
    if (ch != -1) {
        pis.unread(ch);
        AccessControlPolicy policy = new XmlMapper().readValue(
                pis, AccessControlPolicy.class);
        String accessString = mapXmlAclsToCannedPolicy(policy);
        if (accessString.equals("private")) {
            access = ContainerAccess.PRIVATE;
        } else if (accessString.equals("public-read")) {
            access = ContainerAccess.PUBLIC_READ;
        } else {
            throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED);
        }
    }

    blobStore.setContainerAccess(containerName, access);
}
 
Example #27
Source File: SerializationProvider.java    From Web-API with MIT License 5 votes vote down vote up
@Override
public ObjectMapper locateMapper(Class<?> type, MediaType mediaType) {
    Map<String, String> queryParams = Util.getQueryParams(request);
    boolean xml = MediaType.APPLICATION_XML_TYPE.isCompatible(mediaType);
    // Allow override the media type with a header (for better browser debugging)
    if (queryParams.containsKey("accept")) {
        String acc = queryParams.get("accept");
        if (acc.equalsIgnoreCase("json")) xml = false;
        if (acc.equalsIgnoreCase("xml")) xml = true;
    }

    // If we're serializing an error return a normal XML/Object mapper, just in case the error
    // happened while creating the mapper, so that we don't get an infinite recursion
    if (Throwable.class.isAssignableFrom(type)) {
        return xml ? new XmlMapper() : new ObjectMapper();
    }

    SecurityContext ctx = (SecurityContext)request.getAttribute("security");
    TreeNode perms = SecurityService.permitAllNode();
    if (ctx != null && ctx.getEndpointPerms() != null) {
        perms = ctx.getEndpointPerms();
    }

    Boolean det = (Boolean)request.getAttribute("details");
    boolean details = (det != null && det) || queryParams.containsKey("details");

    SerializeService srv = WebAPI.getSerializeService();
    ObjectMapper mapper = srv.getDefaultObjectMapper(xml, details, perms);
    if (queryParams.containsKey("pretty"))
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
    return mapper;
}
 
Example #28
Source File: WxUtils.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
public static String beanToXml(Object bean) {
	 Assert.notNull(bean,"bean 为null");
	 XmlMapper xmlMapper = new XmlMapper();
	 xmlMapper.setSerializationInclusion(Include.NON_NULL);
	 try {
		return xmlMapper.writeValueAsString(bean);
	} catch (JsonProcessingException e) {
		throw new ServiceException(e.getMessage());
	}
}
 
Example #29
Source File: JacksonSingleton.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the current XML mapper.
 *
 * @return the mapper
 */
@Override
public XmlMapper xmlMapper() {
    synchronized (lock) {
        return xml;
    }
}
 
Example #30
Source File: BasicSerializableRepository.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public T fromXML(String xml) {
    T obj = null;
    if (StringUtils.isNotBlank(xml)) {
        final XmlMapper mapper = createXMLMapper();
        try {
            obj = mapper.readValue(xml, getDomainClass());
        } catch (IOException e) {
            log.warn("Could not deserialize xml", e);
            obj = null;
        }
    }
    return obj;
}