1
14
15 package com.liferay.portal.servlet.filters.validhtml;
16
17 import com.liferay.portal.kernel.log.Log;
18 import com.liferay.portal.kernel.log.LogFactoryUtil;
19 import com.liferay.portal.kernel.servlet.StringServletResponse;
20 import com.liferay.portal.kernel.util.ContentTypes;
21 import com.liferay.portal.kernel.util.HttpUtil;
22 import com.liferay.portal.kernel.util.StringPool;
23 import com.liferay.portal.kernel.util.StringUtil;
24 import com.liferay.portal.servlet.filters.BasePortalFilter;
25 import com.liferay.util.servlet.ServletResponseUtil;
26
27 import javax.servlet.FilterChain;
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
30
31
38 public class ValidHtmlFilter extends BasePortalFilter {
39
40 public static final String SKIP_FILTER =
41 ValidHtmlFilter.class.getName() + "SKIP_FILTER";
42
43 protected String getContent(HttpServletRequest request, String content) {
44 content = StringUtil.replaceLast(
45 content, _CLOSE_BODY, StringPool.BLANK);
46 content = StringUtil.replaceLast(
47 content, _CLOSE_HTML, _CLOSE_BODY + _CLOSE_HTML);
48
49 return content;
50 }
51
52 protected boolean isAlreadyFiltered(HttpServletRequest request) {
53 if (request.getAttribute(SKIP_FILTER) != null) {
54 return true;
55 }
56 else {
57 return false;
58 }
59 }
60
61 protected boolean isEnsureValidHtml(
62 HttpServletRequest request, HttpServletResponse response) {
63
64 String contentType = response.getContentType();
65
66 if ((contentType != null) &&
67 contentType.startsWith(ContentTypes.TEXT_HTML)) {
68
69 return true;
70 }
71 else {
72 return false;
73 }
74 }
75
76 protected void processFilter(
77 HttpServletRequest request, HttpServletResponse response,
78 FilterChain filterChain)
79 throws Exception {
80
81 if (isEnsureValidHtml(request, response) &&
82 !isAlreadyFiltered(request)) {
83
84 request.setAttribute(SKIP_FILTER, Boolean.TRUE);
85
86 if (_log.isDebugEnabled()) {
87 String completeURL = HttpUtil.getCompleteURL(request);
88
89 _log.debug("Ensuring valid HTML " + completeURL);
90 }
91
92 StringServletResponse stringServerResponse =
93 new StringServletResponse(response);
94
95 processFilter(
96 ValidHtmlFilter.class, request, stringServerResponse,
97 filterChain);
98
99 String content = getContent(
100 request, stringServerResponse.getString());
101
102 ServletResponseUtil.write(response, content);
103 }
104 else {
105 if (_log.isDebugEnabled()) {
106 String completeURL = HttpUtil.getCompleteURL(request);
107
108 _log.debug("Not ensuring valid HTML " + completeURL);
109 }
110
111 processFilter(
112 ValidHtmlFilter.class, request, response, filterChain);
113 }
114 }
115
116 private static final String _CLOSE_BODY = "</body>";
117
118 private static final String _CLOSE_HTML = "</html>";
119
120 private static Log _log = LogFactoryUtil.getLog(ValidHtmlFilter.class);
121
122 }