blob: efeef9c998c6501ebfe64b030f639abb8196126a [file] [log] [blame]
Dave Borowitz9de65952012-08-13 16:09:45 -07001// Copyright 2012 Google Inc. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package com.google.gitiles;
16
Dave Borowitzfc2f00a2014-07-29 17:34:43 -070017import static com.google.common.base.Preconditions.checkArgument;
Dave Borowitz9de65952012-08-13 16:09:45 -070018import static com.google.common.base.Preconditions.checkNotNull;
Shawn Pearcea9b99a12015-02-10 15:35:11 -080019import static com.google.common.base.Preconditions.checkState;
David Pletcherd7bdaf32014-08-27 14:50:32 -070020import static java.nio.charset.StandardCharsets.UTF_8;
Dave Borowitz9de65952012-08-13 16:09:45 -070021
Dave Borowitz9de65952012-08-13 16:09:45 -070022import com.google.common.collect.ImmutableList;
23import com.google.common.collect.ImmutableMap;
Shawn Pearcea9b99a12015-02-10 15:35:11 -080024import com.google.common.collect.MapMaker;
Dave Borowitz9de65952012-08-13 16:09:45 -070025import com.google.common.collect.Maps;
Shawn Pearcea9b99a12015-02-10 15:35:11 -080026import com.google.common.hash.Funnels;
27import com.google.common.hash.HashCode;
28import com.google.common.hash.Hasher;
29import com.google.common.hash.Hashing;
30import com.google.common.io.ByteStreams;
Shawn Pearcec4d3fd72015-02-10 14:32:37 -080031import com.google.common.net.HttpHeaders;
Dave Borowitz9de65952012-08-13 16:09:45 -070032import com.google.template.soy.tofu.SoyTofu;
Dave Borowitz9de65952012-08-13 16:09:45 -070033import java.io.File;
34import java.io.IOException;
Shawn Pearcea9b99a12015-02-10 15:35:11 -080035import java.io.InputStream;
Dave Borowitzfc2f00a2014-07-29 17:34:43 -070036import java.io.OutputStream;
Dave Borowitz9de65952012-08-13 16:09:45 -070037import java.net.MalformedURLException;
38import java.net.URL;
Dave Borowitz9de65952012-08-13 16:09:45 -070039import java.util.Map;
Shawn Pearcea9b99a12015-02-10 15:35:11 -080040import java.util.concurrent.ConcurrentMap;
David Pursehouseb40361f2017-05-30 10:41:53 +090041import java.util.function.Function;
Shawn Pearcec4d3fd72015-02-10 14:32:37 -080042import javax.servlet.http.HttpServletRequest;
Dave Borowitz9de65952012-08-13 16:09:45 -070043import javax.servlet.http.HttpServletResponse;
44
Dave Borowitzfc775ad2014-07-30 11:38:53 -070045/**
46 * Renderer for Soy templates used by Gitiles.
Dave Borowitz40255d52016-08-19 16:16:22 -040047 *
48 * <p>Most callers should not use the methods in this class directly, and instead use one of the
49 * HTML methods in {@link BaseServlet}.
Dave Borowitzfc775ad2014-07-30 11:38:53 -070050 */
Dave Borowitz9de65952012-08-13 16:09:45 -070051public abstract class Renderer {
Dave Borowitzfc2f00a2014-07-29 17:34:43 -070052 // Must match .streamingPlaceholder.
53 private static final String PLACEHOLDER = "id=\"STREAMED_OUTPUT_BLOCK\"";
54
Dave Borowitz3b685ab2017-03-09 09:24:54 -050055 private static final ImmutableList<String> SOY_FILENAMES =
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +020056 ImmutableList.of(
57 "BlameDetail.soy",
58 "Common.soy",
59 "DiffDetail.soy",
60 "Doc.soy",
61 "HostIndex.soy",
62 "LogDetail.soy",
63 "ObjectDetail.soy",
64 "PathDetail.soy",
65 "RefList.soy",
66 "RevisionDetail.soy",
67 "RepositoryIndex.soy");
Dave Borowitz9de65952012-08-13 16:09:45 -070068
Dave Borowitz3b685ab2017-03-09 09:24:54 -050069 public static final ImmutableMap<String, String> STATIC_URL_GLOBALS =
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +020070 ImmutableMap.of(
71 "gitiles.BASE_CSS_URL", "base.css",
72 "gitiles.DOC_CSS_URL", "doc.css",
73 "gitiles.PRETTIFY_CSS_URL", "prettify/prettify.css");
Dave Borowitz9de65952012-08-13 16:09:45 -070074
Dave Borowitzde07eac2016-10-04 09:44:25 -040075 protected static Function<String, URL> fileUrlMapper() {
76 return fileUrlMapper("");
77 }
Dave Borowitz76bbefd2014-03-11 16:57:45 -070078
Dave Borowitzde07eac2016-10-04 09:44:25 -040079 protected static Function<String, URL> fileUrlMapper(String prefix) {
80 checkNotNull(prefix);
81 return filename -> {
Dave Borowitz76bbefd2014-03-11 16:57:45 -070082 if (filename == null) {
83 return null;
84 }
85 try {
86 return new File(prefix + filename).toURI().toURL();
87 } catch (MalformedURLException e) {
88 throw new IllegalArgumentException(e);
89 }
Dave Borowitzde07eac2016-10-04 09:44:25 -040090 };
Dave Borowitz9de65952012-08-13 16:09:45 -070091 }
92
Shawn Pearcea9b99a12015-02-10 15:35:11 -080093 protected ImmutableMap<String, URL> templates;
Dave Borowitz9de65952012-08-13 16:09:45 -070094 protected ImmutableMap<String, String> globals;
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +020095 private final ConcurrentMap<String, HashCode> hashes =
96 new MapMaker().initialCapacity(SOY_FILENAMES.size()).concurrencyLevel(1).makeMap();
Dave Borowitz9de65952012-08-13 16:09:45 -070097
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +020098 protected Renderer(
99 Function<String, URL> resourceMapper,
100 Map<String, String> globals,
101 String staticPrefix,
102 Iterable<URL> customTemplates,
103 String siteTitle) {
Dave Borowitz9de65952012-08-13 16:09:45 -0700104 checkNotNull(staticPrefix, "staticPrefix");
Shawn Pearcea9b99a12015-02-10 15:35:11 -0800105
106 ImmutableMap.Builder<String, URL> b = ImmutableMap.builder();
107 for (String name : SOY_FILENAMES) {
108 b.put(name, resourceMapper.apply(name));
109 }
110 for (URL u : customTemplates) {
111 b.put(u.toString(), u);
112 }
113 templates = b.build();
Dave Borowitz9de65952012-08-13 16:09:45 -0700114
115 Map<String, String> allGlobals = Maps.newHashMap();
116 for (Map.Entry<String, String> e : STATIC_URL_GLOBALS.entrySet()) {
117 allGlobals.put(e.getKey(), staticPrefix + e.getValue());
118 }
Chad Horohoe2a28d622012-11-12 11:56:59 -0800119 allGlobals.put("gitiles.SITE_TITLE", siteTitle);
Dave Borowitz9de65952012-08-13 16:09:45 -0700120 allGlobals.putAll(globals);
121 this.globals = ImmutableMap.copyOf(allGlobals);
122 }
123
Shawn Pearcea9b99a12015-02-10 15:35:11 -0800124 public HashCode getTemplateHash(String soyFile) {
125 HashCode h = hashes.get(soyFile);
126 if (h == null) {
127 h = computeTemplateHash(soyFile);
128 hashes.put(soyFile, h);
129 }
130 return h;
131 }
132
133 HashCode computeTemplateHash(String soyFile) {
134 URL u = templates.get(soyFile);
135 checkState(u != null, "Missing Soy template %s", soyFile);
136
David Pursehoused5914492017-05-31 13:08:22 +0900137 Hasher h = Hashing.murmur3_128().newHasher();
Shawn Pearcea9b99a12015-02-10 15:35:11 -0800138 try (InputStream is = u.openStream();
139 OutputStream os = Funnels.asOutputStream(h)) {
140 ByteStreams.copy(is, os);
141 } catch (IOException e) {
142 throw new IllegalStateException("Missing Soy template " + soyFile, e);
143 }
144 return h.hash();
145 }
146
Shawn Pearce374f1842015-02-10 15:36:54 -0800147 public String render(String templateName, Map<String, ?> soyData) {
148 return newRenderer(templateName).setData(soyData).render();
149 }
150
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +0200151 void render(
152 HttpServletRequest req, HttpServletResponse res, String templateName, Map<String, ?> soyData)
153 throws IOException {
Dave Borowitz9de65952012-08-13 16:09:45 -0700154 res.setContentType("text/html");
155 res.setCharacterEncoding("UTF-8");
David Pletcherd7bdaf32014-08-27 14:50:32 -0700156 byte[] data = newRenderer(templateName).setData(soyData).render().getBytes(UTF_8);
Shawn Pearcec4d3fd72015-02-10 14:32:37 -0800157 if (BaseServlet.acceptsGzipEncoding(req)) {
Shawn Pearceed3c2d12016-05-30 15:59:02 -0700158 res.addHeader(HttpHeaders.VARY, HttpHeaders.ACCEPT_ENCODING);
Shawn Pearcec4d3fd72015-02-10 14:32:37 -0800159 res.setHeader(HttpHeaders.CONTENT_ENCODING, "gzip");
160 data = BaseServlet.gzip(data);
161 }
Dave Borowitz9de65952012-08-13 16:09:45 -0700162 res.setContentLength(data.length);
163 res.getOutputStream().write(data);
164 }
165
Dave Borowitzfc775ad2014-07-30 11:38:53 -0700166 OutputStream renderStreaming(HttpServletResponse res, String templateName, Map<String, ?> soyData)
167 throws IOException {
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +0200168 final String html = newRenderer(templateName).setData(soyData).render();
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700169 int id = html.indexOf(PLACEHOLDER);
170 checkArgument(id >= 0, "Template must contain %s", PLACEHOLDER);
171
172 int lt = html.lastIndexOf('<', id);
173 final int gt = html.indexOf('>', id + PLACEHOLDER.length());
174 final OutputStream out = res.getOutputStream();
David Pletcherd7bdaf32014-08-27 14:50:32 -0700175 out.write(html.substring(0, lt).getBytes(UTF_8));
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700176 out.flush();
177
178 return new OutputStream() {
179 @Override
180 public void write(byte[] b) throws IOException {
181 out.write(b);
182 }
183
184 @Override
185 public void write(byte[] b, int off, int len) throws IOException {
186 out.write(b, off, len);
187 }
188
189 @Override
190 public void write(int b) throws IOException {
191 out.write(b);
192 }
193
194 @Override
195 public void flush() throws IOException {
196 out.flush();
197 }
198
199 @Override
200 public void close() throws IOException {
David Pletcherd7bdaf32014-08-27 14:50:32 -0700201 out.write(html.substring(gt + 1).getBytes(UTF_8));
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700202 out.close();
203 }
204 };
205 }
206
Dave Borowitz9de65952012-08-13 16:09:45 -0700207 SoyTofu.Renderer newRenderer(String templateName) {
208 return getTofu().newRenderer(templateName);
209 }
210
211 protected abstract SoyTofu getTofu();
212}