1 /*
2  * Copyright (c) 2007 Mockito contributors
3  * This program is made available under the terms of the MIT License.
4  */
5 package org.mockito.internal.matchers;
6 
7 import org.mockito.ArgumentMatcher;
8 
9 import static org.mockito.internal.exceptions.Reporter.noArgumentValueWasCaptured;
10 
11 import java.io.Serializable;
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.concurrent.locks.Lock;
15 import java.util.concurrent.locks.ReadWriteLock;
16 import java.util.concurrent.locks.ReentrantReadWriteLock;
17 
18 @SuppressWarnings("unchecked")
19 public class CapturingMatcher<T> implements ArgumentMatcher<T>, CapturesArguments, VarargMatcher, Serializable {
20 
21     private final List<Object> arguments = new ArrayList<Object>();
22 
23     private final ReadWriteLock lock = new ReentrantReadWriteLock();
24     private final Lock readLock = lock.readLock();
25     private final Lock writeLock = lock.writeLock();
26 
matches(Object argument)27     public boolean matches(Object argument) {
28         return true;
29     }
30 
toString()31     public String toString() {
32         return "<Capturing argument>";
33     }
34 
getLastValue()35     public T getLastValue() {
36         readLock.lock();
37         try {
38             if (arguments.isEmpty()) {
39                 throw noArgumentValueWasCaptured();
40             }
41 
42             return (T) arguments.get(arguments.size() - 1);
43         } finally {
44             readLock.unlock();
45         }
46     }
47 
getAllValues()48     public List<T> getAllValues() {
49         readLock.lock();
50         try {
51             return new ArrayList<T>((List) arguments);
52         } finally {
53             readLock.unlock();
54         }
55     }
56 
captureFrom(Object argument)57     public void captureFrom(Object argument) {
58         writeLock.lock();
59         try {
60             this.arguments.add(argument);
61         } finally {
62             writeLock.unlock();
63         }
64     }
65 }
66