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.util.Arrays;
30 import java.util.Date;
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.Factory;
40 import org.hamcrest.Matcher;
41
42 public class HttpCacheEntryMatcher extends BaseMatcher<HttpCacheEntry> {
43
44 private final HttpCacheEntry expectedValue;
45
46 public HttpCacheEntryMatcher(final HttpCacheEntry expectedValue) {
47 this.expectedValue = expectedValue;
48 }
49
50 @Override
51 public boolean matches(final Object item) {
52 if (item instanceof HttpCacheEntry) {
53 try {
54 final HttpCacheEntry otherValue = (HttpCacheEntry) item;
55
56 final int expectedStatus = expectedValue.getStatus();
57 final int otherStatus = otherValue.getStatus();
58 if (expectedStatus != otherStatus) {
59 return false;
60 }
61 final Date expectedRequestDate = expectedValue.getRequestDate();
62 final Date otherRequestDate = otherValue.getRequestDate();
63 if (!LangUtils.equals(expectedRequestDate, otherRequestDate)) {
64 return false;
65 }
66 final Date expectedResponseDate = expectedValue.getResponseDate();
67 final Date otherResponseDate = otherValue.getResponseDate();
68 if (!LangUtils.equals(expectedResponseDate, otherResponseDate)) {
69 return false;
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 if (!Arrays.equals(expectedContent, otherContent)) {
88 return false;
89 }
90 return true;
91 } catch (final ResourceIOException ex) {
92 throw new RuntimeException(ex);
93 }
94 }
95 return false;
96 }
97
98 @Override
99 public void describeTo(final Description description) {
100 description.appendValue(expectedValue);
101 }
102
103 @Factory
104 public static Matcher<HttpCacheEntry> equivalent(final HttpCacheEntry target) {
105 return new HttpCacheEntryMatcher(target);
106 }
107
108 }