View Javadoc

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.OutputStream;
25  
26  import org.apache.james.mime4j.codec.CodecUtil;
27  import org.apache.james.mime4j.storage.MultiReferenceStorage;
28  
29  /**
30   * Binary body backed by a
31   * {@link org.apache.james.mime4j.storage.Storage}
32   */
33  class StorageBinaryBody extends BinaryBody {
34  
35      private MultiReferenceStorage storage;
36  
37      public StorageBinaryBody(final MultiReferenceStorage storage) {
38          this.storage = storage;
39      }
40  
41      @Override
42      public InputStream getInputStream() throws IOException {
43          return storage.getInputStream();
44      }
45  
46      @Override
47      public void writeTo(OutputStream out) throws IOException {
48          if (out == null)
49              throw new IllegalArgumentException();
50  
51          InputStream in = storage.getInputStream();
52          CodecUtil.copy(in, out);
53          in.close();
54      }
55  
56      @Override
57      public StorageBinaryBody copy() {
58          storage.addReference();
59          return new StorageBinaryBody(storage);
60      }
61  
62      /**
63       * Deletes the Storage that holds the content of this binary body.
64       *
65       * @see org.apache.james.mime4j.message.Disposable#dispose()
66       */
67      @Override
68      public void dispose() {
69          if (storage != null) {
70              storage.delete();
71              storage = null;
72          }
73      }
74  
75  }