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.core5.http.nio.entity;
28
29 import java.io.IOException;
30 import java.nio.ByteBuffer;
31 import java.security.MessageDigest;
32 import java.security.NoSuchAlgorithmException;
33 import java.util.ArrayList;
34 import java.util.List;
35
36 import org.apache.hc.core5.concurrent.FutureCallback;
37 import org.apache.hc.core5.http.EntityDetails;
38 import org.apache.hc.core5.http.Header;
39 import org.apache.hc.core5.http.HttpException;
40 import org.apache.hc.core5.http.nio.AsyncEntityConsumer;
41 import org.apache.hc.core5.http.nio.CapacityChannel;
42 import org.apache.hc.core5.util.Args;
43
44
45
46
47
48
49
50
51 public class DigestingEntityConsumer<T> implements AsyncEntityConsumer<T> {
52
53 private final AsyncEntityConsumer<T> wrapped;
54 private final List<Header> trailers;
55 private final MessageDigest digester;
56
57 private volatile byte[] digest;
58
59 public DigestingEntityConsumer(
60 final String algo,
61 final AsyncEntityConsumer<T> wrapped) throws NoSuchAlgorithmException {
62 this.wrapped = Args.notNull(wrapped, "Entity consumer");
63 this.trailers = new ArrayList<>();
64 this.digester = MessageDigest.getInstance(algo);
65 }
66
67 @Override
68 public void streamStart(
69 final EntityDetails entityDetails,
70 final FutureCallback<T> resultCallback) throws IOException, HttpException {
71 wrapped.streamStart(entityDetails, resultCallback);
72 }
73
74 @Override
75 public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
76 wrapped.updateCapacity(capacityChannel);
77 }
78
79 @Override
80 public void consume(final ByteBuffer src) throws IOException {
81 src.mark();
82 digester.update(src);
83 src.reset();
84 wrapped.consume(src);
85 }
86
87 @Override
88 public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
89 if (trailers != null) {
90 this.trailers.addAll(trailers);
91 }
92 digest = digester.digest();
93 wrapped.streamEnd(trailers);
94 }
95
96 @Override
97 public void failed(final Exception cause) {
98 wrapped.failed(cause);
99 }
100
101 @Override
102 public T getContent() {
103 return wrapped.getContent();
104 }
105
106 @Override
107 public void releaseResources() {
108 wrapped.releaseResources();
109 }
110
111
112
113
114
115
116 public List<Header> getTrailers() {
117 return trailers != null ? new ArrayList<>(trailers) : null;
118 }
119
120
121
122
123
124
125 public byte[] getDigest() {
126 return digest;
127 }
128
129 }