xref: /JGit/org.eclipse.jgit.junit.http/src/org/eclipse/jgit/junit/http/TestRequestLog.java (revision 5c5f7c6b146b24f2bd4afae1902df85ad6e57ea3)
1 /*
2  * Copyright (C) 2010, 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.junit.http;
12 
13 import java.io.IOException;
14 import java.util.ArrayList;
15 import java.util.List;
16 import java.util.concurrent.Semaphore;
17 
18 import javax.servlet.DispatcherType;
19 import javax.servlet.ServletException;
20 import javax.servlet.http.HttpServletRequest;
21 import javax.servlet.http.HttpServletResponse;
22 
23 import org.eclipse.jetty.server.Request;
24 import org.eclipse.jetty.server.Response;
25 import org.eclipse.jetty.server.handler.HandlerWrapper;
26 
27 /** Logs request made through {@link AppServer}. */
28 class TestRequestLog extends HandlerWrapper {
29 	private static final int MAX = 16;
30 
31 	private final List<AccessEvent> events = new ArrayList<>();
32 
33 	private final Semaphore active = new Semaphore(MAX, true);
34 
35 	/** Reset the log back to its original empty state. */
clear()36 	void clear() {
37 		try {
38 			for (;;) {
39 				try {
40 					active.acquire(MAX);
41 					break;
42 				} catch (InterruptedException e) {
43 					continue;
44 				}
45 			}
46 
47 			synchronized (events) {
48 				events.clear();
49 			}
50 		} finally {
51 			active.release(MAX);
52 		}
53 	}
54 
55 	/** @return all of the events made since the last clear. */
getEvents()56 	List<AccessEvent> getEvents() {
57 		try {
58 			for (;;) {
59 				try {
60 					active.acquire(MAX);
61 					break;
62 				} catch (InterruptedException e) {
63 					continue;
64 				}
65 			}
66 
67 			synchronized (events) {
68 				return events;
69 			}
70 		} finally {
71 			active.release(MAX);
72 		}
73 	}
74 
75 	/** {@inheritDoc} */
76 	@Override
handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)77 	public void handle(String target, Request baseRequest,
78 			HttpServletRequest request, HttpServletResponse response)
79 			throws IOException, ServletException {
80 		try {
81 			for (;;) {
82 				try {
83 					active.acquire();
84 					break;
85 				} catch (InterruptedException e) {
86 					continue;
87 				}
88 			}
89 
90 			super.handle(target, baseRequest, request, response);
91 
92 			if (DispatcherType.REQUEST.equals(baseRequest.getDispatcherType()))
93 				log((Request) request, (Response) response);
94 
95 		} finally {
96 			active.release();
97 		}
98 	}
99 
log(Request request, Response response)100 	private void log(Request request, Response response) {
101 		synchronized (events) {
102 			events.add(new AccessEvent(request, response));
103 		}
104 	}
105 }
106