001
014
015 package com.liferay.portal.servlet.filters.validhtml;
016
017 import com.liferay.portal.kernel.log.Log;
018 import com.liferay.portal.kernel.log.LogFactoryUtil;
019 import com.liferay.portal.kernel.servlet.StringServletResponse;
020 import com.liferay.portal.kernel.util.ContentTypes;
021 import com.liferay.portal.kernel.util.HttpUtil;
022 import com.liferay.portal.kernel.util.StringPool;
023 import com.liferay.portal.kernel.util.StringUtil;
024 import com.liferay.portal.servlet.filters.BasePortalFilter;
025 import com.liferay.util.servlet.ServletResponseUtil;
026
027 import javax.servlet.FilterChain;
028 import javax.servlet.http.HttpServletRequest;
029 import javax.servlet.http.HttpServletResponse;
030
031
036 public class ValidHtmlFilter extends BasePortalFilter {
037
038 public static final String SKIP_FILTER =
039 ValidHtmlFilter.class.getName() + "SKIP_FILTER";
040
041 protected String getContent(HttpServletRequest request, String content) {
042 content = StringUtil.replaceLast(
043 content, _CLOSE_BODY, StringPool.BLANK);
044 content = StringUtil.replaceLast(
045 content, _CLOSE_HTML, _CLOSE_BODY + _CLOSE_HTML);
046
047 return content;
048 }
049
050 protected boolean isAlreadyFiltered(HttpServletRequest request) {
051 if (request.getAttribute(SKIP_FILTER) != null) {
052 return true;
053 }
054 else {
055 return false;
056 }
057 }
058
059 protected boolean isEnsureValidHtml(
060 HttpServletRequest request, HttpServletResponse response) {
061
062 String contentType = response.getContentType();
063
064 if ((contentType != null) &&
065 contentType.startsWith(ContentTypes.TEXT_HTML)) {
066
067 return true;
068 }
069 else {
070 return false;
071 }
072 }
073
074 protected void processFilter(
075 HttpServletRequest request, HttpServletResponse response,
076 FilterChain filterChain)
077 throws Exception {
078
079 if (isEnsureValidHtml(request, response) &&
080 !isAlreadyFiltered(request)) {
081
082 request.setAttribute(SKIP_FILTER, Boolean.TRUE);
083
084 if (_log.isDebugEnabled()) {
085 String completeURL = HttpUtil.getCompleteURL(request);
086
087 _log.debug("Ensuring valid HTML " + completeURL);
088 }
089
090 StringServletResponse stringServerResponse =
091 new StringServletResponse(response);
092
093 processFilter(
094 ValidHtmlFilter.class, request, stringServerResponse,
095 filterChain);
096
097 String content = getContent(
098 request, stringServerResponse.getString());
099
100 ServletResponseUtil.write(response, content);
101 }
102 else {
103 if (_log.isDebugEnabled()) {
104 String completeURL = HttpUtil.getCompleteURL(request);
105
106 _log.debug("Not ensuring valid HTML " + completeURL);
107 }
108
109 processFilter(
110 ValidHtmlFilter.class, request, response, filterChain);
111 }
112 }
113
114 private static final String _CLOSE_BODY = "</body>";
115
116 private static final String _CLOSE_HTML = "</html>";
117
118 private static Log _log = LogFactoryUtil.getLog(ValidHtmlFilter.class);
119
120 }