/*
 * @(#)URLConnectionRecognizer.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 java.net.*;

/**
 * This content type detector uses
 * java.net.URLConnection#guessContentTypeFromStream()
 * to determine the type of data.
 *
 * @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 URLConnectionRecognizer
implements Recognizer {
    /**
     * Return the number of bytes needed to
     * determine the content type.
     */
    public int getMinimalDeterminableDataLength() {
        return 10;
    }
    
    /**
     * Return the base MIME Type of this data. This method is
     * expected to ALWAYS return a valid (non-null) MIME Type.
     *
     * @param  dataSnippet the first few bytes of the data file.
     * @return MIME Type or 'content/unknown' if content type
     * can not be determined.
     */
    public String getContentType(byte[] dataSnippet) {
        String contentType = null;
        try  {
            ByteArrayInputStream stream = new ByteArrayInputStream(dataSnippet);
            contentType = URLConnection.guessContentTypeFromStream(stream);
        } catch (IOException e) {
        } finally {
            if (contentType == null) {
                contentType = Recognizer.CONTENT_TYPE_OCTET_STREAM;
            }
        }
        return contentType;
    }
}
