ProtocolV2HookChain.java

  1. /*
  2.  * Copyright (C) 2019, Google LLC. 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.transport;

  11. import java.util.Collections;
  12. import java.util.List;
  13. import java.util.stream.Collectors;

  14. /**
  15.  * {@link org.eclipse.jgit.transport.ProtocolV2Hook} that delegates to a list of
  16.  * other hooks.
  17.  * <p>
  18.  * Hooks are run in the order passed to the constructor. If running a method on
  19.  * one hook throws an exception, execution of remaining hook methods is aborted.
  20.  *
  21.  * @since 5.5
  22.  */
  23. public class ProtocolV2HookChain implements ProtocolV2Hook {
  24.     private final List<? extends ProtocolV2Hook> hooks;

  25.     /**
  26.      * Create a new hook chaining the given hooks together.
  27.      *
  28.      * @param hooks
  29.      *            hooks to execute, in order.
  30.      * @return a new hook chain of the given hooks.
  31.      */
  32.     public static ProtocolV2Hook newChain(
  33.             List<? extends ProtocolV2Hook> hooks) {
  34.         List<? extends ProtocolV2Hook> newHooks = hooks.stream()
  35.                 .filter(hook -> !hook.equals(ProtocolV2Hook.DEFAULT))
  36.                 .collect(Collectors.toList());

  37.         if (newHooks.isEmpty()) {
  38.             return ProtocolV2Hook.DEFAULT;
  39.         } else if (newHooks.size() == 1) {
  40.             return newHooks.get(0);
  41.         } else {
  42.             return new ProtocolV2HookChain(newHooks);
  43.         }
  44.     }

  45.     @Override
  46.     public void onCapabilities(CapabilitiesV2Request req)
  47.             throws ServiceMayNotContinueException {
  48.         for (ProtocolV2Hook hook : hooks) {
  49.             hook.onCapabilities(req);
  50.         }
  51.     }

  52.     @Override
  53.     public void onLsRefs(LsRefsV2Request req)
  54.             throws ServiceMayNotContinueException {
  55.         for (ProtocolV2Hook hook : hooks) {
  56.             hook.onLsRefs(req);
  57.         }
  58.     }

  59.     @Override
  60.     public void onFetch(FetchV2Request req)
  61.             throws ServiceMayNotContinueException {
  62.         for (ProtocolV2Hook hook : hooks) {
  63.             hook.onFetch(req);
  64.         }
  65.     }

  66.     private ProtocolV2HookChain(List<? extends ProtocolV2Hook> hooks) {
  67.         this.hooks = Collections.unmodifiableList(hooks);
  68.     }
  69. }