/*
 * @(#) $Id: CorrectedContentTypeDataSource.java,v 1.4 2001/03/04 13:32:56 shin Exp $
 * $Revision: 1.4 $
 * Copyright (c) 2000 Shin Kinoshita All Rights Reserved.
 */
package com.sk_jp.mail;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import javax.mail.Part;
import javax.mail.MessagingException;
import javax.mail.internet.ContentType;
import javax.mail.internet.ParseException;
import javax.activation.DataSource;

/**
 * Content-Type:の不適合をISO-2022-JPに補正します。
 * 使用方法は<PRE>
 * Object o = new DataHandler(
 *               new CorrectedContentTypeDataSource(part, charset)
 *            ).getContent();
 * </PRE><P>のようになります。</P><P>
 * スレッドセーフではありませんので利用者側で排他制御を行ってください。
 * </P>
 * @author Shin
 * @version $Revision: 1.4 $ $Date: 2001/03/04 13:32:56 $
 */
class CorrectedContentTypeDataSource implements DataSource {
    private DataSource source;
    private String charset;

    public CorrectedContentTypeDataSource() {}
    public CorrectedContentTypeDataSource(DataSource dataSource,
                                          String defaultCharset) {
        setDataSource(dataSource);
        setDefaultCharset(defaultCharset);
    }
    public CorrectedContentTypeDataSource(Part part,
                                          String defaultCharset)
                throws MessagingException {
        setPart(part);
        setDefaultCharset(defaultCharset);
    }

    public void setPart(Part part) throws MessagingException {
        // getDataHandler() method creates a implicit DataSource.
        setDataSource(part.getDataHandler().getDataSource());
    }
    public void setDataSource(DataSource newSource) {
        source = newSource;
    }
    public void setDefaultCharset(String defaultCharset) {
        charset = defaultCharset;
    }

    public String getContentType() {
        ContentType contentType = null;
        try {
            contentType = new ContentType(source.getContentType());
        } catch (ParseException e) {
            return "text/plain; charset=" + charset;
        }
        String specifiedCharset = contentType.getParameter("charset");
        if (specifiedCharset == null) {
            // Content-Type:が存在しない場合は"text/plain"になってしまう。
            // 本当にtext/plainだった場合は正しくない事になるが、
            // charset=ISO-2022-JPにする場合は一応表示上は問題ない。
            contentType.setParameter("charset", charset);
        }
        return contentType.toString();
    }

    public String getName() {
        return source.getName();
    }
    public InputStream getInputStream() throws IOException {
        return source.getInputStream();
    }
    public OutputStream getOutputStream() throws IOException {
        return source.getOutputStream();
    }
}

