blob: bc8529087288a8ef1bfd3030eff254c13f244909 [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;
Dave Borowitz9de65952012-08-13 16:09:45 -070024import com.google.common.collect.Maps;
Shawn Pearcea9b99a12015-02-10 15:35:11 -080025import com.google.common.hash.Funnels;
26import com.google.common.hash.HashCode;
27import com.google.common.hash.Hasher;
28import com.google.common.hash.Hashing;
Jakub Vrana21e70b72019-05-20 16:33:54 +020029import com.google.common.html.types.LegacyConversions;
Shawn Pearcea9b99a12015-02-10 15:35:11 -080030import 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;
Kurt Alfred Klueverc1f6cfc2018-04-30 20:16:43 -070040import java.util.concurrent.ConcurrentHashMap;
Shawn Pearcea9b99a12015-02-10 15:35:11 -080041import java.util.concurrent.ConcurrentMap;
David Pursehouseb40361f2017-05-30 10:41:53 +090042import java.util.function.Function;
Shawn Pearce6451fa52017-06-29 20:47:05 -070043import java.util.zip.GZIPOutputStream;
Shawn Pearcec4d3fd72015-02-10 14:32:37 -080044import javax.servlet.http.HttpServletRequest;
Dave Borowitz9de65952012-08-13 16:09:45 -070045import javax.servlet.http.HttpServletResponse;
46
Dave Borowitzfc775ad2014-07-30 11:38:53 -070047/**
48 * Renderer for Soy templates used by Gitiles.
Dave Borowitz40255d52016-08-19 16:16:22 -040049 *
50 * <p>Most callers should not use the methods in this class directly, and instead use one of the
51 * HTML methods in {@link BaseServlet}.
Dave Borowitzfc775ad2014-07-30 11:38:53 -070052 */
Dave Borowitz9de65952012-08-13 16:09:45 -070053public abstract class Renderer {
Dave Borowitzfc2f00a2014-07-29 17:34:43 -070054 // Must match .streamingPlaceholder.
55 private static final String PLACEHOLDER = "id=\"STREAMED_OUTPUT_BLOCK\"";
56
Dave Borowitz3b685ab2017-03-09 09:24:54 -050057 private static final ImmutableList<String> SOY_FILENAMES =
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +020058 ImmutableList.of(
59 "BlameDetail.soy",
60 "Common.soy",
61 "DiffDetail.soy",
62 "Doc.soy",
Alon Bar-Levcf9e71d2019-01-23 15:23:19 +020063 "Error.soy",
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +020064 "HostIndex.soy",
65 "LogDetail.soy",
66 "ObjectDetail.soy",
67 "PathDetail.soy",
68 "RefList.soy",
69 "RevisionDetail.soy",
70 "RepositoryIndex.soy");
Dave Borowitz9de65952012-08-13 16:09:45 -070071
Dave Borowitz3b685ab2017-03-09 09:24:54 -050072 public static final ImmutableMap<String, String> STATIC_URL_GLOBALS =
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +020073 ImmutableMap.of(
74 "gitiles.BASE_CSS_URL", "base.css",
75 "gitiles.DOC_CSS_URL", "doc.css",
76 "gitiles.PRETTIFY_CSS_URL", "prettify/prettify.css");
Dave Borowitz9de65952012-08-13 16:09:45 -070077
Dave Borowitzde07eac2016-10-04 09:44:25 -040078 protected static Function<String, URL> fileUrlMapper() {
79 return fileUrlMapper("");
80 }
Dave Borowitz76bbefd2014-03-11 16:57:45 -070081
Dave Borowitzde07eac2016-10-04 09:44:25 -040082 protected static Function<String, URL> fileUrlMapper(String prefix) {
83 checkNotNull(prefix);
84 return filename -> {
Dave Borowitz76bbefd2014-03-11 16:57:45 -070085 if (filename == null) {
86 return null;
87 }
88 try {
89 return new File(prefix + filename).toURI().toURL();
90 } catch (MalformedURLException e) {
91 throw new IllegalArgumentException(e);
92 }
Dave Borowitzde07eac2016-10-04 09:44:25 -040093 };
Dave Borowitz9de65952012-08-13 16:09:45 -070094 }
95
Shawn Pearcea9b99a12015-02-10 15:35:11 -080096 protected ImmutableMap<String, URL> templates;
Dave Borowitz9de65952012-08-13 16:09:45 -070097 protected ImmutableMap<String, String> globals;
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +020098 private final ConcurrentMap<String, HashCode> hashes =
Kurt Alfred Klueverc1f6cfc2018-04-30 20:16:43 -070099 new ConcurrentHashMap<>(SOY_FILENAMES.size());
Dave Borowitz9de65952012-08-13 16:09:45 -0700100
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +0200101 protected Renderer(
102 Function<String, URL> resourceMapper,
103 Map<String, String> globals,
104 String staticPrefix,
105 Iterable<URL> customTemplates,
106 String siteTitle) {
Dave Borowitz9de65952012-08-13 16:09:45 -0700107 checkNotNull(staticPrefix, "staticPrefix");
Shawn Pearcea9b99a12015-02-10 15:35:11 -0800108
109 ImmutableMap.Builder<String, URL> b = ImmutableMap.builder();
110 for (String name : SOY_FILENAMES) {
111 b.put(name, resourceMapper.apply(name));
112 }
113 for (URL u : customTemplates) {
114 b.put(u.toString(), u);
115 }
116 templates = b.build();
Dave Borowitz9de65952012-08-13 16:09:45 -0700117
118 Map<String, String> allGlobals = Maps.newHashMap();
119 for (Map.Entry<String, String> e : STATIC_URL_GLOBALS.entrySet()) {
120 allGlobals.put(e.getKey(), staticPrefix + e.getValue());
121 }
Chad Horohoe2a28d622012-11-12 11:56:59 -0800122 allGlobals.put("gitiles.SITE_TITLE", siteTitle);
Dave Borowitz9de65952012-08-13 16:09:45 -0700123 allGlobals.putAll(globals);
124 this.globals = ImmutableMap.copyOf(allGlobals);
125 }
126
Shawn Pearcea9b99a12015-02-10 15:35:11 -0800127 public HashCode getTemplateHash(String soyFile) {
128 HashCode h = hashes.get(soyFile);
129 if (h == null) {
130 h = computeTemplateHash(soyFile);
131 hashes.put(soyFile, h);
132 }
133 return h;
134 }
135
136 HashCode computeTemplateHash(String soyFile) {
137 URL u = templates.get(soyFile);
138 checkState(u != null, "Missing Soy template %s", soyFile);
139
David Pursehoused5914492017-05-31 13:08:22 +0900140 Hasher h = Hashing.murmur3_128().newHasher();
Shawn Pearcea9b99a12015-02-10 15:35:11 -0800141 try (InputStream is = u.openStream();
142 OutputStream os = Funnels.asOutputStream(h)) {
143 ByteStreams.copy(is, os);
144 } catch (IOException e) {
145 throw new IllegalStateException("Missing Soy template " + soyFile, e);
146 }
147 return h.hash();
148 }
149
Shawn Pearce374f1842015-02-10 15:36:54 -0800150 public String render(String templateName, Map<String, ?> soyData) {
151 return newRenderer(templateName).setData(soyData).render();
152 }
153
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +0200154 void render(
155 HttpServletRequest req, HttpServletResponse res, String templateName, Map<String, ?> soyData)
156 throws IOException {
Dave Borowitz9de65952012-08-13 16:09:45 -0700157 res.setContentType("text/html");
158 res.setCharacterEncoding("UTF-8");
David Pletcherd7bdaf32014-08-27 14:50:32 -0700159 byte[] data = newRenderer(templateName).setData(soyData).render().getBytes(UTF_8);
Shawn Pearcec4d3fd72015-02-10 14:32:37 -0800160 if (BaseServlet.acceptsGzipEncoding(req)) {
Shawn Pearceed3c2d12016-05-30 15:59:02 -0700161 res.addHeader(HttpHeaders.VARY, HttpHeaders.ACCEPT_ENCODING);
Shawn Pearcec4d3fd72015-02-10 14:32:37 -0800162 res.setHeader(HttpHeaders.CONTENT_ENCODING, "gzip");
163 data = BaseServlet.gzip(data);
164 }
Dave Borowitz9de65952012-08-13 16:09:45 -0700165 res.setContentLength(data.length);
166 res.getOutputStream().write(data);
167 }
168
Dave Borowitzfc775ad2014-07-30 11:38:53 -0700169 OutputStream renderStreaming(HttpServletResponse res, String templateName, Map<String, ?> soyData)
170 throws IOException {
Shawn Pearce6451fa52017-06-29 20:47:05 -0700171 return renderStreaming(res, false, templateName, soyData);
172 }
173
174 OutputStream renderStreaming(
175 HttpServletResponse res, boolean gzip, String templateName, Map<String, ?> soyData)
176 throws IOException {
Shawn Pearce4b49d8d2017-06-29 20:02:22 -0700177 String html = newRenderer(templateName).setData(soyData).render();
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700178 int id = html.indexOf(PLACEHOLDER);
179 checkArgument(id >= 0, "Template must contain %s", PLACEHOLDER);
180
181 int lt = html.lastIndexOf('<', id);
Shawn Pearce4b49d8d2017-06-29 20:02:22 -0700182 int gt = html.indexOf('>', id + PLACEHOLDER.length());
183
Shawn Pearce6451fa52017-06-29 20:47:05 -0700184 OutputStream out = gzip ? new GZIPOutputStream(res.getOutputStream()) : res.getOutputStream();
David Pletcherd7bdaf32014-08-27 14:50:32 -0700185 out.write(html.substring(0, lt).getBytes(UTF_8));
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700186 out.flush();
187
Shawn Pearce4b49d8d2017-06-29 20:02:22 -0700188 byte[] tail = html.substring(gt + 1).getBytes(UTF_8);
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700189 return new OutputStream() {
190 @Override
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700191 public void write(byte[] b, int off, int len) throws IOException {
192 out.write(b, off, len);
193 }
194
195 @Override
196 public void write(int b) throws IOException {
197 out.write(b);
198 }
199
200 @Override
201 public void flush() throws IOException {
202 out.flush();
203 }
204
205 @Override
206 public void close() throws IOException {
Shawn Pearce4b49d8d2017-06-29 20:02:22 -0700207 try (OutputStream o = out) {
208 o.write(tail);
209 }
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700210 }
211 };
212 }
213
Dave Borowitz9de65952012-08-13 16:09:45 -0700214 SoyTofu.Renderer newRenderer(String templateName) {
Jakub Vrana21e70b72019-05-20 16:33:54 +0200215 ImmutableMap.Builder<String, Object> staticUrls = ImmutableMap.builder();
216 for (String key : STATIC_URL_GLOBALS.keySet()) {
217 staticUrls.put(
218 key.replaceFirst("^gitiles\\.", ""),
219 LegacyConversions.riskilyAssumeTrustedResourceUrl(globals.get(key)));
220 }
221 return getTofu()
222 .newRenderer(templateName)
223 .setIjData(ImmutableMap.of("staticUrls", staticUrls.build()));
Dave Borowitz9de65952012-08-13 16:09:45 -0700224 }
225
226 protected abstract SoyTofu getTofu();
227}