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.entity;
28  
29  import java.io.IOException;
30  import java.io.InputStream;
31  import java.io.UnsupportedEncodingException;
32  import java.nio.ByteBuffer;
33  import java.nio.charset.UnsupportedCharsetException;
34  import java.util.List;
35  import java.util.concurrent.Executor;
36  import java.util.concurrent.atomic.AtomicReference;
37  
38  import org.apache.hc.core5.concurrent.FutureCallback;
39  import org.apache.hc.core5.http.EntityDetails;
40  import org.apache.hc.core5.http.Header;
41  import org.apache.hc.core5.http.HttpException;
42  import org.apache.hc.core5.http.ContentType;
43  import org.apache.hc.core5.http.nio.AsyncEntityConsumer;
44  import org.apache.hc.core5.http.nio.CapacityChannel;
45  import org.apache.hc.core5.util.Args;
46  
47  /**
48   * @since 5.0
49   */
50  public abstract class AbstractClassicEntityConsumer<T> implements AsyncEntityConsumer<T> {
51  
52      private enum State { IDLE, ACTIVE, COMPLETED }
53  
54      private final Executor executor;
55      private final SharedInputBuffer buffer;
56      private final AtomicReference<State> state;
57      private final AtomicReference<T> resultRef;
58      private final AtomicReference<Exception> exceptionRef;
59  
60      public AbstractClassicEntityConsumer(final int initialBufferSize, final Executor executor) {
61          this.executor = Args.notNull(executor, "Executor");
62          this.buffer = new SharedInputBuffer(initialBufferSize);
63          this.state = new AtomicReference<>(State.IDLE);
64          this.resultRef = new AtomicReference<>(null);
65          this.exceptionRef = new AtomicReference<>(null);
66      }
67  
68      protected abstract T consumeData(ContentType contentType, InputStream inputStream) throws IOException;
69  
70      @Override
71      public final void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
72          buffer.updateCapacity(capacityChannel);
73      }
74  
75      @Override
76      public final void streamStart(final EntityDetails entityDetails, final FutureCallback<T> resultCallback) throws HttpException, IOException {
77          final ContentType contentType;
78          try {
79              contentType = ContentType.parse(entityDetails.getContentType());
80          } catch (final UnsupportedCharsetException ex) {
81              throw new UnsupportedEncodingException(ex.getMessage());
82          }
83          if (state.compareAndSet(State.IDLE, State.ACTIVE)) {
84              executor.execute(new Runnable() {
85  
86                  @Override
87                  public void run() {
88                      try {
89                          final T result = consumeData(contentType, new ContentInputStream(buffer));
90                          resultRef.set(result);
91                          resultCallback.completed(result);
92                      } catch (final Exception ex) {
93                          buffer.abort();
94                          resultCallback.failed(ex);
95                      } finally {
96                          state.set(State.COMPLETED);
97                      }
98                  }
99  
100             });
101         }
102     }
103 
104     @Override
105     public final int consume(final ByteBuffer src) throws IOException {
106         return buffer.fill(src);
107     }
108 
109     @Override
110     public final void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
111         buffer.markEndStream();
112     }
113 
114     @Override
115     public final void failed(final Exception cause) {
116         if (exceptionRef.compareAndSet(null, cause)) {
117             releaseResources();
118         }
119     }
120 
121     public final Exception getException() {
122         return exceptionRef.get();
123     }
124 
125     @Override
126     public final T getContent() {
127         return resultRef.get();
128     }
129 
130     @Override
131     public void releaseResources() {
132     }
133 
134 }