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.function.Supplier;
37  import org.apache.hc.core5.http.ContentType;
38  import org.apache.hc.core5.http.EntityDetails;
39  import org.apache.hc.core5.http.Header;
40  import org.apache.hc.core5.http.HttpException;
41  import org.apache.hc.core5.http.HttpRequest;
42  import org.apache.hc.core5.http.nio.AsyncEntityConsumer;
43  import org.apache.hc.core5.http.nio.AsyncRequestConsumer;
44  import org.apache.hc.core5.http.nio.CapacityChannel;
45  import org.apache.hc.core5.http.protocol.HttpContext;
46  import org.apache.hc.core5.util.Args;
47  
48  /**
49   * Abstract asynchronous request consumer that makes use of {@link AsyncEntityConsumer}
50   * to process request message content.
51   *
52   * @param <T> request processing result representation.
53   * @param <E> request entity representation.
54   *
55   * @since 5.0
56   */
57  public abstract class AbstractAsyncRequesterConsumer<T, E> implements AsyncRequestConsumer<T> {
58  
59      private final Supplier<AsyncEntityConsumer<E>> dataConsumerSupplier;
60      private final AtomicReference<AsyncEntityConsumer<E>> dataConsumerRef;
61  
62      public AbstractAsyncRequesterConsumer(final Supplier<AsyncEntityConsumer<E>> dataConsumerSupplier) {
63          this.dataConsumerSupplier = Args.notNull(dataConsumerSupplier, "Data consumer supplier");
64          this.dataConsumerRef = new AtomicReference<>(null);
65      }
66  
67      public AbstractAsyncRequesterConsumer(final AsyncEntityConsumer<E> dataConsumer) {
68          this(new Supplier<AsyncEntityConsumer<E>>() {
69  
70              @Override
71              public AsyncEntityConsumer<E> get() {
72                  return dataConsumer;
73              }
74  
75          });
76      }
77  
78      /**
79       * Triggered to generate object that represents a result of request message processing.
80       * @param request the request message.
81       * @param entity the request entity.
82       * @param contentType the request content type.
83       * @return the result of request processing.
84       */
85      protected abstract T buildResult(HttpRequest request, E entity, ContentType contentType);
86  
87      @Override
88      public final void consumeRequest(
89              final HttpRequest request,
90              final EntityDetails entityDetails,
91              final HttpContext httpContext, final FutureCallback<T> resultCallback) throws HttpException, IOException {
92          if (entityDetails != null) {
93              final AsyncEntityConsumer<E> dataConsumer = dataConsumerSupplier.get();
94              if (dataConsumer == null) {
95                  throw new HttpException("Supplied data consumer is null");
96              }
97              dataConsumerRef.set(dataConsumer);
98              dataConsumer.streamStart(entityDetails, new FutureCallback<E>() {
99  
100                 @Override
101                 public void completed(final E entity) {
102                     final ContentType contentType;
103                     try {
104                         contentType = ContentType.parse(entityDetails.getContentType());
105                         final T result = buildResult(request, entity, contentType);
106                         resultCallback.completed(result);
107                     } catch (final UnsupportedCharsetException ex) {
108                         resultCallback.failed(ex);
109                     }
110                 }
111 
112                 @Override
113                 public void failed(final Exception ex) {
114                     resultCallback.failed(ex);
115                 }
116 
117                 @Override
118                 public void cancelled() {
119                     resultCallback.cancelled();
120                 }
121 
122             });
123         } else {
124             resultCallback.completed(buildResult(request, null, null));
125         }
126 
127     }
128 
129     @Override
130     public final void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
131         final AsyncEntityConsumer<E> dataConsumer = dataConsumerRef.get();
132         dataConsumer.updateCapacity(capacityChannel);
133     }
134 
135     @Override
136     public final void consume(final ByteBuffer src) throws IOException {
137         final AsyncEntityConsumer<E> dataConsumer = dataConsumerRef.get();
138         dataConsumer.consume(src);
139     }
140 
141     @Override
142     public final void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
143         final AsyncEntityConsumer<E> dataConsumer = dataConsumerRef.get();
144         dataConsumer.streamEnd(trailers);
145     }
146 
147     @Override
148     public final void failed(final Exception cause) {
149         releaseResources();
150     }
151 
152     @Override
153     public final void releaseResources() {
154         final AsyncEntityConsumer<E> dataConsumer = dataConsumerRef.getAndSet(null);
155         if (dataConsumer != null) {
156             dataConsumer.releaseResources();
157         }
158     }
159 
160 }