001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.wicket.response.filter;
018
019import java.util.HashMap;
020
021import org.apache.wicket.Application;
022import org.apache.wicket.core.util.string.JavaScriptUtils;
023import org.apache.wicket.model.Model;
024import org.apache.wicket.request.cycle.RequestCycle;
025import org.apache.wicket.util.string.AppendingStringBuffer;
026import org.slf4j.Logger;
027import org.slf4j.LoggerFactory;
028
029/**
030 * This is a filter that injects javascript code to the top head portion and after the body so that
031 * the time can me measured what the client parse time was for this page. It also reports the total
032 * server parse/response time in the client and logs the server response time and response size it
033 * took for a specific response in the server log.
034 * 
035 * You can specify what the status text should be like this: ServerAndClientTimeFilter.statustext=My
036 * Application, Server parsetime: ${servertime}, Client parsetime: ${clienttime} likewise for ajax
037 * request use ajax.ServerAndClientTimeFilter.statustext
038 * 
039 * <p>
040 * Usage: in YourApplication.java:
041 * 
042 * <pre>
043 * &#064;Override
044 * public init()
045 * {
046 *      super.init();
047 *      getRequestCycleSettings().addResponseFilter(new AjaxServerAndClientTimeFilter());
048 * }
049 * </pre>
050 * 
051 * @author jcompagner
052 * @deprecated This class has been deprecated for several reasons. The way it tries to measure
053 *             server and client times is very inaccurate. Modern browsers provide much better tools
054 *             to measure Javascript execution times. The measurements were written in a property
055 *             that has been deprecated for years and removed in modern browsers. Finally, rendering
056 *             the Javascript directly into the response makes it hard to support a strict CSP with
057 *             nonces. There is no real replacement for this class. Use the tools provided by the
058 *             browser. See {@code WicketExampleApplication} for a simple example of passing
059 *             rendering times to the browser via the {@code Server-Timing} header.
060 */
061@Deprecated
062public class AjaxServerAndClientTimeFilter implements IResponseFilter
063{
064        private static Logger log = LoggerFactory.getLogger(AjaxServerAndClientTimeFilter.class);
065
066        /**
067         * @see IResponseFilter#filter(org.apache.wicket.util.string.AppendingStringBuffer)
068         */
069        @Override
070        public AppendingStringBuffer filter(AppendingStringBuffer responseBuffer)
071        {
072                int headIndex = responseBuffer.indexOf("<head>");
073                int bodyIndex = responseBuffer.indexOf("</body>");
074                int ajaxStart = responseBuffer.indexOf("<ajax-response>");
075                int ajaxEnd = responseBuffer.indexOf("</ajax-response>");
076                long timeTaken = System.currentTimeMillis() - RequestCycle.get().getStartTime();
077                if (headIndex != -1 && bodyIndex != -1)
078                {
079                        responseBuffer.insert(bodyIndex, scriptTag("window.defaultStatus=" + getStatusString(timeTaken, "ServerAndClientTimeFilter.statustext") + ";"));
080                        responseBuffer.insert(headIndex + 6, scriptTag("clientTimeVariable = new Date().getTime();"));
081                }
082                else if (ajaxStart != -1 && ajaxEnd != -1)
083                {
084                        responseBuffer.insert(ajaxEnd, headerContribution("window.defaultStatus=" + getStatusString(timeTaken, "ajax.ServerAndClientTimeFilter.statustext") + ";"));
085                        responseBuffer.insert(ajaxStart + 15, headerContribution("clientTimeVariable = new Date().getTime();"));
086                }
087                log.info(timeTaken + "ms server time taken for request " +
088                        RequestCycle.get().getRequest().getUrl() + " response size: " + responseBuffer.length());
089                return responseBuffer;
090        }
091
092        private String scriptTag(String script)
093        {
094                AppendingStringBuffer buffer = new AppendingStringBuffer(250);
095                buffer.append("\n");
096                buffer.append(JavaScriptUtils.SCRIPT_OPEN_TAG);
097                buffer.append(script);
098                buffer.append(JavaScriptUtils.SCRIPT_CLOSE_TAG).append("\n");
099                return buffer.toString();
100        }
101        
102        private String headerContribution(String script)
103        {
104                AppendingStringBuffer buffer = new AppendingStringBuffer(250);
105                buffer.append("<header-contribution><![CDATA[<head xmlns:wicket=\"http://wicket.apache.org\">");
106                buffer.append(script);
107                buffer.append("</head>]]></header-contribution>");
108                return buffer.toString();
109        }
110
111        /**
112         * Returns a locale specific status message about the server and client time.
113         * 
114         * @param timeTaken
115         *            the server time it took
116         * @param resourceKey
117         *            The key for the locale specific string lookup
118         * @return String with the status message
119         */
120        private String getStatusString(long timeTaken, String resourceKey)
121        {
122                final HashMap<String, String> map = new HashMap<String, String>(4);
123                map.put("servertime", ((double)timeTaken) / 1000 + "s");
124                map.put("clienttime", "' + (new Date().getTime() - clientTimeVariable)/1000 +  's");
125
126                return Application.get()
127                        .getResourceSettings()
128                        .getLocalizer()
129                        .getString(resourceKey, null, Model.of(map),
130                                "'Server parsetime: ${servertime}, Client parsetime: ${clienttime}'");
131        }
132}