1 /****************************************************************
2 * Licensed to the Apache Software Foundation (ASF) under one *
3 * or more contributor license agreements. See the NOTICE file *
4 * distributed with this work for additional information *
5 * regarding copyright ownership. The ASF licenses this file *
6 * to you under the Apache License, Version 2.0 (the *
7 * "License"); you may not use this file except in compliance *
8 * with the License. You may obtain a copy of the License at *
9 * *
10 * http://www.apache.org/licenses/LICENSE-2.0 *
11 * *
12 * Unless required by applicable law or agreed to in writing, *
13 * software distributed under the License is distributed on an *
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
15 * KIND, either express or implied. See the License for the *
16 * specific language governing permissions and limitations *
17 * under the License. *
18 ****************************************************************/
19
20 package org.apache.james.mime4j.message;
21
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.InputStreamReader;
25 import java.io.OutputStream;
26 import java.io.Reader;
27 import java.nio.charset.Charset;
28
29 import org.apache.james.mime4j.codec.CodecUtil;
30 import org.apache.james.mime4j.storage.MultiReferenceStorage;
31 import org.apache.james.mime4j.util.CharsetUtil;
32
33 /**
34 * Text body backed by a {@link org.apache.james.mime4j.storage.Storage}.
35 */
36 class StorageTextBody extends TextBody {
37
38 private MultiReferenceStorage storage;
39 private Charset charset;
40
41 public StorageTextBody(MultiReferenceStorage storage, Charset charset) {
42 this.storage = storage;
43 this.charset = charset;
44 }
45
46 @Override
47 public String getMimeCharset() {
48 return CharsetUtil.toMimeCharset(charset.name());
49 }
50
51 @Override
52 public Reader getReader() throws IOException {
53 return new InputStreamReader(storage.getInputStream(), charset);
54 }
55
56 @Override
57 public void writeTo(OutputStream out) throws IOException {
58 if (out == null)
59 throw new IllegalArgumentException();
60
61 InputStream in = storage.getInputStream();
62 CodecUtil.copy(in, out);
63 in.close();
64 }
65
66 @Override
67 public StorageTextBody copy() {
68 storage.addReference();
69 return new StorageTextBody(storage, charset);
70 }
71
72 /**
73 * Deletes the Storage that holds the content of this text body.
74 *
75 * @see org.apache.james.mime4j.message.Disposable#dispose()
76 */
77 @Override
78 public void dispose() {
79 if (storage != null) {
80 storage.delete();
81 storage = null;
82 }
83 }
84
85 }