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.util.List;
32  import java.util.concurrent.atomic.AtomicReference;
33  
34  import org.apache.hc.core5.concurrent.FutureCallback;
35  import org.apache.hc.core5.http.EntityDetails;
36  import org.apache.hc.core5.http.Header;
37  import org.apache.hc.core5.http.HttpException;
38  import org.apache.hc.core5.http.HttpRequest;
39  import org.apache.hc.core5.http.HttpResponse;
40  import org.apache.hc.core5.http.HttpStatus;
41  import org.apache.hc.core5.http.nio.AsyncPushProducer;
42  import org.apache.hc.core5.http.nio.AsyncRequestConsumer;
43  import org.apache.hc.core5.http.nio.AsyncResponseProducer;
44  import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
45  import org.apache.hc.core5.http.nio.AsyncServerRequestHandler;
46  import org.apache.hc.core5.http.nio.BasicResponseProducer;
47  import org.apache.hc.core5.http.nio.CapacityChannel;
48  import org.apache.hc.core5.http.nio.DataStreamChannel;
49  import org.apache.hc.core5.http.nio.ResponseChannel;
50  import org.apache.hc.core5.http.protocol.HttpContext;
51  import org.apache.hc.core5.util.Asserts;
52  
53  /**
54   * @since 5.0
55   */
56  public abstract class AbstractServerExchangeHandler<T> implements AsyncServerExchangeHandler {
57  
58      private final AtomicReference<AsyncRequestConsumer<T>> requestConsumerRef;
59      private final AtomicReference<AsyncResponseProducer> responseProducerRef;
60  
61      public AbstractServerExchangeHandler() {
62          this.requestConsumerRef = new AtomicReference<>(null);
63          this.responseProducerRef = new AtomicReference<>(null);
64      }
65  
66      protected abstract AsyncRequestConsumer<T> supplyConsumer(
67              HttpRequest request,
68              HttpContext context) throws HttpException;
69  
70      protected abstract void handle(
71              T requestMessage,
72              AsyncServerRequestHandler.ResponseTrigger responseTrigger,
73              HttpContext context) throws HttpException, IOException;
74  
75      @Override
76      public final void handleRequest(
77              final HttpRequest request,
78              final EntityDetails entityDetails,
79              final ResponseChannel responseChannel,
80              final HttpContext context) throws HttpException, IOException {
81  
82          final AsyncRequestConsumer<T> requestConsumer = supplyConsumer(request, context);
83          if (requestConsumer == null) {
84              throw new HttpException("Unable to handle request");
85          }
86          requestConsumerRef.set(requestConsumer);
87          final AsyncServerRequestHandler.ResponseTrigger responseTrigger = new AsyncServerRequestHandler.ResponseTrigger() {
88  
89              @Override
90              public void sendInformation(final HttpResponse response) throws HttpException, IOException {
91                  responseChannel.sendInformation(response);
92              }
93  
94              @Override
95              public void submitResponse(
96                      final AsyncResponseProducer producer) throws HttpException, IOException {
97                  if (responseProducerRef.compareAndSet(null, producer)) {
98                      producer.sendResponse(responseChannel);
99                  }
100             }
101 
102             @Override
103             public void pushPromise(
104                     final HttpRequest promise, final AsyncPushProducer pushProducer) throws HttpException, IOException {
105                 responseChannel.pushPromise(promise, pushProducer);
106             }
107 
108             @Override
109             public String toString() {
110                 return "Response trigger: " + responseChannel;
111             }
112 
113         };
114         requestConsumer.consumeRequest(request, entityDetails, new FutureCallback<T>() {
115 
116             @Override
117             public void completed(final T result) {
118                 try {
119                     handle(result, responseTrigger, context);
120                 } catch (final HttpException ex) {
121                     try {
122                         responseTrigger.submitResponse(
123                                 new BasicResponseProducer(HttpStatus.SC_INTERNAL_SERVER_ERROR, ex.getMessage()));
124                     } catch (final HttpException | IOException ex2) {
125                         failed(ex2);
126                     }
127                 } catch (final IOException ex) {
128                     failed(ex);
129                 }
130             }
131 
132             @Override
133             public void failed(final Exception ex) {
134                 AbstractServerExchangeHandler.this.failed(ex);
135             }
136 
137             @Override
138             public void cancelled() {
139                 releaseResources();
140             }
141 
142         });
143 
144     }
145 
146     @Override
147     public final void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
148         final AsyncRequestConsumer<T> requestConsumer = requestConsumerRef.get();
149         Asserts.notNull(requestConsumer, "Data consumer");
150         requestConsumer.updateCapacity(capacityChannel);
151     }
152 
153     @Override
154     public final int consume(final ByteBuffer src) throws IOException {
155         final AsyncRequestConsumer<T> requestConsumer = requestConsumerRef.get();
156         Asserts.notNull(requestConsumer, "Data consumer");
157         return requestConsumer.consume(src);
158     }
159 
160     @Override
161     public final void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
162         final AsyncRequestConsumer<T> requestConsumer = requestConsumerRef.get();
163         Asserts.notNull(requestConsumer, "Data consumer");
164         requestConsumer.streamEnd(trailers);
165     }
166 
167     @Override
168     public final int available() {
169         final AsyncResponseProducer dataProducer = responseProducerRef.get();
170         return dataProducer != null ? dataProducer.available() : 0;
171     }
172 
173     @Override
174     public final void produce(final DataStreamChannel channel) throws IOException {
175         final AsyncResponseProducer dataProducer = responseProducerRef.get();
176         Asserts.notNull(dataProducer, "Data producer");
177         dataProducer.produce(channel);
178     }
179 
180     @Override
181     public final void failed(final Exception cause) {
182         try {
183             final AsyncRequestConsumer<T> requestConsumer = requestConsumerRef.get();
184             if (requestConsumer != null) {
185                 requestConsumer.failed(cause);
186             }
187             final AsyncResponseProducer dataProducer = responseProducerRef.get();
188             if (dataProducer != null) {
189                 dataProducer.failed(cause);
190             }
191         } finally {
192             releaseResources();
193         }
194     }
195 
196     @Override
197     public final void releaseResources() {
198         final AsyncRequestConsumer<T> requestConsumer = requestConsumerRef.getAndSet(null);
199         if (requestConsumer != null) {
200             requestConsumer.releaseResources();
201         }
202         final AsyncResponseProducer dataProducer = responseProducerRef.getAndSet(null);
203         if (dataProducer != null) {
204             dataProducer.releaseResources();
205         }
206     }
207 
208 }