blob: 7030694b28f398a566e1382f54e5419bd22a0b63 [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.base.Function;
23import com.google.common.collect.ImmutableList;
24import com.google.common.collect.ImmutableMap;
Shawn Pearcea9b99a12015-02-10 15:35:11 -080025import com.google.common.collect.MapMaker;
Dave Borowitz9de65952012-08-13 16:09:45 -070026import com.google.common.collect.Maps;
Shawn Pearcea9b99a12015-02-10 15:35:11 -080027import com.google.common.hash.Funnels;
28import com.google.common.hash.HashCode;
29import com.google.common.hash.Hasher;
30import com.google.common.hash.Hashing;
31import com.google.common.io.ByteStreams;
Shawn Pearcec4d3fd72015-02-10 14:32:37 -080032import com.google.common.net.HttpHeaders;
Dave Borowitz9de65952012-08-13 16:09:45 -070033import com.google.template.soy.tofu.SoyTofu;
Dave Borowitz9de65952012-08-13 16:09:45 -070034import java.io.File;
35import java.io.IOException;
Shawn Pearcea9b99a12015-02-10 15:35:11 -080036import java.io.InputStream;
Dave Borowitzfc2f00a2014-07-29 17:34:43 -070037import java.io.OutputStream;
Dave Borowitz9de65952012-08-13 16:09:45 -070038import java.net.MalformedURLException;
39import java.net.URL;
40import java.util.List;
41import java.util.Map;
Shawn Pearcea9b99a12015-02-10 15:35:11 -080042import java.util.concurrent.ConcurrentMap;
Shawn Pearcec4d3fd72015-02-10 14:32:37 -080043import javax.servlet.http.HttpServletRequest;
Dave Borowitz9de65952012-08-13 16:09:45 -070044import javax.servlet.http.HttpServletResponse;
45
Dave Borowitzfc775ad2014-07-30 11:38:53 -070046/**
47 * Renderer for Soy templates used by Gitiles.
Dave Borowitz40255d52016-08-19 16:16:22 -040048 *
49 * <p>Most callers should not use the methods in this class directly, and instead use one of the
50 * HTML methods in {@link BaseServlet}.
Dave Borowitzfc775ad2014-07-30 11:38:53 -070051 */
Dave Borowitz9de65952012-08-13 16:09:45 -070052public abstract class Renderer {
Dave Borowitzfc2f00a2014-07-29 17:34:43 -070053 // Must match .streamingPlaceholder.
54 private static final String PLACEHOLDER = "id=\"STREAMED_OUTPUT_BLOCK\"";
55
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +020056 private static final List<String> SOY_FILENAMES =
57 ImmutableList.of(
58 "BlameDetail.soy",
59 "Common.soy",
60 "DiffDetail.soy",
61 "Doc.soy",
62 "HostIndex.soy",
63 "LogDetail.soy",
64 "ObjectDetail.soy",
65 "PathDetail.soy",
66 "RefList.soy",
67 "RevisionDetail.soy",
68 "RepositoryIndex.soy");
Dave Borowitz9de65952012-08-13 16:09:45 -070069
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +020070 public static final Map<String, String> STATIC_URL_GLOBALS =
71 ImmutableMap.of(
72 "gitiles.BASE_CSS_URL", "base.css",
73 "gitiles.DOC_CSS_URL", "doc.css",
74 "gitiles.PRETTIFY_CSS_URL", "prettify/prettify.css");
Dave Borowitz9de65952012-08-13 16:09:45 -070075
Dave Borowitz76bbefd2014-03-11 16:57:45 -070076 protected static class FileUrlMapper implements Function<String, URL> {
77 private final String prefix;
78
79 protected FileUrlMapper() {
80 this("");
Dave Borowitz9de65952012-08-13 16:09:45 -070081 }
Dave Borowitz76bbefd2014-03-11 16:57:45 -070082
83 protected FileUrlMapper(String prefix) {
84 this.prefix = checkNotNull(prefix, "prefix");
85 }
86
87 @Override
88 public URL apply(String filename) {
89 if (filename == null) {
90 return null;
91 }
92 try {
93 return new File(prefix + filename).toURI().toURL();
94 } catch (MalformedURLException e) {
95 throw new IllegalArgumentException(e);
96 }
Dave Borowitz9de65952012-08-13 16:09:45 -070097 }
98 }
99
Shawn Pearcea9b99a12015-02-10 15:35:11 -0800100 protected ImmutableMap<String, URL> templates;
Dave Borowitz9de65952012-08-13 16:09:45 -0700101 protected ImmutableMap<String, String> globals;
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +0200102 private final ConcurrentMap<String, HashCode> hashes =
103 new MapMaker().initialCapacity(SOY_FILENAMES.size()).concurrencyLevel(1).makeMap();
Dave Borowitz9de65952012-08-13 16:09:45 -0700104
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +0200105 protected Renderer(
106 Function<String, URL> resourceMapper,
107 Map<String, String> globals,
108 String staticPrefix,
109 Iterable<URL> customTemplates,
110 String siteTitle) {
Dave Borowitz9de65952012-08-13 16:09:45 -0700111 checkNotNull(staticPrefix, "staticPrefix");
Shawn Pearcea9b99a12015-02-10 15:35:11 -0800112
113 ImmutableMap.Builder<String, URL> b = ImmutableMap.builder();
114 for (String name : SOY_FILENAMES) {
115 b.put(name, resourceMapper.apply(name));
116 }
117 for (URL u : customTemplates) {
118 b.put(u.toString(), u);
119 }
120 templates = b.build();
Dave Borowitz9de65952012-08-13 16:09:45 -0700121
122 Map<String, String> allGlobals = Maps.newHashMap();
123 for (Map.Entry<String, String> e : STATIC_URL_GLOBALS.entrySet()) {
124 allGlobals.put(e.getKey(), staticPrefix + e.getValue());
125 }
Chad Horohoe2a28d622012-11-12 11:56:59 -0800126 allGlobals.put("gitiles.SITE_TITLE", siteTitle);
Dave Borowitz9de65952012-08-13 16:09:45 -0700127 allGlobals.putAll(globals);
128 this.globals = ImmutableMap.copyOf(allGlobals);
129 }
130
Shawn Pearcea9b99a12015-02-10 15:35:11 -0800131 public HashCode getTemplateHash(String soyFile) {
132 HashCode h = hashes.get(soyFile);
133 if (h == null) {
134 h = computeTemplateHash(soyFile);
135 hashes.put(soyFile, h);
136 }
137 return h;
138 }
139
140 HashCode computeTemplateHash(String soyFile) {
141 URL u = templates.get(soyFile);
142 checkState(u != null, "Missing Soy template %s", soyFile);
143
144 Hasher h = Hashing.sha1().newHasher();
145 try (InputStream is = u.openStream();
146 OutputStream os = Funnels.asOutputStream(h)) {
147 ByteStreams.copy(is, os);
148 } catch (IOException e) {
149 throw new IllegalStateException("Missing Soy template " + soyFile, e);
150 }
151 return h.hash();
152 }
153
Shawn Pearce374f1842015-02-10 15:36:54 -0800154 public String render(String templateName, Map<String, ?> soyData) {
155 return newRenderer(templateName).setData(soyData).render();
156 }
157
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +0200158 void render(
159 HttpServletRequest req, HttpServletResponse res, String templateName, Map<String, ?> soyData)
160 throws IOException {
Dave Borowitz9de65952012-08-13 16:09:45 -0700161 res.setContentType("text/html");
162 res.setCharacterEncoding("UTF-8");
David Pletcherd7bdaf32014-08-27 14:50:32 -0700163 byte[] data = newRenderer(templateName).setData(soyData).render().getBytes(UTF_8);
Shawn Pearcec4d3fd72015-02-10 14:32:37 -0800164 if (BaseServlet.acceptsGzipEncoding(req)) {
Shawn Pearceed3c2d12016-05-30 15:59:02 -0700165 res.addHeader(HttpHeaders.VARY, HttpHeaders.ACCEPT_ENCODING);
Shawn Pearcec4d3fd72015-02-10 14:32:37 -0800166 res.setHeader(HttpHeaders.CONTENT_ENCODING, "gzip");
167 data = BaseServlet.gzip(data);
168 }
Dave Borowitz9de65952012-08-13 16:09:45 -0700169 res.setContentLength(data.length);
170 res.getOutputStream().write(data);
171 }
172
Dave Borowitzfc775ad2014-07-30 11:38:53 -0700173 OutputStream renderStreaming(HttpServletResponse res, String templateName, Map<String, ?> soyData)
174 throws IOException {
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +0200175 final String html = newRenderer(templateName).setData(soyData).render();
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700176 int id = html.indexOf(PLACEHOLDER);
177 checkArgument(id >= 0, "Template must contain %s", PLACEHOLDER);
178
179 int lt = html.lastIndexOf('<', id);
180 final int gt = html.indexOf('>', id + PLACEHOLDER.length());
181 final OutputStream out = res.getOutputStream();
David Pletcherd7bdaf32014-08-27 14:50:32 -0700182 out.write(html.substring(0, lt).getBytes(UTF_8));
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700183 out.flush();
184
185 return new OutputStream() {
186 @Override
187 public void write(byte[] b) throws IOException {
188 out.write(b);
189 }
190
191 @Override
192 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 {
David Pletcherd7bdaf32014-08-27 14:50:32 -0700208 out.write(html.substring(gt + 1).getBytes(UTF_8));
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700209 out.close();
210 }
211 };
212 }
213
Dave Borowitz9de65952012-08-13 16:09:45 -0700214 SoyTofu.Renderer newRenderer(String templateName) {
215 return getTofu().newRenderer(templateName);
216 }
217
218 protected abstract SoyTofu getTofu();
219}