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  
28  package org.apache.http.nio.entity;
29  
30  import java.io.ByteArrayInputStream;
31  import java.io.IOException;
32  import java.io.InputStream;
33  import java.io.OutputStream;
34  import java.io.UnsupportedEncodingException;
35  import java.nio.ByteBuffer;
36  import java.nio.charset.Charset;
37  import java.nio.charset.UnsupportedCharsetException;
38  
39  import org.apache.http.annotation.NotThreadSafe;
40  import org.apache.http.entity.AbstractHttpEntity;
41  import org.apache.http.entity.ContentType;
42  import org.apache.http.nio.ContentEncoder;
43  import org.apache.http.nio.IOControl;
44  import org.apache.http.protocol.HTTP;
45  import org.apache.http.util.Args;
46  
47  /**
48   * A simple, self contained, repeatable non-blocking entity that retrieves
49   * its content from a {@link String} object.
50   *
51   * @since 4.0
52   *
53   */
54  @SuppressWarnings("deprecation")
55  @NotThreadSafe
56  public class NStringEntity extends AbstractHttpEntity
57                             implements HttpAsyncContentProducer, ProducingNHttpEntity {
58  
59      private final byte[] b;
60      private final ByteBuffer buf;
61      /**
62       * @deprecated (4.2)
63       */
64      @Deprecated
65      protected final byte[] content;
66      /**
67       * @deprecated (4.2)
68       */
69      @Deprecated
70      protected final ByteBuffer buffer;
71  
72      /**
73       * Creates a NStringEntity with the specified content and content type.
74       *
75       * @param s content to be used. Not {@code null}.
76       * @param contentType content type to be used. May be {@code null}, in which case
77       * {@link ContentType#TEXT_PLAIN} is assumed.
78       *
79       * @throws IllegalArgumentException if the string parameter is null
80       *
81       * @since 4.2
82       */
83      public NStringEntity(final String s, final ContentType contentType) {
84          Args.notNull(s, "Source string");
85          Charset charset = contentType != null ? contentType.getCharset() : null;
86          if (charset == null) {
87              charset = HTTP.DEF_CONTENT_CHARSET;
88          }
89          try {
90              this.b = s.getBytes(charset.name());
91          } catch (final UnsupportedEncodingException ex) {
92              // should never happen
93              throw new UnsupportedCharsetException(charset.name());
94          }
95          this.buf = ByteBuffer.wrap(this.b);
96          this.content = b;
97          this.buffer = this.buf;
98          if (contentType != null) {
99              setContentType(contentType.toString());
100         }
101     }
102 
103     /**
104      * Creates a NStringEntity with the specified content and charset. The MIME type defaults
105      * to "text/plain".
106      *
107      * @param s content to be used. Not {@code null}.
108      * @param charset character set to be used. May be {@code null}, in which case the default
109      *   is {@link HTTP#DEF_CONTENT_CHARSET} is assumed
110      *
111      * @throws IllegalArgumentException if the string parameter is null
112      * @throws UnsupportedCharsetException Thrown when the named charset is not available in
113      * this instance of the Java virtual machine
114      */
115     public NStringEntity(final String s, final String charset)
116             throws UnsupportedEncodingException {
117         this(s, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset));
118     }
119 
120     /**
121      * Creates a NStringEntity with the specified content and charset. The MIME type defaults
122      * to "text/plain".
123      *
124      * @param s content to be used. Not {@code null}.
125      * @param charset character set to be used. May be {@code null}, in which case the default
126      *   is {@link HTTP#DEF_CONTENT_CHARSET} is assumed
127      *
128      * @throws IllegalArgumentException if the string parameter is null
129      *
130      * @since 4.2
131      */
132     public NStringEntity(final String s, final Charset charset) {
133         this(s, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset));
134     }
135 
136     /**
137      * Creates a NStringEntity with the specified content. The content type defaults to
138      * {@link ContentType#TEXT_PLAIN}.
139      *
140      * @param s content to be used. Not {@code null}.
141      *
142      * @throws IllegalArgumentException if the string parameter is null
143      * @throws UnsupportedEncodingException if the default HTTP charset is not supported.
144      */
145     public NStringEntity(final String s) throws UnsupportedEncodingException {
146         this(s, ContentType.DEFAULT_TEXT);
147     }
148 
149     public boolean isRepeatable() {
150         return true;
151     }
152 
153     public long getContentLength() {
154         return this.b.length;
155     }
156 
157     /**
158      * {@inheritDoc}
159      *
160      * @since 4.2
161      */
162     public void close() {
163         this.buf.rewind();
164     }
165 
166     /**
167      * {@inheritDoc}
168      *
169      * @deprecated (4.2) use {@link #close()}
170      */
171     @Deprecated
172     public void finish() {
173         close();
174     }
175 
176     public void produceContent(
177             final ContentEncoder encoder, final IOControl ioctrl) throws IOException {
178         encoder.write(this.buf);
179         if (!this.buf.hasRemaining()) {
180             encoder.complete();
181         }
182     }
183 
184     public boolean isStreaming() {
185         return false;
186     }
187 
188     public InputStream getContent() {
189         return new ByteArrayInputStream(this.b);
190     }
191 
192     public void writeTo(final OutputStream outstream) throws IOException {
193         Args.notNull(outstream, "Output stream");
194         outstream.write(this.b);
195         outstream.flush();
196     }
197 
198 }