/**
 * 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.security;

import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang3.StringEscapeUtils;

/**
 * @author 田平 create 2019年5月27日上午10:57:45
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

	public XssHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
	}

	@Override
	public String getHeader(String name) {
		String value = super.getHeader(name);
		return StringEscapeUtils.escapeHtml4(value);
	}

	@Override
	public String getParameter(String name) {
		String value = super.getParameter(name);
		return StringEscapeUtils.escapeHtml4(value);
	}

	@Override
	public String[] getParameterValues(String name) {
		String[] values = super.getParameterValues(name);
		if (values != null) {
			int length = values.length;
			String[] escapeValues = new String[length];
			for (int i = 0; i < length; i++) {
				escapeValues[i] = StringEscapeUtils.escapeHtml4(values[i]);
			}
			return escapeValues;
		} else {
			return null;
		}
	}

	@Override
	public Map<String, String[]> getParameterMap() {
		Map<String, String[]> map = super.getParameterMap();
		if (map != null) {
			Map<String, String[]> clone = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> {
				String[] values = entry.getValue();
				if (values != null) {
					String[] newValues = new String[values.length];
					for (int i = 0; i < values.length; i++) {
						newValues[i] = StringEscapeUtils.escapeHtml4(values[i]);
					}
				}
				return values;
			}));
			return Collections.unmodifiableMap(clone);
		} else {
			return null;
		}
	}

}
