您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

BasePage.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. /*
  2. * Copyright 2011 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.wicket.pages;
  17. import java.text.MessageFormat;
  18. import java.util.ArrayList;
  19. import java.util.Calendar;
  20. import java.util.Collections;
  21. import java.util.Date;
  22. import java.util.HashSet;
  23. import java.util.LinkedHashMap;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.ResourceBundle;
  27. import java.util.Set;
  28. import java.util.TimeZone;
  29. import java.util.regex.Pattern;
  30. import javax.servlet.http.HttpServletRequest;
  31. import org.apache.wicket.Application;
  32. import org.apache.wicket.Page;
  33. import org.apache.wicket.PageParameters;
  34. import org.apache.wicket.RedirectToUrlException;
  35. import org.apache.wicket.markup.html.CSSPackageResource;
  36. import org.apache.wicket.markup.html.basic.Label;
  37. import org.apache.wicket.markup.html.link.ExternalLink;
  38. import org.apache.wicket.markup.html.panel.FeedbackPanel;
  39. import org.apache.wicket.protocol.http.RequestUtils;
  40. import org.apache.wicket.protocol.http.WebResponse;
  41. import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
  42. import org.apache.wicket.util.time.Duration;
  43. import org.apache.wicket.util.time.Time;
  44. import org.slf4j.Logger;
  45. import org.slf4j.LoggerFactory;
  46. import com.gitblit.Constants;
  47. import com.gitblit.Constants.AccessPermission;
  48. import com.gitblit.Constants.AccessRestrictionType;
  49. import com.gitblit.Constants.AuthorizationControl;
  50. import com.gitblit.Constants.FederationStrategy;
  51. import com.gitblit.GitBlit;
  52. import com.gitblit.Keys;
  53. import com.gitblit.models.ProjectModel;
  54. import com.gitblit.models.TeamModel;
  55. import com.gitblit.models.UserModel;
  56. import com.gitblit.utils.StringUtils;
  57. import com.gitblit.utils.TimeUtils;
  58. import com.gitblit.wicket.CacheControl;
  59. import com.gitblit.wicket.GitBlitWebApp;
  60. import com.gitblit.wicket.GitBlitWebSession;
  61. import com.gitblit.wicket.WicketUtils;
  62. public abstract class BasePage extends SessionPage {
  63. private final Logger logger;
  64. private transient TimeUtils timeUtils;
  65. public BasePage() {
  66. super();
  67. logger = LoggerFactory.getLogger(getClass());
  68. customizeHeader();
  69. }
  70. public BasePage(PageParameters params) {
  71. super(params);
  72. logger = LoggerFactory.getLogger(getClass());
  73. customizeHeader();
  74. }
  75. private void customizeHeader() {
  76. if (GitBlit.getBoolean(Keys.web.useResponsiveLayout, true)) {
  77. add(CSSPackageResource.getHeaderContribution("bootstrap/css/bootstrap-responsive.css"));
  78. }
  79. }
  80. protected String getLanguageCode() {
  81. return GitBlitWebSession.get().getLocale().getLanguage();
  82. }
  83. protected String getCountryCode() {
  84. return GitBlitWebSession.get().getLocale().getCountry().toLowerCase();
  85. }
  86. protected TimeUtils getTimeUtils() {
  87. if (timeUtils == null) {
  88. ResourceBundle bundle;
  89. try {
  90. bundle = ResourceBundle.getBundle("com.gitblit.wicket.GitBlitWebApp", GitBlitWebSession.get().getLocale());
  91. } catch (Throwable t) {
  92. bundle = ResourceBundle.getBundle("com.gitblit.wicket.GitBlitWebApp");
  93. }
  94. timeUtils = new TimeUtils(bundle, getTimeZone());
  95. }
  96. return timeUtils;
  97. }
  98. @Override
  99. protected void onBeforeRender() {
  100. if (GitBlit.isDebugMode()) {
  101. // strip Wicket tags in debug mode for jQuery DOM traversal
  102. Application.get().getMarkupSettings().setStripWicketTags(true);
  103. }
  104. super.onBeforeRender();
  105. }
  106. @Override
  107. protected void onAfterRender() {
  108. if (GitBlit.isDebugMode()) {
  109. // restore Wicket debug tags
  110. Application.get().getMarkupSettings().setStripWicketTags(false);
  111. }
  112. super.onAfterRender();
  113. }
  114. @Override
  115. protected void setHeaders(WebResponse response) {
  116. int expires = GitBlit.getInteger(Keys.web.pageCacheExpires, 0);
  117. if (expires > 0) {
  118. // pages are personalized for the authenticated user so they must be
  119. // marked private to prohibit proxy servers from caching them
  120. response.setHeader("Cache-Control", "private, must-revalidate");
  121. setLastModified();
  122. } else {
  123. // use default Wicket caching behavior
  124. super.setHeaders(response);
  125. }
  126. }
  127. /**
  128. * Sets the last-modified header date, if appropriate, for this page. The
  129. * date used is determined by the CacheControl annotation.
  130. *
  131. */
  132. protected void setLastModified() {
  133. if (getClass().isAnnotationPresent(CacheControl.class)) {
  134. CacheControl cacheControl = getClass().getAnnotation(CacheControl.class);
  135. switch (cacheControl.value()) {
  136. case ACTIVITY:
  137. setLastModified(GitBlit.getLastActivityDate());
  138. break;
  139. case BOOT:
  140. setLastModified(GitBlit.getBootDate());
  141. break;
  142. case NONE:
  143. break;
  144. default:
  145. logger.warn(getClass().getSimpleName() + ": unhandled LastModified type " + cacheControl.value());
  146. break;
  147. }
  148. }
  149. }
  150. /**
  151. * Sets the last-modified header field and the expires field.
  152. *
  153. * @param when
  154. */
  155. protected final void setLastModified(Date when) {
  156. if (when == null) {
  157. return;
  158. }
  159. if (when.before(GitBlit.getBootDate())) {
  160. // last-modified can not be before the Gitblit boot date
  161. // this helps ensure that pages are properly refreshed after a
  162. // server config change
  163. when = GitBlit.getBootDate();
  164. }
  165. int expires = GitBlit.getInteger(Keys.web.pageCacheExpires, 0);
  166. WebResponse response = (WebResponse) getResponse();
  167. response.setLastModifiedTime(Time.valueOf(when));
  168. response.setDateHeader("Expires", System.currentTimeMillis() + Duration.minutes(expires).getMilliseconds());
  169. }
  170. protected void setupPage(String repositoryName, String pageName) {
  171. String siteName = GitBlit.getString(Keys.web.siteName, Constants.NAME);
  172. if (StringUtils.isEmpty(siteName)) {
  173. siteName = Constants.NAME;
  174. }
  175. if (repositoryName != null && repositoryName.trim().length() > 0) {
  176. add(new Label("title", repositoryName + " - " + siteName));
  177. } else {
  178. add(new Label("title", siteName));
  179. }
  180. ExternalLink rootLink = new ExternalLink("rootLink", urlFor(GitBlitWebApp.HOME_PAGE_CLASS, null).toString());
  181. WicketUtils.setHtmlTooltip(rootLink, GitBlit.getString(Keys.web.siteName, Constants.NAME));
  182. add(rootLink);
  183. // Feedback panel for info, warning, and non-fatal error messages
  184. add(new FeedbackPanel("feedback"));
  185. add(new Label("gbVersion", "v" + Constants.getVersion()));
  186. if (GitBlit.getBoolean(Keys.web.aggressiveHeapManagement, false)) {
  187. System.gc();
  188. }
  189. }
  190. protected Map<AccessRestrictionType, String> getAccessRestrictions() {
  191. Map<AccessRestrictionType, String> map = new LinkedHashMap<AccessRestrictionType, String>();
  192. for (AccessRestrictionType type : AccessRestrictionType.values()) {
  193. switch (type) {
  194. case NONE:
  195. map.put(type, getString("gb.notRestricted"));
  196. break;
  197. case PUSH:
  198. map.put(type, getString("gb.pushRestricted"));
  199. break;
  200. case CLONE:
  201. map.put(type, getString("gb.cloneRestricted"));
  202. break;
  203. case VIEW:
  204. map.put(type, getString("gb.viewRestricted"));
  205. break;
  206. }
  207. }
  208. return map;
  209. }
  210. protected Map<AccessPermission, String> getAccessPermissions() {
  211. Map<AccessPermission, String> map = new LinkedHashMap<AccessPermission, String>();
  212. for (AccessPermission type : AccessPermission.values()) {
  213. switch (type) {
  214. case NONE:
  215. map.put(type, MessageFormat.format(getString("gb.noPermission"), type.code));
  216. break;
  217. case EXCLUDE:
  218. map.put(type, MessageFormat.format(getString("gb.excludePermission"), type.code));
  219. break;
  220. case VIEW:
  221. map.put(type, MessageFormat.format(getString("gb.viewPermission"), type.code));
  222. break;
  223. case CLONE:
  224. map.put(type, MessageFormat.format(getString("gb.clonePermission"), type.code));
  225. break;
  226. case PUSH:
  227. map.put(type, MessageFormat.format(getString("gb.pushPermission"), type.code));
  228. break;
  229. case CREATE:
  230. map.put(type, MessageFormat.format(getString("gb.createPermission"), type.code));
  231. break;
  232. case DELETE:
  233. map.put(type, MessageFormat.format(getString("gb.deletePermission"), type.code));
  234. break;
  235. case REWIND:
  236. map.put(type, MessageFormat.format(getString("gb.rewindPermission"), type.code));
  237. break;
  238. }
  239. }
  240. return map;
  241. }
  242. protected Map<FederationStrategy, String> getFederationTypes() {
  243. Map<FederationStrategy, String> map = new LinkedHashMap<FederationStrategy, String>();
  244. for (FederationStrategy type : FederationStrategy.values()) {
  245. switch (type) {
  246. case EXCLUDE:
  247. map.put(type, getString("gb.excludeFromFederation"));
  248. break;
  249. case FEDERATE_THIS:
  250. map.put(type, getString("gb.federateThis"));
  251. break;
  252. case FEDERATE_ORIGIN:
  253. map.put(type, getString("gb.federateOrigin"));
  254. break;
  255. }
  256. }
  257. return map;
  258. }
  259. protected Map<AuthorizationControl, String> getAuthorizationControls() {
  260. Map<AuthorizationControl, String> map = new LinkedHashMap<AuthorizationControl, String>();
  261. for (AuthorizationControl type : AuthorizationControl.values()) {
  262. switch (type) {
  263. case AUTHENTICATED:
  264. map.put(type, getString("gb.allowAuthenticatedDescription"));
  265. break;
  266. case NAMED:
  267. map.put(type, getString("gb.allowNamedDescription"));
  268. break;
  269. }
  270. }
  271. return map;
  272. }
  273. protected TimeZone getTimeZone() {
  274. return GitBlit.getBoolean(Keys.web.useClientTimezone, false) ? GitBlitWebSession.get()
  275. .getTimezone() : GitBlit.getTimezone();
  276. }
  277. protected String getServerName() {
  278. ServletWebRequest servletWebRequest = (ServletWebRequest) getRequest();
  279. HttpServletRequest req = servletWebRequest.getHttpServletRequest();
  280. return req.getServerName();
  281. }
  282. protected List<ProjectModel> getProjectModels() {
  283. final UserModel user = GitBlitWebSession.get().getUser();
  284. List<ProjectModel> projects = GitBlit.self().getProjectModels(user, true);
  285. return projects;
  286. }
  287. protected List<ProjectModel> getProjects(PageParameters params) {
  288. if (params == null) {
  289. return getProjectModels();
  290. }
  291. boolean hasParameter = false;
  292. String regex = WicketUtils.getRegEx(params);
  293. String team = WicketUtils.getTeam(params);
  294. int daysBack = params.getInt("db", 0);
  295. List<ProjectModel> availableModels = getProjectModels();
  296. Set<ProjectModel> models = new HashSet<ProjectModel>();
  297. if (!StringUtils.isEmpty(regex)) {
  298. // filter the projects by the regex
  299. hasParameter = true;
  300. Pattern pattern = Pattern.compile(regex);
  301. for (ProjectModel model : availableModels) {
  302. if (pattern.matcher(model.name).find()) {
  303. models.add(model);
  304. }
  305. }
  306. }
  307. if (!StringUtils.isEmpty(team)) {
  308. // filter the projects by the specified teams
  309. hasParameter = true;
  310. List<String> teams = StringUtils.getStringsFromValue(team, ",");
  311. // need TeamModels first
  312. List<TeamModel> teamModels = new ArrayList<TeamModel>();
  313. for (String name : teams) {
  314. TeamModel teamModel = GitBlit.self().getTeamModel(name);
  315. if (teamModel != null) {
  316. teamModels.add(teamModel);
  317. }
  318. }
  319. // brute-force our way through finding the matching models
  320. for (ProjectModel projectModel : availableModels) {
  321. for (String repositoryName : projectModel.repositories) {
  322. for (TeamModel teamModel : teamModels) {
  323. if (teamModel.hasRepositoryPermission(repositoryName)) {
  324. models.add(projectModel);
  325. }
  326. }
  327. }
  328. }
  329. }
  330. if (!hasParameter) {
  331. models.addAll(availableModels);
  332. }
  333. // time-filter the list
  334. if (daysBack > 0) {
  335. Calendar cal = Calendar.getInstance();
  336. cal.set(Calendar.HOUR_OF_DAY, 0);
  337. cal.set(Calendar.MINUTE, 0);
  338. cal.set(Calendar.SECOND, 0);
  339. cal.set(Calendar.MILLISECOND, 0);
  340. cal.add(Calendar.DATE, -1 * daysBack);
  341. Date threshold = cal.getTime();
  342. Set<ProjectModel> timeFiltered = new HashSet<ProjectModel>();
  343. for (ProjectModel model : models) {
  344. if (model.lastChange.after(threshold)) {
  345. timeFiltered.add(model);
  346. }
  347. }
  348. models = timeFiltered;
  349. }
  350. List<ProjectModel> list = new ArrayList<ProjectModel>(models);
  351. Collections.sort(list);
  352. return list;
  353. }
  354. public void warn(String message, Throwable t) {
  355. logger.warn(message, t);
  356. }
  357. public void error(String message, boolean redirect) {
  358. error(message, null, redirect ? getApplication().getHomePage() : null);
  359. }
  360. public void error(String message, Throwable t, boolean redirect) {
  361. error(message, t, getApplication().getHomePage());
  362. }
  363. public void error(String message, Throwable t, Class<? extends Page> toPage) {
  364. error(message, t, toPage, null);
  365. }
  366. public void error(String message, Throwable t, Class<? extends Page> toPage, PageParameters params) {
  367. if (t == null) {
  368. logger.error(message + " for " + GitBlitWebSession.get().getUsername());
  369. } else {
  370. logger.error(message + " for " + GitBlitWebSession.get().getUsername(), t);
  371. }
  372. if (toPage != null) {
  373. GitBlitWebSession.get().cacheErrorMessage(message);
  374. String relativeUrl = urlFor(toPage, params).toString();
  375. String absoluteUrl = RequestUtils.toAbsolutePath(relativeUrl);
  376. throw new RedirectToUrlException(absoluteUrl);
  377. } else {
  378. super.error(message);
  379. }
  380. }
  381. public void authenticationError(String message) {
  382. logger.error(getRequest().getURL() + " for " + GitBlitWebSession.get().getUsername());
  383. if (!GitBlitWebSession.get().isLoggedIn()) {
  384. // cache the request if we have not authenticated.
  385. // the request will continue after authentication.
  386. GitBlitWebSession.get().cacheRequest(getClass());
  387. }
  388. error(message, true);
  389. }
  390. }