1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.hc.client5.http.impl.cache;
28
29 import java.time.Instant;
30 import java.util.Arrays;
31
32 import org.apache.hc.client5.http.cache.HttpCacheEntry;
33 import org.apache.hc.client5.http.cache.Resource;
34 import org.apache.hc.client5.http.cache.ResourceIOException;
35 import org.apache.hc.core5.http.Header;
36 import org.apache.hc.core5.util.LangUtils;
37 import org.hamcrest.BaseMatcher;
38 import org.hamcrest.Description;
39 import org.hamcrest.Matcher;
40
41 public class HttpCacheEntryMatcher extends BaseMatcher<HttpCacheEntry> {
42
43 private final HttpCacheEntry expectedValue;
44
45 public HttpCacheEntryMatcher(final HttpCacheEntry expectedValue) {
46 this.expectedValue = expectedValue;
47 }
48
49 @Override
50 public boolean matches(final Object item) {
51 if (item instanceof HttpCacheEntry) {
52 try {
53 final HttpCacheEntry otherValue = (HttpCacheEntry) item;
54
55 final int expectedStatus = expectedValue.getStatus();
56 final int otherStatus = otherValue.getStatus();
57 if (expectedStatus != otherStatus) {
58 return false;
59 }
60 final Instant expectedRequestInstant = expectedValue.getRequestInstant();
61 final Instant otherRequestInstant = otherValue.getRequestInstant();
62 if (!LangUtils.equals(expectedRequestInstant, otherRequestInstant)) {
63 return false;
64 }
65 final Instant expectedResponseInstant = expectedValue.getResponseInstant();
66 final Instant otherResponseInstant = otherValue.getResponseInstant();
67 if (!LangUtils.equals(expectedResponseInstant, otherResponseInstant)) {
68 return false;
69 }
70
71 final Header[] expectedHeaders = expectedValue.getHeaders();
72 final Header[] otherHeaders = otherValue.getHeaders();
73 if (expectedHeaders.length != otherHeaders.length) {
74 return false;
75 }
76 for (int i = 0; i < expectedHeaders.length; i++) {
77 final Header h1 = expectedHeaders[i];
78 final Header h2 = otherHeaders[i];
79 if (!h1.getName().equals(h2.getName()) || !LangUtils.equals(h1.getValue(), h2.getValue())) {
80 return false;
81 }
82 }
83 final Resource expectedResource = expectedValue.getResource();
84 final byte[] expectedContent = expectedResource != null ? expectedResource.get() : null;
85 final Resource otherResource = otherValue.getResource();
86 final byte[] otherContent = otherResource != null ? otherResource.get() : null;
87 return Arrays.equals(expectedContent, otherContent);
88 } catch (final ResourceIOException ex) {
89 throw new RuntimeException(ex);
90 }
91 }
92 return false;
93 }
94
95 @Override
96 public void describeTo(final Description description) {
97 description.appendValue(expectedValue);
98 }
99
100 public static Matcher<HttpCacheEntry> equivalent(final HttpCacheEntry target) {
101 return new HttpCacheEntryMatcher(target);
102 }
103
104 }