org.apache.http.impl.client.AbstractResponseHandler#com.fasterxml.jackson.dataformat.xml.XmlMapper源码实例Demo

下面列出了org.apache.http.impl.client.AbstractResponseHandler#com.fasterxml.jackson.dataformat.xml.XmlMapper 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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();
}
 
@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"));
}
 
@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()
            );
}
 
源代码4 项目: blog-tutorials   文件: FunctionConfiguration.java
@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);
    }
  };
}
 
@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());
    }
}
 
源代码6 项目: robe   文件: XMLExporter.java
@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();
}
 
源代码7 项目: cloudstack   文件: VeeamClient.java
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");
}
 
@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 );
    }
}
 
源代码9 项目: wisdom   文件: JacksonSingleton.java
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));
        }
    }
}
 
源代码10 项目: s3proxy   文件: S3ProxyHandler.java
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);
}
 
源代码11 项目: weixin-sdk   文件: AnySetter349Test.java
@Test
public void testUnwrappedWithAny() throws Exception {
    final XmlMapper mapper = new XmlMapper();
    final String xml = "<xml>\n" +
            "<type>type</type>\n" +
            "<x>10</x>\n" +
            "<y>10</y>\n" +
            "<k1>k1</k1>\n" +
            "<k2>k1</k2>\n" +
            "<k3>k1</k3>\n" +
            "</xml>";

    Bean349 value = mapper.readValue(xml, Bean349.class);
    Assert.assertNotNull(value);
}
 
public ObjectMapper create(@Nullable JsonFactory factory) {
	if (factory != null) {
		return new XmlMapper((XmlFactory) factory);
	}
	else {
		return new XmlMapper(StaxUtils.createDefensiveInputFactory());
	}
}
 
public ObjectMapper create(boolean defaultUseWrapper, @Nullable JsonFactory factory) {
	JacksonXmlModule module = new JacksonXmlModule();
	module.setDefaultUseWrapper(defaultUseWrapper);
	if (factory != null) {
		return new XmlMapper((XmlFactory) factory, module);
	}
	else {
		return new XmlMapper(new XmlFactory(StaxUtils.createDefensiveInputFactory()), module);
	}
}
 
源代码14 项目: tutorials   文件: XmlToJsonUnitTest.java
@Test
public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() throws IOException {
    String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>";

    XmlMapper xmlMapper = new XmlMapper();
    JsonNode node = xmlMapper.readTree(flowerXML.getBytes());

    ObjectMapper jsonMapper = new ObjectMapper();
    String json = jsonMapper.writeValueAsString(node);

    assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}");
}
 
源代码15 项目: streamline   文件: ConfigFileWriter.java
private void writeConfigToHadoopXmlTypeFile(Map<String, String> configuration, File destPath)
    throws IOException {
  ObjectMapper objectMapper = new XmlMapper();
  objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

  HadoopXml hadoopXml = new HadoopXml();
  for (Map.Entry<String, String> property : configuration.entrySet()) {
    hadoopXml.addProperty(new HadoopXml.HadoopXmlProperty(property.getKey(), property.getValue()));
  }

  objectMapper.writeValue(destPath, hadoopXml);
}
 
@Test
public void whenJavaSerializedToXmlFile_thenSuccess() throws IOException {
    XmlMapper xmlMapper = new XmlMapper();

    String expectedXml = "<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 person = new Person();

    person.setFirstName("Rohan");
    person.setLastName("Daye");

    List<String> ph = new ArrayList<>();
    ph.add("9911034731");
    ph.add("9911033478");
    person.setPhoneNumbers(ph);

    List<Address> addresses = new ArrayList<>();

    Address address1 = new Address();
    address1.setStreetNumber("1");
    address1.setStreetName("Name1");
    address1.setCity("City1");

    Address address2 = new Address();
    address2.setStreetNumber("2");
    address2.setStreetName("Name2");
    address2.setCity("City2");

    addresses.add(address1);
    addresses.add(address2);

    person.setAddress(addresses);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    xmlMapper.writeValue(byteArrayOutputStream, person);
    assertEquals(expectedXml, byteArrayOutputStream.toString());
}
 
源代码17 项目: streams   文件: SysomosXmlSerDeIT.java
/**
 * before.
 */
@BeforeClass
public void before() {

  XmlFactory xmlFactory = new XmlFactory(new InputFactoryImpl(),
      new OutputFactoryImpl());

  JacksonXmlModule module = new JacksonXmlModule();

  module.setDefaultUseWrapper(false);

  xmlMapper = new XmlMapper(xmlFactory, module);

  xmlMapper
      .configure(
          DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
          Boolean.TRUE);
  xmlMapper
      .configure(
          DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,
          Boolean.TRUE);
  xmlMapper
      .configure(
          DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY,
          Boolean.TRUE);
  xmlMapper.configure(
      DeserializationFeature.READ_ENUMS_USING_TO_STRING,
      Boolean.TRUE);

}
 
源代码18 项目: map-matching   文件: GetBoundsCommand.java
@Override
public void run(Bootstrap bootstrap, Namespace args) {
    XmlMapper xmlMapper = new XmlMapper();
    BBox bbox = BBox.createInverse(false);
    for (File gpxFile : args.<File>getList("gpx")) {
        try {
            Gpx gpx = xmlMapper.readValue(gpxFile, Gpx.class);
            for (Trk trk : gpx.trk) {
                List<Observation> inputGPXEntries = trk.getEntries();
                for (Observation entry : inputGPXEntries) {
                    bbox.update(entry.getPoint().getLat(), entry.getPoint().getLon());
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    System.out.println("bounds: " + bbox);

    // show download only for small areas
    if (bbox.maxLat - bbox.minLat < 0.1 && bbox.maxLon - bbox.minLon < 0.1) {
        double delta = 0.01;
        System.out.println("Get small areas via\n"
                + "wget -O extract.osm 'http://overpass-api.de/api/map?bbox="
                + (bbox.minLon - delta) + "," + (bbox.minLat - delta) + ","
                + (bbox.maxLon + delta) + "," + (bbox.maxLat + delta) + "'");
    }
}
 
@Test
public void requestMappingHandlerAdapter() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
	List<HttpMessageConverter<?>> converters = adapter.getMessageConverters();
	assertEquals(12, converters.size());
	converters.stream()
			.filter(converter -> converter instanceof AbstractJackson2HttpMessageConverter)
			.forEach(converter -> {
				ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter) converter).getObjectMapper();
				assertFalse(mapper.getDeserializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
				assertFalse(mapper.getSerializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
				assertFalse(mapper.getDeserializationConfig().isEnabled(FAIL_ON_UNKNOWN_PROPERTIES));
				if (converter instanceof MappingJackson2XmlHttpMessageConverter) {
					assertEquals(XmlMapper.class, mapper.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());
}
 
/**
 * 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"),
			new MediaType("text", "xml"),
			new MediaType("application", "*+xml"));
	Assert.isInstanceOf(XmlMapper.class, objectMapper, "XmlMapper required");
}
 
@Test  // SPR-13975
public void defaultUseWrapper() throws JsonProcessingException {
	ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.xml().defaultUseWrapper(false).build();
	assertNotNull(objectMapper);
	assertEquals(XmlMapper.class, objectMapper.getClass());
	ListContainer<String> container = new ListContainer<>(Arrays.asList("foo", "bar"));
	String output = objectMapper.writeValueAsString(container);
	assertThat(output, containsString("<list>foo</list><list>bar</list></ListContainer>"));
}
 
源代码22 项目: find   文件: IdolStatsService.java
@Autowired
public IdolStatsService(
        final AciService statsServerAciService,
        final ProcessorFactory processorFactory,
        final XmlMapper xmlMapper,
        final ConfigService<IdolFindConfig> configService
) {
    this.statsServerAciService = statsServerAciService;
    this.processorFactory = processorFactory;
    this.xmlMapper = xmlMapper;
    this.configService = configService;
}
 
源代码23 项目: wisdom   文件: JacksonSingleton.java
/**
 * Sets the object mapper.
 *
 * @param mapper the object mapper to use
 */
private void setMappers(ObjectMapper mapper, XmlMapper xml) {
    synchronized (lock) {
        this.mapper = mapper;
        this.xml = xml;
        // mapper and xml are set to null on invalidation.
        if (mapper != null && xml != null) {
            applyMapperConfiguration(mapper, xml);
        }
    }
}
 
源代码24 项目: joyqueue   文件: GrafanaUtils.java
private static GrafanaConfig load(String file) {
    try {
        logger.info("loading grafana.xml");
        return new XmlMapper().readValue(
                StringUtils.toEncodedString(IOUtils.toByteArray(GrafanaUtils.class.getClassLoader().getResourceAsStream(file)),
                        StandardCharsets.UTF_8), GrafanaConfig.class);
    } catch (IOException e) {
        throw new ConfigException(ErrorCode.ConfigurationNotExists, "load file grafana.xml error.");
    }
}
 
源代码25 项目: archiva   文件: JacksonJsonConfigurator.java
@Inject
public JacksonJsonConfigurator( @Named( "redbackJacksonJsonMapper" ) ObjectMapper objectMapper,
                                @Named( "redbackJacksonXMLMapper" ) XmlMapper xmlMapper )
{

    log.info( "configure jackson ObjectMapper" );
    objectMapper.disable( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    xmlMapper.disable( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES );
}
 
源代码26 项目: seezoon-framework-all   文件: WxUtils.java
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());
	}
}
 
源代码27 项目: weixin-pay   文件: PayUtils.java
/**
 * 
 * @param inputStream request.getInputStream()
 * @return
 */
public static PayNativeInput convertRequest(InputStream inputStream){
	try {
		String content = IOUtils.toString(inputStream);
		
		XmlMapper xmlMapper = new XmlMapper();
		PayNativeInput payNativeInput = xmlMapper.readValue(content, PayNativeInput.class);
		
		return payNativeInput;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
源代码28 项目: seezoon-framework-all   文件: T.java
@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));
}
 
@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);
}
 
源代码30 项目: syndesis   文件: ErrorMap.java
/**
 * 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;
}