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.Collections;
15  import java.util.List;
16  import java.util.stream.Collectors;
17  
18  import org.eclipse.jgit.lib.ObjectId;
19  
20  /**
21   * {@link org.eclipse.jgit.transport.PreUploadHook} that delegates to a list of
22   * other hooks.
23   * <p>
24   * Hooks are run in the order passed to the constructor. If running a method on
25   * one hook throws an exception, execution of remaining hook methods is aborted.
26   */
27  public class PreUploadHookChain implements PreUploadHook {
28  	private final List<PreUploadHook> hooks;
29  
30  	/**
31  	 * Create a new hook chaining the given hooks together.
32  	 *
33  	 * @param hooks
34  	 *            hooks to execute, in order.
35  	 * @return a new hook chain of the given hooks.
36  	 */
37  	public static PreUploadHook newChain(List<PreUploadHook> hooks) {
38  		List<PreUploadHook> newHooks = hooks.stream()
39  				.filter(hook -> !hook.equals(PreUploadHook.NULL))
40  				.collect(Collectors.toList());
41  
42  		if (newHooks.isEmpty()) {
43  			return PreUploadHook.NULL;
44  		} else if (newHooks.size() == 1) {
45  			return newHooks.get(0);
46  		} else {
47  			return new PreUploadHookChain(newHooks);
48  		}
49  	}
50  
51  	/** {@inheritDoc} */
52  	@Override
53  	public void onBeginNegotiateRound(UploadPack up,
54  			Collection<? extends ObjectId> wants, int cntOffered)
55  			throws ServiceMayNotContinueException {
56  		for (PreUploadHook hook : hooks) {
57  			hook.onBeginNegotiateRound(up, wants, cntOffered);
58  		}
59  	}
60  
61  	/** {@inheritDoc} */
62  	@Override
63  	public void onEndNegotiateRound(UploadPack up,
64  			Collection<? extends ObjectId> wants, int cntCommon,
65  			int cntNotFound, boolean ready)
66  			throws ServiceMayNotContinueException {
67  		for (PreUploadHook hook : hooks) {
68  			hook.onEndNegotiateRound(up, wants, cntCommon, cntNotFound, ready);
69  		}
70  	}
71  
72  	/** {@inheritDoc} */
73  	@Override
74  	public void onSendPack(UploadPack up,
75  			Collection<? extends ObjectId> wants,
76  			Collection<? extends ObjectId> haves)
77  			throws ServiceMayNotContinueException {
78  		for (PreUploadHook hook : hooks) {
79  			hook.onSendPack(up, wants, haves);
80  		}
81  	}
82  
83  	private PreUploadHookChain(List<PreUploadHook> hooks) {
84  		this.hooks = Collections.unmodifiableList(hooks);
85  	}
86  }