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     public final void responseReceived(
125             final HttpResponse response) throws IOException, HttpException {
126         onResponseReceived(response);
127         final HttpEntity entity = response.getEntity();
128         if (entity != null) {
129             final ContentType contentType = ContentType.getOrDefault(entity);
130             onEntityEnclosed(entity, contentType);
131         }
132     }
133 
134     /**
135      * Use {@link #onContentReceived(ContentDecoder, IOControl)} instead.
136      */
137     public final void consumeContent(
138             final ContentDecoder decoder, final IOControl ioctrl) throws IOException {
139         onContentReceived(decoder, ioctrl);
140     }
141 
142     /**
143      * Use {@link #buildResult(HttpContext)} instead.
144      */
145     public final void responseCompleted(final HttpContext context) {
146         if (this.completed.compareAndSet(false, true)) {
147             try {
148                 this.result = buildResult(context);
149             } catch (final Exception ex) {
150                 this.ex = ex;
151             } finally {
152                 releaseResources();
153             }
154         }
155     }
156 
157     public final boolean cancel() {
158         if (this.completed.compareAndSet(false, true)) {
159             releaseResources();
160             return true;
161         }
162         return false;
163     }
164 
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     public final void close() throws IOException {
173         if (this.completed.compareAndSet(false, true)) {
174             releaseResources();
175             onClose();
176         }
177     }
178 
179     public Exception getException() {
180         return this.ex;
181     }
182 
183     public T getResult() {
184         return this.result;
185     }
186 
187     public boolean isDone() {
188         return this.completed.get();
189     }
190 
191 }