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.http.nio.protocol;
28  
29  import java.io.IOException;
30  import java.util.concurrent.atomic.AtomicBoolean;
31  
32  import org.apache.http.HttpEntity;
33  import org.apache.http.HttpEntityEnclosingRequest;
34  import org.apache.http.HttpException;
35  import org.apache.http.HttpRequest;
36  import org.apache.http.entity.ContentType;
37  import org.apache.http.nio.ContentDecoder;
38  import org.apache.http.nio.IOControl;
39  import org.apache.http.protocol.HttpContext;
40  
41  /**
42   * Abstract {@link HttpAsyncRequestConsumer} implementation that relieves its
43   * subclasses from having to manage internal state and provides a number of protected
44   * event methods that they need to implement.
45   *
46   * @since 4.2
47   */
48  public abstract class AbstractAsyncRequestConsumer<T> implements HttpAsyncRequestConsumer<T> {
49  
50      private final AtomicBoolean completed;
51  
52      private volatile T result;
53      private volatile Exception ex;
54  
55      public AbstractAsyncRequestConsumer() {
56          super();
57          this.completed = new AtomicBoolean(false);
58      }
59  
60      /**
61       * Invoked when a HTTP request message is received. Please note
62       * that the {@link #onContentReceived(ContentDecoder, IOControl)} method
63       * will be invoked only for if the request message implements
64       * {@link HttpEntityEnclosingRequest} interface and has a content
65       * entity enclosed.
66       *
67       * @param request HTTP request message.
68       * @throws HttpException in case of HTTP protocol violation
69       * @throws IOException in case of an I/O error
70       */
71      protected abstract void onRequestReceived(
72              HttpRequest request) throws HttpException, IOException;
73  
74      /**
75       * Invoked if the request message encloses a content entity.
76       *
77       * @param entity HTTP entity
78       * @param contentType expected content type.
79       * @throws IOException in case of an I/O error
80       */
81      protected abstract void onEntityEnclosed(
82              HttpEntity entity, ContentType contentType) throws IOException;
83  
84      /**
85       * Invoked to process a chunk of content from the {@link ContentDecoder}.
86       * The {@link IOControl} interface can be used to suspend input events
87       * if the consumer is temporarily unable to consume more content.
88       * <p>
89       * The consumer can use the {@link ContentDecoder#isCompleted()} method
90       * to find out whether or not the message content has been fully consumed.
91       *
92       * @param decoder content decoder.
93       * @param ioControl I/O control of the underlying connection.
94       * @throws IOException in case of an I/O error
95       */
96      protected abstract void onContentReceived(
97              ContentDecoder decoder, IOControl ioControl) throws IOException;
98  
99      /**
100      * Invoked to generate a result object from the received HTTP request
101      * message.
102      *
103      * @param context HTTP context.
104      * @return result of the request processing.
105      * @throws Exception in case of an abnormal termination.
106      */
107     protected abstract T buildResult(HttpContext context) throws Exception;
108 
109     /**
110      * Invoked to release all system resources currently allocated.
111      */
112     protected abstract void releaseResources();
113 
114     /**
115      * Invoked when the consumer is being closed.
116      * @throws IOException may be thrown by subclassses
117      *
118      * @since 4.3
119      */
120     protected void onClose() throws IOException {
121     }
122 
123     /**
124      * Use {@link #onRequestReceived(HttpRequest)} instead.
125      */
126     @Override
127     public final void requestReceived(
128             final HttpRequest request) throws HttpException, IOException {
129         onRequestReceived(request);
130         if (request instanceof HttpEntityEnclosingRequest) {
131             final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
132             if (entity != null) {
133                 final ContentType contentType = ContentType.getOrDefault(entity);
134                 onEntityEnclosed(entity, contentType);
135             }
136         }
137     }
138 
139     /**
140      * Use {@link #onContentReceived(ContentDecoder, IOControl)} instead.
141      */
142     @Override
143     public final void consumeContent(
144             final ContentDecoder decoder, final IOControl ioControl) throws IOException {
145         onContentReceived(decoder, ioControl);
146     }
147 
148     /**
149      * Use {@link #buildResult(HttpContext)} instead.
150      */
151     @Override
152     public final void requestCompleted(final HttpContext context) {
153         if (this.completed.compareAndSet(false, true)) {
154             try {
155                 this.result = buildResult(context);
156             } catch (final Exception ex) {
157                 this.ex = ex;
158             } finally {
159                 releaseResources();
160             }
161         }
162     }
163 
164     @Override
165     public final void failed(final Exception ex) {
166         if (this.completed.compareAndSet(false, true)) {
167             this.ex = ex;
168             releaseResources();
169         }
170     }
171 
172     @Override
173     public final void close() throws IOException {
174         if (this.completed.compareAndSet(false, true)) {
175             releaseResources();
176             onClose();
177         }
178     }
179 
180     @Override
181     public Exception getException() {
182         return this.ex;
183     }
184 
185     @Override
186     public T getResult() {
187         return this.result;
188     }
189 
190     @Override
191     public boolean isDone() {
192         return this.completed.get();
193     }
194 
195 }