blob: dbd5590a192849128919985c9f509942d4e83829 [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;
David Pursehouse28726042019-06-27 09:09:30 +090032import com.google.template.soy.jbcsrc.api.SoySauce;
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
David Pursehouse28726042019-06-27 09:09:30 +0900150 public String renderHtml(String templateName, Map<String, ?> soyData) {
151 return newRenderer(templateName).setData(soyData).renderHtml().get().toString();
Shawn Pearce374f1842015-02-10 15:36:54 -0800152 }
153
David Pursehouse28726042019-06-27 09:09:30 +0900154 void renderHtml(
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +0200155 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 Pursehouse28726042019-06-27 09:09:30 +0900159 byte[] data =
160 newRenderer(templateName).setData(soyData).renderHtml().get().toString().getBytes(UTF_8);
Shawn Pearcec4d3fd72015-02-10 14:32:37 -0800161 if (BaseServlet.acceptsGzipEncoding(req)) {
Shawn Pearceed3c2d12016-05-30 15:59:02 -0700162 res.addHeader(HttpHeaders.VARY, HttpHeaders.ACCEPT_ENCODING);
Shawn Pearcec4d3fd72015-02-10 14:32:37 -0800163 res.setHeader(HttpHeaders.CONTENT_ENCODING, "gzip");
164 data = BaseServlet.gzip(data);
165 }
Dave Borowitz9de65952012-08-13 16:09:45 -0700166 res.setContentLength(data.length);
167 res.getOutputStream().write(data);
168 }
169
David Pursehouse28726042019-06-27 09:09:30 +0900170 OutputStream renderHtmlStreaming(
171 HttpServletResponse res, String templateName, Map<String, ?> soyData) throws IOException {
172 return renderHtmlStreaming(res, false, templateName, soyData);
Shawn Pearce6451fa52017-06-29 20:47:05 -0700173 }
174
David Pursehouse28726042019-06-27 09:09:30 +0900175 OutputStream renderHtmlStreaming(
Shawn Pearce6451fa52017-06-29 20:47:05 -0700176 HttpServletResponse res, boolean gzip, String templateName, Map<String, ?> soyData)
177 throws IOException {
David Pursehouse28726042019-06-27 09:09:30 +0900178 String html = newRenderer(templateName).setData(soyData).renderHtml().get().toString();
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700179 int id = html.indexOf(PLACEHOLDER);
180 checkArgument(id >= 0, "Template must contain %s", PLACEHOLDER);
181
182 int lt = html.lastIndexOf('<', id);
Shawn Pearce4b49d8d2017-06-29 20:02:22 -0700183 int gt = html.indexOf('>', id + PLACEHOLDER.length());
184
Shawn Pearce6451fa52017-06-29 20:47:05 -0700185 OutputStream out = gzip ? new GZIPOutputStream(res.getOutputStream()) : res.getOutputStream();
David Pletcherd7bdaf32014-08-27 14:50:32 -0700186 out.write(html.substring(0, lt).getBytes(UTF_8));
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700187 out.flush();
188
Shawn Pearce4b49d8d2017-06-29 20:02:22 -0700189 byte[] tail = html.substring(gt + 1).getBytes(UTF_8);
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700190 return new OutputStream() {
191 @Override
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700192 public void write(byte[] b, int off, int len) throws IOException {
193 out.write(b, off, len);
194 }
195
196 @Override
197 public void write(int b) throws IOException {
198 out.write(b);
199 }
200
201 @Override
202 public void flush() throws IOException {
203 out.flush();
204 }
205
206 @Override
207 public void close() throws IOException {
Shawn Pearce4b49d8d2017-06-29 20:02:22 -0700208 try (OutputStream o = out) {
209 o.write(tail);
210 }
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700211 }
212 };
213 }
214
David Pursehouse28726042019-06-27 09:09:30 +0900215 SoySauce.Renderer newRenderer(String templateName) {
Jakub Vrana21e70b72019-05-20 16:33:54 +0200216 ImmutableMap.Builder<String, Object> staticUrls = ImmutableMap.builder();
217 for (String key : STATIC_URL_GLOBALS.keySet()) {
218 staticUrls.put(
219 key.replaceFirst("^gitiles\\.", ""),
220 LegacyConversions.riskilyAssumeTrustedResourceUrl(globals.get(key)));
221 }
David Pursehouse28726042019-06-27 09:09:30 +0900222 return getSauce()
223 .renderTemplate(templateName)
224 .setIj(ImmutableMap.of("staticUrls", staticUrls.build()));
Dave Borowitz9de65952012-08-13 16:09:45 -0700225 }
226
David Pursehouse28726042019-06-27 09:09:30 +0900227 protected abstract SoySauce getSauce();
Dave Borowitz9de65952012-08-13 16:09:45 -0700228}