View Javadoc
1   /*
2    * Copyright (C) 2011, 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  
11  package org.eclipse.jgit.transport;
12  
13  import java.util.Collection;
14  import java.util.List;
15  
16  /**
17   * {@link org.eclipse.jgit.transport.PreReceiveHook} that delegates to a list of
18   * other hooks.
19   * <p>
20   * Hooks are run in the order passed to the constructor.
21   */
22  public class PreReceiveHookChain implements PreReceiveHook {
23  	private final PreReceiveHook[] hooks;
24  	private final int count;
25  
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 PreReceiveHook newChain(List<? extends PreReceiveHook> hooks) {
34  		PreReceiveHook[] newHooks = new PreReceiveHook[hooks.size()];
35  		int i = 0;
36  		for (PreReceiveHook hook : hooks)
37  			if (hook != PreReceiveHook.NULL)
38  				newHooks[i++] = hook;
39  		switch (i) {
40  		case 0:
41  			return PreReceiveHook.NULL;
42  		case 1:
43  			return newHooks[0];
44  		default:
45  			return new PreReceiveHookChain(newHooks, i);
46  		}
47  	}
48  
49  	/** {@inheritDoc} */
50  	@Override
51  	public void onPreReceive(ReceivePack rp,
52  			Collection<ReceiveCommand> commands) {
53  		for (int i = 0; i < count; i++)
54  			hooks[i].onPreReceive(rp, commands);
55  	}
56  
57  	private PreReceiveHookChain(PreReceiveHook[] hooks, int count) {
58  		this.hooks = hooks;
59  		this.count = count;
60  	}
61  }