com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator Java Examples

The following examples show how to use com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator. 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: ApiClient.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Build the RestTemplate used to make HTTP requests.
 * @return RestTemplate
 */
protected RestTemplate buildRestTemplate() {
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(new MappingJackson2HttpMessageConverter());
    XmlMapper xmlMapper = new XmlMapper();
    xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
    xmlMapper.registerModule(new JsonNullableModule());
    messageConverters.add(new MappingJackson2XmlHttpMessageConverter(xmlMapper));

    RestTemplate restTemplate = new RestTemplate(messageConverters);
    
    for(HttpMessageConverter converter:restTemplate.getMessageConverters()){
        if(converter instanceof AbstractJackson2HttpMessageConverter){
            ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper();
            ThreeTenModule module = new ThreeTenModule();
            module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
            module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
            module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
            mapper.registerModule(module);
            mapper.registerModule(new JsonNullableModule());
        }
    }
    // This allows us to read the response more than once - Necessary for debugging.
    restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory()));
    return restTemplate;
}
 
Example #2
Source File: StAXNodeSerializer.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @param simpleNode the {@link SimpleNode}.
 * @param writer the {@link XMLStreamWriter}.
 *
 * @return true if given simpleNode has been serialized using custom JsonSerializer
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws IOException
 */
private boolean handledCustomSerializer( SimpleNode simpleNode, XMLStreamWriter writer )
    throws IllegalAccessException, InstantiationException, IOException
{
    if ( simpleNode.getProperty() != null )
    {
        JsonSerialize declaredAnnotation = simpleNode.getProperty().getGetterMethod().getAnnotation( JsonSerialize.class );
        if ( declaredAnnotation != null )
        {
            Class<? extends JsonSerializer> serializer = declaredAnnotation.using();

            if ( serializer != null )
            {
                JsonSerializer serializerInstance = serializer.newInstance();
                XmlFactory factory = new XmlFactory();
                ToXmlGenerator generator = factory.createGenerator( writer );
                serializerInstance.serialize( simpleNode.getValue(), generator, null );
                return true;
            }
        }
    }
    return false;
}
 
Example #3
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 #4
Source File: VeeamClient.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private HttpResponse post(final String path, final Object obj) throws IOException {
    String xml = null;
    if (obj != null) {
        XmlMapper xmlMapper = new XmlMapper();
        xml = xmlMapper.writer()
                .with(ToXmlGenerator.Feature.WRITE_XML_DECLARATION)
                .writeValueAsString(obj);
        // Remove invalid/empty xmlns
        xml = xml.replace(" xmlns=\"\"", "");
    }

    final HttpPost request = new HttpPost(apiURI.toString() + path);
    request.setHeader(SESSION_HEADER, veeamSessionId);
    request.setHeader("Content-type", "application/xml");
    if (StringUtils.isNotBlank(xml)) {
        request.setEntity(new StringEntity(xml));
    }

    final HttpResponse response = httpClient.execute(request);
    checkAuthFailure(response);
    return response;
}
 
Example #5
Source File: SerializeService.java    From Web-API with MIT License 5 votes vote down vote up
public ObjectMapper getDefaultObjectMapper(boolean xml, boolean details, TreeNode perms) {
    if (perms == null) {
        throw new NullPointerException("Permissions may not be null");
    }

    ObjectMapper om = xml ? new XmlMapper() : new ObjectMapper();
    if (xml) {
        ((XmlMapper)om).configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
    }
    om.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    SimpleModule mod = new SimpleModule();
    for (Map.Entry<Class, BaseSerializer> entry : serializers.entrySet()) {
        mod.addSerializer(entry.getKey(), entry.getValue());
    }
    mod.addDeserializer(ItemStack.class, new ItemStackDeserializer());
    mod.addDeserializer(BlockState.class, new BlockStateDeserializer());
    mod.addDeserializer(ItemStackSnapshot.class, new ItemStackSnapshotDeserializer());
    mod.addDeserializer(CachedLocation.class, new CachedLocationDeserializer());
    mod.addDeserializer(CachedPlayer.class, new CachedPlayerDeserializer());
    mod.addDeserializer(CachedWorld.class, new CachedWorldDeserializer());
    mod.addDeserializer(CachedCatalogType.class, new CachedCatalogTypeDeserializer<>(CatalogType.class));
    om.registerModule(mod);

    SimpleFilterProvider filterProvider = new SimpleFilterProvider();
    filterProvider.addFilter(BaseFilter.ID, new BaseFilter(details, perms));
    om.setFilterProvider(filterProvider);

    om.setAnnotationIntrospector(new AnnotationIntrospector());

    return om;
}
 
Example #6
Source File: CustomLastUpdatedUserSerializerTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void serializeXml() throws Exception
{
    Writer jsonWriter = new StringWriter();
    ToXmlGenerator jsonGenerator = new XmlFactory().createGenerator( jsonWriter );
    SerializerProvider serializerProvider = new ObjectMapper().getSerializerProvider();
    jsonGenerator.setNextName( new QName( "urn:test", "lastUpdatedBy" ) );
    new CustomLastUpdatedUserSerializer().serialize( user, jsonGenerator, serializerProvider );
    jsonGenerator.flush();
    assertEquals( "<wstxns1:lastUpdatedBy xmlns:wstxns1=\"urn:test\" id=\"jshfdkd323\" name=\"Peter Brown\"/>", jsonWriter.toString() );
}
 
Example #7
Source File: XmlXContentGenerator.java    From elasticsearch-xml with Apache License 2.0 5 votes vote down vote up
public XmlXContentGenerator(ToXmlGenerator generator) {
    this.generator = generator;
    this.params = new XmlXParams();
    this.started = false;
    this.context = false;
    this.prefix = null;
    generator.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, false);
}
 
Example #8
Source File: GsonJacksonBridgeSerializationTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
public void xmlFactoryTest() throws IOException {
  TestObject value = createTestObject();
  XmlFactory factory = new XmlFactory();
  Class<TestObject> clazz = TestObject.class;
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  ToXmlGenerator g = factory.createGenerator(outputStream);
  g.setNextName(QName.valueOf(clazz.getAnnotation(JacksonXmlRootElement.class).localName()));
  JsonGeneratorWriter generatorWriter = new JsonGeneratorWriter(g);
  gson.toJson(value, clazz, generatorWriter);
  generatorWriter.flush();
  TestObject value2 = testXmlReading(factory, clazz, outputStream);
  Assert.assertEquals(value2.toString(), value.toString());
}
 
Example #9
Source File: XmlModule.java    From proteus with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure() {

    XMLInputFactory inputFactory = new WstxInputFactory();
    inputFactory.setProperty(WstxInputProperties.P_MAX_ATTRIBUTE_SIZE, 32000);

    bind(XMLInputFactory.class).toInstance(inputFactory);

    XMLOutputFactory outputFactory = new WstxOutputFactory();
    outputFactory.setProperty(WstxOutputProperties.P_OUTPUT_CDATA_AS_TEXT, true);

    bind(XMLOutputFactory.class).toInstance(outputFactory);

    XmlFactory xmlFactory = new XmlFactory(inputFactory, outputFactory);

    XmlMapper xmlMapper = new XmlMapper(xmlFactory);
    xmlMapper.registerModule(new JavaTimeModule())
             .registerModule(new ParameterNamesModule())
             .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
             .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    xmlMapper.enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION);

    bind(XmlMapper.class).toInstance(xmlMapper);

}
 
Example #10
Source File: JacksonOrganisationUnitChildrenSerializer.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void serialize( OrganisationUnit value, JsonGenerator jgen, SerializerProvider provider ) throws IOException
{
    DateFormat DATE_FORMAT = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssZ" );

    if ( ToXmlGenerator.class.isAssignableFrom( jgen.getClass() ) )
    {
        ToXmlGenerator xmlGenerator = (ToXmlGenerator) jgen;

        try
        {
            XMLStreamWriter staxWriter = xmlGenerator.getStaxWriter();

            staxWriter.writeStartElement( DxfNamespaces.DXF_2_0, "child" );
            staxWriter.writeAttribute( "id", value.getUid() );
            staxWriter.writeAttribute( "name", value.getName() );
            staxWriter.writeAttribute( "created", DATE_FORMAT.format( value.getCreated() ) );
            staxWriter.writeAttribute( "lastUpdated", DATE_FORMAT.format( value.getLastUpdated() ) );

            if ( value.getHref() != null )
            {
                staxWriter.writeAttribute( "href", value.getHref() );
            }

            staxWriter.writeAttribute( "hasChildren", String.valueOf( value.hasChild() ) );
            staxWriter.writeEndElement();
        }
        catch ( XMLStreamException e )
        {
            e.printStackTrace(); //TODO fix
        }
    }
    else
    {
        jgen.writeStartObject();

        jgen.writeStringField( "id", value.getUid() );
        jgen.writeStringField( "name", value.getName() );
        jgen.writeFieldName( "created" );
        provider.defaultSerializeDateValue( value.getCreated(), jgen );

        jgen.writeFieldName( "lastUpdated" );
        provider.defaultSerializeDateValue( value.getLastUpdated(), jgen );

        if ( value.getHref() != null )
        {
            jgen.writeStringField( "href", value.getHref() );
        }

        jgen.writeBooleanField( "hasChildren", value.hasChild() );

        jgen.writeEndObject();
    }
}
 
Example #11
Source File: JacksonOrganisationUnitGroupSymbolSerializer.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void serialize( OrganisationUnitGroup value, JsonGenerator jgen, SerializerProvider provider ) throws IOException
{
    DateFormat DATE_FORMAT = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssZ" );

    if ( ToXmlGenerator.class.isAssignableFrom( jgen.getClass() ) )
    {
        ToXmlGenerator xmlGenerator = (ToXmlGenerator) jgen;

        try
        {
            XMLStreamWriter staxWriter = xmlGenerator.getStaxWriter();

            staxWriter.writeStartElement( DxfNamespaces.DXF_2_0, "organisationUnitGroup" );
            staxWriter.writeAttribute( "id", value.getUid() );
            staxWriter.writeAttribute( "name", value.getName() );
            staxWriter.writeAttribute( "created", DATE_FORMAT.format( value.getCreated() ) );
            staxWriter.writeAttribute( "lastUpdated", DATE_FORMAT.format( value.getLastUpdated() ) );

            if ( value.getHref() != null )
            {
                staxWriter.writeAttribute( "href", value.getHref() );
            }

            staxWriter.writeAttribute( "symbol", String.valueOf( value.getSymbol() ) );
            staxWriter.writeEndElement();
        }
        catch ( XMLStreamException e )
        {
            e.printStackTrace(); //TODO fix
        }
    }
    else
    {
        jgen.writeStartObject();

        jgen.writeStringField( "id", value.getUid() );
        jgen.writeStringField( "name", value.getName() );
        jgen.writeFieldName( "created" );
        provider.defaultSerializeDateValue( value.getCreated(), jgen );

        jgen.writeFieldName( "lastUpdated" );
        provider.defaultSerializeDateValue( value.getLastUpdated(), jgen );

        if ( value.getHref() != null )
        {
            jgen.writeStringField( "href", value.getHref() );
        }

        jgen.writeStringField( "symbol", value.getSymbol() );

        jgen.writeEndObject();
    }
}