You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PagesServlet.java 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*
  2. * Copyright 2012 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit;
  17. import java.io.IOException;
  18. import java.text.MessageFormat;
  19. import java.text.ParseException;
  20. import java.util.ArrayList;
  21. import java.util.List;
  22. import javax.servlet.ServletContext;
  23. import javax.servlet.ServletException;
  24. import javax.servlet.http.HttpServlet;
  25. import javax.servlet.http.HttpServletRequest;
  26. import javax.servlet.http.HttpServletResponse;
  27. import org.eclipse.jgit.lib.Repository;
  28. import org.eclipse.jgit.revwalk.RevCommit;
  29. import org.eclipse.jgit.revwalk.RevTree;
  30. import org.slf4j.Logger;
  31. import org.slf4j.LoggerFactory;
  32. import com.gitblit.models.RefModel;
  33. import com.gitblit.utils.ArrayUtils;
  34. import com.gitblit.utils.JGitUtils;
  35. import com.gitblit.utils.MarkdownUtils;
  36. import com.gitblit.utils.StringUtils;
  37. /**
  38. * Serves the content of a gh-pages branch.
  39. *
  40. * @author James Moger
  41. *
  42. */
  43. public class PagesServlet extends HttpServlet {
  44. private static final long serialVersionUID = 1L;
  45. private transient Logger logger = LoggerFactory.getLogger(PagesServlet.class);
  46. public PagesServlet() {
  47. super();
  48. }
  49. /**
  50. * Returns an url to this servlet for the specified parameters.
  51. *
  52. * @param baseURL
  53. * @param repository
  54. * @param path
  55. * @return an url
  56. */
  57. public static String asLink(String baseURL, String repository, String path) {
  58. if (baseURL.length() > 0 && baseURL.charAt(baseURL.length() - 1) == '/') {
  59. baseURL = baseURL.substring(0, baseURL.length() - 1);
  60. }
  61. return baseURL + Constants.PAGES + repository + "/" + (path == null ? "" : ("/" + path));
  62. }
  63. /**
  64. * Retrieves the specified resource from the gh-pages branch of the
  65. * repository.
  66. *
  67. * @param request
  68. * @param response
  69. * @throws javax.servlet.ServletException
  70. * @throws java.io.IOException
  71. */
  72. private void processRequest(HttpServletRequest request, HttpServletResponse response)
  73. throws ServletException, IOException {
  74. String path = request.getPathInfo();
  75. if (path.toLowerCase().endsWith(".git")) {
  76. // forward to url with trailing /
  77. // this is important for relative pages links
  78. response.sendRedirect(request.getServletPath() + path + "/");
  79. return;
  80. }
  81. if (path.charAt(0) == '/') {
  82. // strip leading /
  83. path = path.substring(1);
  84. }
  85. // determine repository and resource from url
  86. String repository = "";
  87. String resource = "";
  88. Repository r = null;
  89. int offset = 0;
  90. while (r == null) {
  91. int slash = path.indexOf('/', offset);
  92. if (slash == -1) {
  93. repository = path;
  94. } else {
  95. repository = path.substring(0, slash);
  96. }
  97. r = GitBlit.self().getRepository(repository, false);
  98. offset = slash + 1;
  99. if (offset > 0) {
  100. resource = path.substring(offset);
  101. }
  102. if (repository.equals(path)) {
  103. // either only repository in url or no repository found
  104. break;
  105. }
  106. }
  107. ServletContext context = request.getSession().getServletContext();
  108. try {
  109. if (r == null) {
  110. // repository not found!
  111. String mkd = MessageFormat.format(
  112. "# Error\nSorry, no valid **repository** specified in this url: {0}!",
  113. repository);
  114. error(response, mkd);
  115. return;
  116. }
  117. // retrieve the content from the repository
  118. RefModel pages = JGitUtils.getPagesBranch(r);
  119. RevCommit commit = JGitUtils.getCommit(r, pages.getObjectId().getName());
  120. if (commit == null) {
  121. // branch not found!
  122. String mkd = MessageFormat.format(
  123. "# Error\nSorry, the repository {0} does not have a **gh-pages** branch!",
  124. repository);
  125. error(response, mkd);
  126. r.close();
  127. return;
  128. }
  129. String [] encodings = GitBlit.getEncodings();
  130. RevTree tree = commit.getTree();
  131. byte[] content = null;
  132. if (StringUtils.isEmpty(resource)) {
  133. // find resource
  134. List<String> markdownExtensions = GitBlit.getStrings(Keys.web.markdownExtensions);
  135. List<String> extensions = new ArrayList<String>(markdownExtensions.size() + 2);
  136. extensions.add("html");
  137. extensions.add("htm");
  138. extensions.addAll(markdownExtensions);
  139. for (String ext : extensions){
  140. String file = "index." + ext;
  141. String stringContent = JGitUtils.getStringContent(r, tree, file, encodings);
  142. if(stringContent == null){
  143. continue;
  144. }
  145. content = stringContent.getBytes(Constants.ENCODING);
  146. if (content != null) {
  147. resource = file;
  148. // assume text/html unless the servlet container
  149. // overrides
  150. response.setContentType("text/html; charset=" + Constants.ENCODING);
  151. break;
  152. }
  153. }
  154. } else {
  155. // specific resource
  156. try {
  157. String contentType = context.getMimeType(resource);
  158. if (contentType == null) {
  159. contentType = "text/plain";
  160. }
  161. if (contentType.startsWith("text")) {
  162. content = JGitUtils.getStringContent(r, tree, resource, encodings).getBytes(
  163. Constants.ENCODING);
  164. } else {
  165. content = JGitUtils.getByteContent(r, tree, resource, false);
  166. }
  167. response.setContentType(contentType);
  168. } catch (Exception e) {
  169. }
  170. }
  171. // no content, try custom 404 page
  172. if (ArrayUtils.isEmpty(content)) {
  173. String custom404 = JGitUtils.getStringContent(r, tree, "404.html", encodings);
  174. if (!StringUtils.isEmpty(custom404)) {
  175. content = custom404.getBytes(Constants.ENCODING);
  176. }
  177. // still no content
  178. if (ArrayUtils.isEmpty(content)) {
  179. String str = MessageFormat.format(
  180. "# Error\nSorry, the requested resource **{0}** was not found.",
  181. resource);
  182. content = MarkdownUtils.transformMarkdown(str).getBytes(Constants.ENCODING);
  183. }
  184. try {
  185. // output the content
  186. logger.warn("Pages 404: " + resource);
  187. response.setStatus(HttpServletResponse.SC_NOT_FOUND);
  188. response.getOutputStream().write(content);
  189. response.flushBuffer();
  190. } catch (Throwable t) {
  191. logger.error("Failed to write page to client", t);
  192. }
  193. return;
  194. }
  195. // check to see if we should transform markdown files
  196. for (String ext : GitBlit.getStrings(Keys.web.markdownExtensions)) {
  197. if (resource.endsWith(ext)) {
  198. String mkd = new String(content, Constants.ENCODING);
  199. content = MarkdownUtils.transformMarkdown(mkd).getBytes(Constants.ENCODING);
  200. response.setContentType("text/html; charset=" + Constants.ENCODING);
  201. break;
  202. }
  203. }
  204. try {
  205. // output the content
  206. response.setHeader("Cache-Control", "public, max-age=3600, must-revalidate");
  207. response.setDateHeader("Last-Modified", JGitUtils.getCommitDate(commit).getTime());
  208. response.getOutputStream().write(content);
  209. response.flushBuffer();
  210. } catch (Throwable t) {
  211. logger.error("Failed to write page to client", t);
  212. }
  213. // close the repository
  214. r.close();
  215. } catch (Throwable t) {
  216. logger.error("Failed to write page to client", t);
  217. }
  218. }
  219. private void error(HttpServletResponse response, String mkd) throws ServletException,
  220. IOException, ParseException {
  221. String content = MarkdownUtils.transformMarkdown(mkd);
  222. response.setContentType("text/html; charset=" + Constants.ENCODING);
  223. response.getWriter().write(content);
  224. }
  225. @Override
  226. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  227. throws ServletException, IOException {
  228. processRequest(request, response);
  229. }
  230. @Override
  231. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  232. throws ServletException, IOException {
  233. processRequest(request, response);
  234. }
  235. }