AdvertiseRefsHookChain.java

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

  11. import java.io.IOException;
  12. import java.util.List;

  13. /**
  14.  * {@link org.eclipse.jgit.transport.AdvertiseRefsHook} that delegates to a list
  15.  * of other hooks.
  16.  * <p>
  17.  * Hooks are run in the order passed to the constructor. A hook may inspect or
  18.  * modify the results of the previous hooks in the chain by calling
  19.  * {@link org.eclipse.jgit.transport.UploadPack#getAdvertisedRefs()}, or
  20.  * {@link org.eclipse.jgit.transport.ReceivePack#getAdvertisedRefs()} or
  21.  * {@link org.eclipse.jgit.transport.ReceivePack#getAdvertisedObjects()}.
  22.  */
  23. public class AdvertiseRefsHookChain implements AdvertiseRefsHook {
  24.     private final AdvertiseRefsHook[] hooks;
  25.     private final int count;

  26.     /**
  27.      * Create a new hook chaining the given hooks together.
  28.      *
  29.      * @param hooks
  30.      *            hooks to execute, in order.
  31.      * @return a new hook chain of the given hooks.
  32.      */
  33.     public static AdvertiseRefsHook newChain(List<? extends AdvertiseRefsHook> hooks) {
  34.         AdvertiseRefsHook[] newHooks = new AdvertiseRefsHook[hooks.size()];
  35.         int i = 0;
  36.         for (AdvertiseRefsHook hook : hooks)
  37.             if (hook != AdvertiseRefsHook.DEFAULT)
  38.                 newHooks[i++] = hook;
  39.         switch (i) {
  40.         case 0:
  41.             return AdvertiseRefsHook.DEFAULT;
  42.         case 1:
  43.             return newHooks[0];
  44.         default:
  45.             return new AdvertiseRefsHookChain(newHooks, i);
  46.         }
  47.     }

  48.     /**
  49.      * {@inheritDoc}
  50.      */
  51.     @Override
  52.     public void advertiseRefs(ReceivePack rp)
  53.             throws IOException {
  54.         for (int i = 0; i < count; i++)
  55.             hooks[i].advertiseRefs(rp);
  56.     }

  57.     /** {@inheritDoc} */
  58.     @Override
  59.     public void advertiseRefs(UploadPack rp)
  60.             throws ServiceMayNotContinueException {
  61.         for (int i = 0; i < count; i++)
  62.             hooks[i].advertiseRefs(rp);
  63.     }

  64.     private AdvertiseRefsHookChain(AdvertiseRefsHook[] hooks, int count) {
  65.         this.hooks = hooks;
  66.         this.count = count;
  67.     }
  68. }