/*
 * @(#)RecognizerFileTypeMap.java  1.1  2002-02-12
 *
 * Copyright (c) 1999 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.io.*;
import javax.activation.*;

/**
 * This file data source uses a Recognizer to
 * determine the content type of the file.
 *
 * @author  Werner Randelshofer, Hausmatt 10, CH-6405 Immensee, Switzerland.
 * @version 1.1 2002-02-12 Return 'application/octet-stream'
 * when file type can not be determined.
 * <br>1.0  1999-10-19
 */
public class RecognizerFileTypeMap
        extends FileTypeMap {

    private Recognizer detector;

    /**
     * Creates a new instance
     * No Recognizer will be used to determine the
     * content type of the file (#getContentType will always
     * return 'application/octet-stream'.
     */
    public RecognizerFileTypeMap() {
    }

    /**
     * Creates a new instance.
     * The specified Recognizer will be used to determine the
     * content type of the file.
     */
    public RecognizerFileTypeMap(Recognizer detector) {
        this.detector = detector;
    }

    /**
     * Sets the Recognizer that will be
     * used for determining the content type of the file.
     */
    public void setRecognizer(Recognizer detector) {
        this.detector = detector;
    }

    /**
     * Returns the Recognizer that will be
     * used for determining the content type of the file.
     */
    public Recognizer getRecognizer() {
        return detector;
    }

    /**
     * Return the base MIME Type of this data. This method is
     * expected to ALWAYS return a valid (non-null) MIME Type.
     *
     * @return MIME Type or 'application/octet-stream' if content type
     * can not be determined.
     */
    @Override
    public String getContentType(File file) {
        Recognizer d = getRecognizer();
        String contentType = Recognizer.CONTENT_TYPE_OCTET_STREAM;
        if (d == null) {
            return contentType;
        }
        try {
            InputStream in = new FileInputStream(file);
            try {
                byte[] snippet = new byte[d.getMinimalDeterminableDataLength()];
                in.read(snippet);
                contentType = d.getContentType(snippet);
            } finally {
                in.close();
            }
        } catch (IOException e) {
        }
        return contentType;
    }

    /**
     * Return the base MIME Type of this data. This method is
     * expected to ALWAYS return a valid (non-null) MIME Type.
     *
     * @return MIME Type or 'application/octet-stream' if content type
     * can not be determined.
     */
    public String getContentType(String filename) {
        return getContentType(new File(filename));
    }
}
