blob: 8d04578696abe0921cb64aa7730f109c3b598f1c [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;
34
35import java.io.File;
36import java.io.IOException;
Shawn Pearcea9b99a12015-02-10 15:35:11 -080037import java.io.InputStream;
Dave Borowitzfc2f00a2014-07-29 17:34:43 -070038import java.io.OutputStream;
Dave Borowitz9de65952012-08-13 16:09:45 -070039import java.net.MalformedURLException;
40import java.net.URL;
41import java.util.List;
42import java.util.Map;
Shawn Pearcea9b99a12015-02-10 15:35:11 -080043import java.util.concurrent.ConcurrentMap;
Dave Borowitz9de65952012-08-13 16:09:45 -070044
Shawn Pearcec4d3fd72015-02-10 14:32:37 -080045import javax.servlet.http.HttpServletRequest;
Dave Borowitz9de65952012-08-13 16:09:45 -070046import javax.servlet.http.HttpServletResponse;
47
Dave Borowitzfc775ad2014-07-30 11:38:53 -070048/**
49 * Renderer for Soy templates used by Gitiles.
50 * <p>
51 * Most callers should not use the methods in this class directly, and instead
52 * use one of the HTML methods in {@link BaseServlet}.
53 */
Dave Borowitz9de65952012-08-13 16:09:45 -070054public abstract class Renderer {
Dave Borowitzfc2f00a2014-07-29 17:34:43 -070055 // Must match .streamingPlaceholder.
56 private static final String PLACEHOLDER = "id=\"STREAMED_OUTPUT_BLOCK\"";
57
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +020058 private static final List<String> SOY_FILENAMES =
59 ImmutableList.of(
60 "BlameDetail.soy",
61 "Common.soy",
62 "DiffDetail.soy",
63 "Doc.soy",
64 "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
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +020072 public static final Map<String, String> STATIC_URL_GLOBALS =
73 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 Borowitz76bbefd2014-03-11 16:57:45 -070078 protected static class FileUrlMapper implements Function<String, URL> {
79 private final String prefix;
80
81 protected FileUrlMapper() {
82 this("");
Dave Borowitz9de65952012-08-13 16:09:45 -070083 }
Dave Borowitz76bbefd2014-03-11 16:57:45 -070084
85 protected FileUrlMapper(String prefix) {
86 this.prefix = checkNotNull(prefix, "prefix");
87 }
88
89 @Override
90 public URL apply(String filename) {
91 if (filename == null) {
92 return null;
93 }
94 try {
95 return new File(prefix + filename).toURI().toURL();
96 } catch (MalformedURLException e) {
97 throw new IllegalArgumentException(e);
98 }
Dave Borowitz9de65952012-08-13 16:09:45 -070099 }
100 }
101
Shawn Pearcea9b99a12015-02-10 15:35:11 -0800102 protected ImmutableMap<String, URL> templates;
Dave Borowitz9de65952012-08-13 16:09:45 -0700103 protected ImmutableMap<String, String> globals;
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +0200104 private final ConcurrentMap<String, HashCode> hashes =
105 new MapMaker().initialCapacity(SOY_FILENAMES.size()).concurrencyLevel(1).makeMap();
Dave Borowitz9de65952012-08-13 16:09:45 -0700106
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +0200107 protected Renderer(
108 Function<String, URL> resourceMapper,
109 Map<String, String> globals,
110 String staticPrefix,
111 Iterable<URL> customTemplates,
112 String siteTitle) {
Dave Borowitz9de65952012-08-13 16:09:45 -0700113 checkNotNull(staticPrefix, "staticPrefix");
Shawn Pearcea9b99a12015-02-10 15:35:11 -0800114
115 ImmutableMap.Builder<String, URL> b = ImmutableMap.builder();
116 for (String name : SOY_FILENAMES) {
117 b.put(name, resourceMapper.apply(name));
118 }
119 for (URL u : customTemplates) {
120 b.put(u.toString(), u);
121 }
122 templates = b.build();
Dave Borowitz9de65952012-08-13 16:09:45 -0700123
124 Map<String, String> allGlobals = Maps.newHashMap();
125 for (Map.Entry<String, String> e : STATIC_URL_GLOBALS.entrySet()) {
126 allGlobals.put(e.getKey(), staticPrefix + e.getValue());
127 }
Chad Horohoe2a28d622012-11-12 11:56:59 -0800128 allGlobals.put("gitiles.SITE_TITLE", siteTitle);
Dave Borowitz9de65952012-08-13 16:09:45 -0700129 allGlobals.putAll(globals);
130 this.globals = ImmutableMap.copyOf(allGlobals);
131 }
132
Shawn Pearcea9b99a12015-02-10 15:35:11 -0800133 public HashCode getTemplateHash(String soyFile) {
134 HashCode h = hashes.get(soyFile);
135 if (h == null) {
136 h = computeTemplateHash(soyFile);
137 hashes.put(soyFile, h);
138 }
139 return h;
140 }
141
142 HashCode computeTemplateHash(String soyFile) {
143 URL u = templates.get(soyFile);
144 checkState(u != null, "Missing Soy template %s", soyFile);
145
146 Hasher h = Hashing.sha1().newHasher();
147 try (InputStream is = u.openStream();
148 OutputStream os = Funnels.asOutputStream(h)) {
149 ByteStreams.copy(is, os);
150 } catch (IOException e) {
151 throw new IllegalStateException("Missing Soy template " + soyFile, e);
152 }
153 return h.hash();
154 }
155
Shawn Pearce374f1842015-02-10 15:36:54 -0800156 public String render(String templateName, Map<String, ?> soyData) {
157 return newRenderer(templateName).setData(soyData).render();
158 }
159
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +0200160 void render(
161 HttpServletRequest req, HttpServletResponse res, String templateName, Map<String, ?> soyData)
162 throws IOException {
Dave Borowitz9de65952012-08-13 16:09:45 -0700163 res.setContentType("text/html");
164 res.setCharacterEncoding("UTF-8");
David Pletcherd7bdaf32014-08-27 14:50:32 -0700165 byte[] data = newRenderer(templateName).setData(soyData).render().getBytes(UTF_8);
Shawn Pearcec4d3fd72015-02-10 14:32:37 -0800166 if (BaseServlet.acceptsGzipEncoding(req)) {
167 res.setHeader(HttpHeaders.CONTENT_ENCODING, "gzip");
168 data = BaseServlet.gzip(data);
169 }
Dave Borowitz9de65952012-08-13 16:09:45 -0700170 res.setContentLength(data.length);
171 res.getOutputStream().write(data);
172 }
173
Dave Borowitzfc775ad2014-07-30 11:38:53 -0700174 OutputStream renderStreaming(HttpServletResponse res, String templateName, Map<String, ?> soyData)
175 throws IOException {
Han-Wen Nienhuysc0200f62016-05-02 17:34:51 +0200176 final String html = newRenderer(templateName).setData(soyData).render();
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700177 int id = html.indexOf(PLACEHOLDER);
178 checkArgument(id >= 0, "Template must contain %s", PLACEHOLDER);
179
180 int lt = html.lastIndexOf('<', id);
181 final int gt = html.indexOf('>', id + PLACEHOLDER.length());
182 final OutputStream out = res.getOutputStream();
David Pletcherd7bdaf32014-08-27 14:50:32 -0700183 out.write(html.substring(0, lt).getBytes(UTF_8));
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700184 out.flush();
185
186 return new OutputStream() {
187 @Override
188 public void write(byte[] b) throws IOException {
189 out.write(b);
190 }
191
192 @Override
193 public void write(byte[] b, int off, int len) throws IOException {
194 out.write(b, off, len);
195 }
196
197 @Override
198 public void write(int b) throws IOException {
199 out.write(b);
200 }
201
202 @Override
203 public void flush() throws IOException {
204 out.flush();
205 }
206
207 @Override
208 public void close() throws IOException {
David Pletcherd7bdaf32014-08-27 14:50:32 -0700209 out.write(html.substring(gt + 1).getBytes(UTF_8));
Dave Borowitzfc2f00a2014-07-29 17:34:43 -0700210 out.close();
211 }
212 };
213 }
214
Dave Borowitz9de65952012-08-13 16:09:45 -0700215 SoyTofu.Renderer newRenderer(String templateName) {
216 return getTofu().newRenderer(templateName);
217 }
218
219 protected abstract SoyTofu getTofu();
220}