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