All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ifengxue.http.codec.JacksonXmlCodec Maven / Gradle / Ivy

/*
 * Copyright 2019 https://www.ifengxue.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ifengxue.http.codec;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlFactory;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator.Feature;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;
import javax.xml.stream.XMLInputFactory;

/**
 * jackson xml codec
 */
public class JacksonXmlCodec implements XmlCodec {

  private final XmlMapper xmlMapper;

  public JacksonXmlCodec() {
    this(createXmlMapper());
  }

  private static XmlMapper createXmlMapper() {
    JacksonXmlModule module = new JacksonXmlModule();
    module.setDefaultUseWrapper(true);
    XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
    XmlFactory xmlFactory = new XmlFactory(xmlInputFactory);
    XmlMapper xmlMapper = new XmlMapper(xmlFactory, module);
    xmlMapper.enable(Feature.WRITE_XML_DECLARATION);
    xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
    return xmlMapper;
  }

  public JacksonXmlCodec(XmlMapper xmlMapper) {
    this.xmlMapper = xmlMapper;
  }

  @Override
  public  String encode(T obj) {
    try {
      return xmlMapper.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
      throw new CodecException(e);
    }
  }

  @Override
  public  Map decode(T obj) {
    try {
      return xmlMapper.readValue(encode(obj), new TypeReference>() {
      });
    } catch (IOException e) {
      throw new CodecException(e);
    }
  }

  @Override
  public  T decode(String text, Type type) {
    try {
      return xmlMapper.readValue(text, new TypeReference() {
        @Override
        public Type getType() {
          return type;
        }
      });
    } catch (IOException e) {
      throw new CodecException(e);
    }
  }

  @Override
  public  T decode(String text, Class clazz) {
    try {
      return xmlMapper.readValue(text, clazz);
    } catch (IOException e) {
      throw new CodecException(e);
    }
  }
}