View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.core5.http.nio.support;
28  
29  import java.io.IOException;
30  import java.nio.ByteBuffer;
31  import java.nio.charset.UnsupportedCharsetException;
32  import java.util.List;
33  import java.util.concurrent.atomic.AtomicReference;
34  
35  import org.apache.hc.core5.concurrent.FutureCallback;
36  import org.apache.hc.core5.http.ContentType;
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.HttpResponse;
41  import org.apache.hc.core5.http.nio.AsyncEntityConsumer;
42  import org.apache.hc.core5.http.nio.AsyncResponseConsumer;
43  import org.apache.hc.core5.http.nio.CapacityChannel;
44  import org.apache.hc.core5.http.protocol.HttpContext;
45  import org.apache.hc.core5.util.Args;
46  
47  /**
48   * Abstract asynchronous response consumer that makes use of {@link AsyncEntityConsumer}
49   * to process response message content.
50   *
51   * @param <T> response processing result representation.
52   * @param <E> response entity representation.
53   *
54   * @since 5.0
55   */
56  public abstract class AbstractAsyncResponseConsumer<T, E> implements AsyncResponseConsumer<T> {
57  
58      private final AsyncEntityConsumer<E> entityConsumer;
59      private final AtomicReference<T> resultRef;
60      private final AtomicReference<Exception> exceptionRef;
61  
62      public AbstractAsyncResponseConsumer(final AsyncEntityConsumer<E> entityConsumer) {
63          Args.notNull(entityConsumer, "Entity consumer");
64          this.entityConsumer = entityConsumer;
65          this.resultRef = new AtomicReference<>(null);
66          this.exceptionRef = new AtomicReference<>(null);
67      }
68  
69      /**
70       * Triggered to generate object that represents a result of response message processing.
71       * @param response the response message.
72       * @param entity the response entity.
73       * @param contentType the response content type.
74       * @return the result of response processing.
75       */
76      protected abstract T buildResult(HttpResponse response, E entity, ContentType contentType);
77  
78      @Override
79      public final void consumeResponse(
80              final HttpResponse response,
81              final EntityDetails entityDetails,
82              final HttpContext httpContext, final FutureCallback<T> resultCallback) throws HttpException, IOException {
83          if (entityDetails != null) {
84              entityConsumer.streamStart(entityDetails, new FutureCallback<E>() {
85  
86                  @Override
87                  public void completed(final E entity) {
88                      final ContentType contentType;
89                      try {
90                          contentType = ContentType.parse(entityDetails.getContentType());
91                          final T result = buildResult(response, entity, contentType);
92                          resultRef.compareAndSet(null, result);
93                          if (resultCallback != null) {
94                              resultCallback.completed(result);
95                          }
96                      } catch (final UnsupportedCharsetException ex) {
97                          exceptionRef.compareAndSet(null, ex);
98                          if (resultCallback != null) {
99                              resultCallback.failed(ex);
100                         }
101                     }
102                 }
103 
104                 @Override
105                 public void failed(final Exception ex) {
106                     exceptionRef.compareAndSet(null, ex);
107                     if (resultCallback != null) {
108                         resultCallback.failed(ex);
109                     }
110                 }
111 
112                 @Override
113                 public void cancelled() {
114                     if (resultCallback != null) {
115                         resultCallback.cancelled();
116                     }
117                 }
118 
119             });
120         } else {
121             final T result = buildResult(response, null, null);
122             resultRef.compareAndSet(null, result);
123             if (resultCallback != null) {
124                 resultCallback.completed(result);
125             }
126             entityConsumer.releaseResources();
127         }
128 
129     }
130 
131     @Override
132     public final void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
133         entityConsumer.updateCapacity(capacityChannel);
134     }
135 
136     @Override
137     public final void consume(final ByteBuffer src) throws IOException {
138         entityConsumer.consume(src);
139     }
140 
141     @Override
142     public final void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
143         entityConsumer.streamEnd(trailers);
144     }
145 
146     @Override
147     public T getResult() {
148         return resultRef.get();
149     }
150 
151     public Exception getException() {
152         return exceptionRef.get();
153     }
154 
155     @Override
156     public final void failed(final Exception cause) {
157         exceptionRef.compareAndSet(null, cause);
158         releaseResources();
159     }
160 
161     @Override
162     public final void releaseResources() {
163         entityConsumer.releaseResources();
164     }
165 
166 }