/**
 * 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 com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
import org.apache.commons.lang3.StringEscapeUtils;
import org.owasp.html.Sanitizers;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * @author 田平 create 2019年5月27日上午9:29:27
 */
public class XssStringDeserializer extends JsonDeserializer<String> {

	@Override
	public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		String deserialize = StringDeserializer.instance.deserialize(p, ctxt);
		if (StringUtils.hasText(deserialize)) {
			return StringEscapeUtils.unescapeHtml4(deserialize);
		} else {
			return p.getValueAsString();
		}
	}

	public static void main(String[] args) {
		String aa = "{\"a\":\"b\"}aaa<html></html><script></script><javascript></javascript><>smallh1<br>";
		// 过滤使用
		System.out.println(Sanitizers.FORMATTING.sanitize(aa));
		// 简单转义
		System.out.println(StringEscapeUtils.escapeHtml4(aa));
	}

}
