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