/*
 * @(#)FileTypeMappedURLDataSource.java  1.0  2002-02-12
 *
 * Copyright (c) 2002 Werner Randelshofer, Immensee, Switzerland.
 * All rights reserved.
 *
 * You may not use, copy or modify this file, except in compliance with the
 * license agreement you entered into with Werner Randelshofer.
 * For details see accompanying license terms.
 */

package ch.randelshofer.activation;

import java.net.*;
import javax.activation.*;

/**
 * An extension to URLDataSource which tries to guess the content
 * type of the URL by using the default FileTypeMap when the URLConnection
 * returns 'content/unknown' or 'application/octet-stream'.
 *
 * @author  Werner Randelshofer
 * @version 1.0 2002-02-12
 */
public class FileTypeMappedURLDataSource extends javax.activation.URLDataSource {
    
    /**
     * FileTypeMappedURLDataSource constructor.
     * <p>
     * The FileTypedMappedURLDataSource class will not open a connection to
     * the URL until a method requiring it to do so is called.
     *
     * @param url The URL to be encapsulated in this object.
     */
    public FileTypeMappedURLDataSource(URL url) {
        super(url);
    }
    
    /**
     * Returns the value of the URL content-type header field.
     * It calls the URL's URLConnection.getContentType method
     * after retrieving a URLConnection object.
     * <p>
     * If this gives not a satisfactory result (either 'content/unknown'
     * or 'application/octet-stream') then this method uses the currently
     * installed FileTypeMap to guess the content type.
     *
     * @return The MIME type.
     */
    public String getContentType() {
        String type = super.getContentType();
        if (type.equals(Recognizer.CONTENT_TYPE_UNKNOWN)
        || type.equals(Recognizer.CONTENT_TYPE_OCTET_STREAM)) {
            return FileTypeMap.getDefaultFileTypeMap().getContentType(getURL().getFile());
        } else {
            return type;
        }
    }
           
}
