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.entity.mime.content;
29
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33
34 import org.apache.http.entity.mime.MIME;
35
36 /**
37 *
38 * @since 4.0
39 */
40 public class InputStreamBody extends AbstractContentBody {
41
42 private final InputStream in;
43 private final String filename;
44
45 public InputStreamBody(final InputStream in, final String mimeType, final String filename) {
46 super(mimeType);
47 if (in == null) {
48 throw new IllegalArgumentException("Input stream may not be null");
49 }
50 this.in = in;
51 this.filename = filename;
52 }
53
54 public InputStreamBody(final InputStream in, final String filename) {
55 this(in, "application/octet-stream", filename);
56 }
57
58 public InputStream getInputStream() {
59 return this.in;
60 }
61
62 public void writeTo(final OutputStream out) throws IOException {
63 if (out == null) {
64 throw new IllegalArgumentException("Output stream may not be null");
65 }
66 try {
67 byte[] tmp = new byte[4096];
68 int l;
69 while ((l = this.in.read(tmp)) != -1) {
70 out.write(tmp, 0, l);
71 }
72 out.flush();
73 } finally {
74 this.in.close();
75 }
76 }
77
78 public String getTransferEncoding() {
79 return MIME.ENC_BINARY;
80 }
81
82 public String getCharset() {
83 return null;
84 }
85
86 public long getContentLength() {
87 return -1;
88 }
89
90 public String getFilename() {
91 return this.filename;
92 }
93
94 }