001    /**
002     *
003     * Copyright 2003-2006 The Apache Software Foundation
004     *
005     *  Licensed under the Apache License, Version 2.0 (the "License");
006     *  you may not use this file except in compliance with the License.
007     *  You may obtain a copy of the License at
008     *
009     *     http://www.apache.org/licenses/LICENSE-2.0
010     *
011     *  Unless required by applicable law or agreed to in writing, software
012     *  distributed under the License is distributed on an "AS IS" BASIS,
013     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     *  See the License for the specific language governing permissions and
015     *  limitations under the License.
016     */
017    
018    package javax.mail.internet;
019    
020    import java.io.IOException;
021    import java.io.InputStream;
022    import java.io.OutputStream;
023    import java.net.UnknownServiceException;
024    import javax.activation.DataSource;
025    import javax.mail.MessageAware;
026    import javax.mail.MessageContext;
027    import javax.mail.MessagingException;
028    
029    /**
030     * @version $Rev: 421852 $ $Date: 2006-07-14 03:02:19 -0700 (Fri, 14 Jul 2006) $
031     */
032    public class MimePartDataSource implements DataSource, MessageAware {
033        // the part that provides the data form this data source.
034        protected MimePart part;
035    
036        public MimePartDataSource(MimePart part) {
037            this.part = part;
038        }
039    
040        public InputStream getInputStream() throws IOException {
041            try {
042                InputStream stream;
043                if (part instanceof MimeMessage) {
044                    stream = ((MimeMessage) part).getContentStream();
045                } else if (part instanceof MimeBodyPart) {
046                    stream = ((MimeBodyPart) part).getContentStream();
047                } else {
048                    throw new MessagingException("Unknown part");
049                }
050                String encoding = part.getEncoding();
051                return encoding == null ? stream : MimeUtility.decode(stream, encoding);
052            } catch (MessagingException e) {
053                throw (IOException) new IOException(e.getMessage()).initCause(e);
054            }
055        }
056    
057        public OutputStream getOutputStream() throws IOException {
058            throw new UnknownServiceException();
059        }
060    
061        public String getContentType() {
062            try {
063                return part.getContentType();
064            } catch (MessagingException e) {
065                return null;
066            }
067        }
068    
069        public String getName() {
070            return "";
071        }
072    
073        public synchronized MessageContext getMessageContext() {
074            return new MessageContext(part);
075        }
076    }