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.

RegexGroupFilter.java 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright (C) 2009-2010, Google Inc. and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.http.server.glue;
  11. import static java.lang.Integer.valueOf;
  12. import java.io.IOException;
  13. import java.text.MessageFormat;
  14. import javax.servlet.Filter;
  15. import javax.servlet.FilterChain;
  16. import javax.servlet.FilterConfig;
  17. import javax.servlet.ServletException;
  18. import javax.servlet.ServletRequest;
  19. import javax.servlet.ServletResponse;
  20. import org.eclipse.jgit.http.server.HttpServerText;
  21. /**
  22. * Switch servlet path and path info to use another regex match group.
  23. * <p>
  24. * This filter is meant to be installed in the middle of a pipeline created by
  25. * {@link org.eclipse.jgit.http.server.glue.MetaServlet#serveRegex(String)}. The
  26. * passed request's servlet path is updated to be all text up to the start of
  27. * the designated capture group, and the path info is changed to the contents of
  28. * the capture group.
  29. */
  30. public class RegexGroupFilter implements Filter {
  31. private final int groupIdx;
  32. /**
  33. * Constructor for RegexGroupFilter
  34. *
  35. * @param groupIdx
  36. * capture group number, 1 through the number of groups.
  37. */
  38. public RegexGroupFilter(int groupIdx) {
  39. if (groupIdx < 1)
  40. throw new IllegalArgumentException(MessageFormat.format(
  41. HttpServerText.get().invalidIndex, valueOf(groupIdx)));
  42. this.groupIdx = groupIdx - 1;
  43. }
  44. /** {@inheritDoc} */
  45. @Override
  46. public void init(FilterConfig config) throws ServletException {
  47. // Do nothing.
  48. }
  49. /** {@inheritDoc} */
  50. @Override
  51. public void destroy() {
  52. // Do nothing.
  53. }
  54. /** {@inheritDoc} */
  55. @Override
  56. public void doFilter(final ServletRequest request,
  57. final ServletResponse rsp, final FilterChain chain)
  58. throws IOException, ServletException {
  59. final WrappedRequest[] g = groupsFor(request);
  60. if (groupIdx < g.length)
  61. chain.doFilter(g[groupIdx], rsp);
  62. else
  63. throw new ServletException(MessageFormat.format(
  64. HttpServerText.get().invalidRegexGroup,
  65. valueOf(groupIdx + 1)));
  66. }
  67. private static WrappedRequest[] groupsFor(ServletRequest r) {
  68. return (WrappedRequest[]) r.getAttribute(MetaFilter.REGEX_GROUPS);
  69. }
  70. }