/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.jackson;

import org.springframework.beans.factory.FactoryBean;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;

/**
 * @author 田平 create 2016年3月10日上午11:54:54
 */
public class ObjectMapperFactoryBean implements FactoryBean<ObjectMapper> {

	private boolean enableXssSerializer = false;

	private boolean enableXssDeserializer = true;

	public ObjectMapperFactoryBean() {

	}

	public ObjectMapperFactoryBean(boolean enableXssSerializer, boolean enableXssDeserializer) {
		this.enableXssSerializer = enableXssSerializer;
		this.enableXssDeserializer = enableXssDeserializer;
	}

	public ObjectMapper getObject() throws Exception {
		ObjectMapper jsonMapper = new ObjectMapper();
		jsonMapper.registerModule(new DateModule());
		// 字符串进行html的转义
		if (enableXssSerializer) {
			SimpleModule moduleSe = new SimpleModule("XssStringSerializer");
			moduleSe.addSerializer(String.class, new XssStringSerializer());
			jsonMapper.registerModule(moduleSe);
		}

		if (enableXssDeserializer) {
			SimpleModule moduleDe = new SimpleModule("XssStringDeserializer");
			moduleDe.addDeserializer(String.class, new XssStringDeserializer());
			jsonMapper.registerModule(moduleDe);
		}

		Hibernate5Module hModule = new Hibernate5Module();
		hModule.enable(Hibernate5Module.Feature.FORCE_LAZY_LOADING);
		jsonMapper.registerModule(hModule);
		jsonMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
		jsonMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		jsonMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
		jsonMapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);

		return jsonMapper;
	}

	public Class<?> getObjectType() {
		return ObjectMapper.class;
	}

	public boolean isSingleton() {
		return false;
	}

	/**
	 * @return the enableXssDeserializer
	 */
	public boolean isEnableXssDeserializer() {
		return enableXssDeserializer;
	}

	/**
	 * @param enableXssDeserializer the enableXssDeserializer to set
	 */
	public void setEnableXssDeserializer(boolean enableXssDeserializer) {
		this.enableXssDeserializer = enableXssDeserializer;
	}

	/**
	 * @return the enableXssSerializer
	 */
	public boolean isEnableXssSerializer() {
		return enableXssSerializer;
	}

	/**
	 * @param enableXssSerializer the enableXssSerializer to set
	 */
	public void setEnableXssSerializer(boolean enableXssSerializer) {
		this.enableXssSerializer = enableXssSerializer;
	}

}
