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

The following examples show how to use com.fasterxml.jackson.dataformat.xml.XmlFactory. 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: ClientODataDeserializerImpl.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
protected XmlMapper getXmlMapper() {
  final XmlMapper xmlMapper = new XmlMapper(
      new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl()), new JacksonXmlModule());

  xmlMapper.setInjectableValues(new InjectableValues.Std().addValue(Boolean.class, Boolean.FALSE));

  xmlMapper.addHandler(new DeserializationProblemHandler() {
    @Override
    public boolean handleUnknownProperty(final DeserializationContext ctxt, final JsonParser jp,
        final com.fasterxml.jackson.databind.JsonDeserializer<?> deserializer,
        final Object beanOrClass, final String propertyName)
        throws IOException, JsonProcessingException {

      // skip any unknown property
      ctxt.getParser().skipChildren();
      return true;
    }
  });
  return xmlMapper;
}
 
Example #2
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 #3
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 #4
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 #5
Source File: JacksonXML.java    From dropwizard-xml with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link com.fasterxml.jackson.dataformat.xml.XmlMapper} using Woodstox
 * with Logback and Joda Time support.
 * Also includes all {@link io.dropwizard.jackson.Discoverable} interface implementations.
 *
 * @return XmlMapper
 */
public static XmlMapper newXMLMapper(JacksonXmlModule jacksonXmlModule) {

    final XmlFactory woodstoxFactory = new XmlFactory(new WstxInputFactory(), new WstxOutputFactory());
    final XmlMapper mapper = new XmlMapper(woodstoxFactory, jacksonXmlModule);

    mapper.registerModule(new GuavaModule());
    mapper.registerModule(new GuavaExtrasModule());
    mapper.registerModule(new JodaModule());
    mapper.registerModule(new FuzzyEnumModule());
    mapper.setPropertyNamingStrategy(new AnnotationSensitivePropertyNamingStrategy());
    mapper.setSubtypeResolver(new DiscoverableSubtypeResolver());

    return mapper;
}
 
Example #6
Source File: BasicSerializableRepository.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private XmlMapper createXMLMapper() {
    final XMLInputFactory ifactory = new WstxInputFactory();
    ifactory.setProperty(WstxInputProperties.P_MAX_ATTRIBUTE_SIZE, 32000);
    ifactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);

    final XMLOutputFactory ofactory = new WstxOutputFactory();
    ofactory.setProperty(WstxOutputProperties.P_OUTPUT_CDATA_AS_TEXT, true);
    ofactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

    final XmlFactory xf = new XmlFactory(ifactory, ofactory);

    final XmlMapper mapper = new XmlMapper(xf);
    mapper.registerModules(new JavaTimeModule());
    return mapper;
}
 
Example #7
Source File: SysomosXmlSerDeIT.java    From streams with Apache License 2.0 5 votes vote down vote up
/**
 * 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);

}
 
Example #8
Source File: XMLServiceDocumentDeserializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public ResWrap<ServiceDocument> toServiceDocument(InputStream input) throws ODataDeserializerException {
  try {
    JsonParser parser = new XmlFactory().createParser(input);
    return doDeserialize(parser);
  } catch (final IOException e) {
    throw new ODataDeserializerException(e);
  }
}
 
Example #9
Source File: ParserUtil.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static JsonParser getParser(String xml) throws Exception {
    XmlFactory factory = new XmlFactory();
    JsonParser parser = factory.createParser(xml);
    parser.nextToken();
    parser.nextToken();
    parser.nextToken();
    return parser;
}
 
Example #10
Source File: XMLImporter.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void importStream(InputStream inputStream, OnItemHandler handler, String charSetName) throws Exception {

    XmlFactory factory = new XmlFactory();
    JsonParser parser = factory.createParser(new InputStreamReader(inputStream, charSetName));

    Map<String, Field> fields = getFieldMap(getDataClass());

    while (parser.nextToken() != JsonToken.END_OBJECT) {
        try {
            parser.getCurrentName();
        } catch (Exception e) {
            continue;
        }
        if (getDataClass().getSimpleName().equals(parser.getValueAsString())) {
            T item = (T) getDataClass().newInstance();
            while (parser.nextToken() != JsonToken.END_OBJECT) {
                if (parser.getValueAsString() == null || parser.getCurrentToken() == JsonToken.FIELD_NAME)
                    continue;
                Field field = fields.get(parser.getCurrentName());
                setField(parser, item, field);
            }
            handler.onItem(item);
        }

    }

}
 
Example #11
Source File: BasicSerializableRepository.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private XmlMapper createXMLMapper() {
    final XMLInputFactory ifactory = new WstxInputFactory();
    ifactory.setProperty(WstxInputProperties.P_MAX_ATTRIBUTE_SIZE, 32000);
    ifactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);

    final XMLOutputFactory ofactory = new WstxOutputFactory();
    ofactory.setProperty(WstxOutputProperties.P_OUTPUT_CDATA_AS_TEXT, true);
    ofactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

    final XmlFactory xf = new XmlFactory(ifactory, ofactory);

    final XmlMapper mapper = new XmlMapper(xf);
    mapper.registerModules(new JavaTimeModule());
    return mapper;
}
 
Example #12
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 #13
Source File: Jackson2ObjectMapperBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
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);
	}
}
 
Example #14
Source File: Jackson2ObjectMapperBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public ObjectMapper create(@Nullable JsonFactory factory) {
	if (factory != null) {
		return new XmlMapper((XmlFactory) factory);
	}
	else {
		return new XmlMapper(StaxUtils.createDefensiveInputFactory());
	}
}
 
Example #15
Source File: Jackson2ObjectMapperBuilder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public ObjectMapper create(boolean defaultUseWrapper) {
	JacksonXmlModule module = new JacksonXmlModule();
	module.setDefaultUseWrapper(defaultUseWrapper);
	return new XmlMapper(new XmlFactory(xmlInputFactory()), module);
}
 
Example #16
Source File: FormatInputStream.java    From vespa with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a single data input stream from either file or InputStream depending on which one is present. Preference
 * for file if both present. Additionally also detects input data format of the result stream, throws
 * IllegalArgumentException if unable to determine data format.
 *
 * @param stream              InputStream of the data if present
 * @param inputFile           path to file to use as input
 * @param addRootElementToXml to add vespafeed root element around the input data stream
 * @throws IOException        on errors
 */
public FormatInputStream(InputStream stream, Optional<String> inputFile, boolean addRootElementToXml)
        throws IOException {
    DataFormatDetector dataFormatDetector = new DataFormatDetector(new JsonFactory(), new XmlFactory());
    DataFormatMatcher formatMatcher;

    if (inputFile.isPresent()) {
        try (FileInputStream fileInputStream = new FileInputStream(inputFile.get())) {
            formatMatcher = dataFormatDetector.findFormat(fileInputStream);
        }
        inputStream = new FileInputStream(inputFile.get());

    } else {
        if (stream.available() == 0)
            System.out.println("No data in stream yet and no file specified, waiting for data.");

        inputStream = stream.markSupported() ? stream : new BufferedInputStream(stream);
        inputStream.mark(DataFormatDetector.DEFAULT_MAX_INPUT_LOOKAHEAD);
        formatMatcher = dataFormatDetector.findFormat(inputStream);
        inputStream.reset();
    }

    if (addRootElementToXml) {
        inputStream = addVespafeedTag(inputStream);
        format = Format.XML;
        return;
    }

    if (formatMatcher.getMatchStrength() == MatchStrength.INCONCLUSIVE
        || formatMatcher.getMatchStrength() == MatchStrength.NO_MATCH) {
        throw new IllegalArgumentException("Could not detect input format");
    }

    switch (formatMatcher.getMatchedFormatName().toLowerCase()) {
        case "json":
            format = Format.JSON;
            break;
        case "xml":
            format = Format.XML;
            break;
        default:
            throw new IllegalArgumentException("Unknown data format");
    }
}
 
Example #17
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 #18
Source File: XmlDeserializer.java    From httpdoc with Apache License 2.0 4 votes vote down vote up
public XmlDeserializer(XmlFactory factory) {
    this(new XmlMapper(factory));
}
 
Example #19
Source File: XmlDeserializer.java    From httpdoc with Apache License 2.0 4 votes vote down vote up
public XmlDeserializer() {
    this(new XmlFactory());
}
 
Example #20
Source File: XmlSerializer.java    From httpdoc with Apache License 2.0 4 votes vote down vote up
public XmlSerializer(XmlFactory factory) {
    this(new XmlMapper(factory));
}
 
Example #21
Source File: XmlSerializer.java    From httpdoc with Apache License 2.0 4 votes vote down vote up
public XmlSerializer() {
    this(new XmlFactory());
}
 
Example #22
Source File: Jackson2ObjectMapperBuilder.java    From java-technology-stack with MIT License 4 votes vote down vote up
public ObjectMapper create(boolean defaultUseWrapper) {
	JacksonXmlModule module = new JacksonXmlModule();
	module.setDefaultUseWrapper(defaultUseWrapper);
	return new XmlMapper(new XmlFactory(StaxUtils.createDefensiveInputFactory()), module);
}
 
Example #23
Source File: XmlXContent.java    From elasticsearch-xml with Apache License 2.0 4 votes vote down vote up
protected static XmlFactory xmlFactory() {
    return xmlFactory;
}
 
Example #24
Source File: XmlDeserializer.java    From halo-docs with Apache License 2.0 4 votes vote down vote up
public XmlDeserializer(XmlFactory factory) {
    this(new XmlMapper(factory));
}
 
Example #25
Source File: MoreoverResult.java    From streams with Apache License 2.0 4 votes vote down vote up
protected MoreoverResult(String clientId, String xmlString, long start, long end) {
  this.xmlString = xmlString;
  this.clientId = clientId;
  this.start = start;
  this.end = end;
  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);
  xmlMapper.configure(
      DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
      Boolean.FALSE);

  ObjectMapper mapper = new ObjectMapper();

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

}
 
Example #26
Source File: XmlDeserializer.java    From halo-docs with Apache License 2.0 4 votes vote down vote up
public XmlDeserializer() {
    this(new XmlFactory());
}
 
Example #27
Source File: XmlSerializer.java    From halo-docs with Apache License 2.0 4 votes vote down vote up
public XmlSerializer(XmlFactory factory) {
    this(new XmlMapper(factory));
}
 
Example #28
Source File: XmlSerializer.java    From halo-docs with Apache License 2.0 4 votes vote down vote up
public XmlSerializer() {
    this(new XmlFactory());
}