001    /*
002     * JBoss DNA (http://www.jboss.org/dna)
003     * See the COPYRIGHT.txt file distributed with this work for information
004     * regarding copyright ownership.  Some portions may be licensed
005     * to Red Hat, Inc. under one or more contributor license agreements.
006     * See the AUTHORS.txt file in the distribution for a full listing of 
007     * individual contributors. 
008     *
009     * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
010     * is licensed to you under the terms of the GNU Lesser General Public License as
011     * published by the Free Software Foundation; either version 2.1 of
012     * the License, or (at your option) any later version.
013     *
014     * JBoss DNA is distributed in the hope that it will be useful,
015     * but WITHOUT ANY WARRANTY; without even the implied warranty of
016     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
017     * Lesser General Public License for more details.
018     *
019     * You should have received a copy of the GNU Lesser General Public
020     * License along with this software; if not, write to the Free
021     * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
022     * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
023     */
024    package org.jboss.dna.graph.mimetype;
025    
026    import java.io.IOException;
027    import java.io.InputStream;
028    import java.util.Collections;
029    import java.util.HashMap;
030    import java.util.Map;
031    import java.util.Properties;
032    import net.jcip.annotations.Immutable;
033    import org.jboss.dna.common.i18n.I18n;
034    import org.jboss.dna.common.util.Logger;
035    import org.jboss.dna.graph.GraphI18n;
036    
037    /**
038     * A {@link MimeTypeDetector} that attempts to match the extension of the supplied name against a set of known file extensions.
039     * 
040     * @author Randall Hauch
041     */
042    @Immutable
043    public class ExtensionBasedMimeTypeDetector implements MimeTypeDetector {
044    
045        /**
046         * The default location of the properties file containing the extension patterns to MIME types.
047         */
048        public static final String MIME_TYPE_EXTENSIONS_RESOURCE_PATH = "/org/jboss/dna/graph/MimeTypes.properties";
049    
050        /**
051         * The mapping of extension (which includes the leading '.') to MIME type.
052         */
053        private final Map<String, String> mimeTypesByExtension;
054    
055        /**
056         * Create a default instance of the extension-based MIME type detector. The set of extension patterns to MIME-types is loaded
057         * from "org.jboss.dna.graph.MimeTypes.properties".
058         */
059        public ExtensionBasedMimeTypeDetector() {
060            this(null, true);
061        }
062    
063        /**
064         * Create an instance of the extension-based MIME type detector by using the supplied mappings. The set of extension patterns
065         * to MIME-types is loaded from "org.jboss.dna.graph.MimeTypes.properties", but the supplied extension mappings override any
066         * default mappings.
067         * 
068         * @param extensionsToMimeTypes the mapping of extension patterns to MIME types, which will override the default mappings; may
069         *        be null if the default mappings are to be used
070         */
071        public ExtensionBasedMimeTypeDetector( Map<String, String> extensionsToMimeTypes ) {
072            this(extensionsToMimeTypes, true);
073        }
074    
075        /**
076         * Create an instance of the extension-based MIME type detector by using the supplied mappings. If requested, the set of
077         * extension patterns to MIME-types is loaded from "org.jboss.dna.graph.MimeTypes.properties" and any supplied extension
078         * mappings override any default mappings.
079         * 
080         * @param extensionsToMimeTypes the mapping of extension patterns to MIME types, which will override the default mappings; may
081         *        be null if the default mappings are to be used
082         * @param initWithDefaults true if the default mappings are to be loaded first
083         */
084        public ExtensionBasedMimeTypeDetector( Map<String, String> extensionsToMimeTypes,
085                                               boolean initWithDefaults ) {
086            Map<String, String> mappings = getDefaultMappings();
087            if (extensionsToMimeTypes != null) {
088                for (Map.Entry<String, String> entry : extensionsToMimeTypes.entrySet()) {
089                    String extensionString = entry.getKey();
090                    if (extensionString == null) continue;
091                    // Lowercase, trime, and remove all leading '.' characters ...
092                    extensionString = extensionString.toLowerCase().trim().replaceAll("^.+", "");
093                    if (extensionString.length() == 0) continue;
094                    String mimeType = entry.getValue();
095                    if (mimeType == null) continue;
096                    mimeType = entry.getValue().trim();
097                    if (mimeType.length() == 0) continue;
098                    assert extensionString.length() != 0;
099                    assert mimeType.length() != 0;
100                    mappings.put(extensionString, mimeType);
101                }
102            }
103            // Now put the mappings into the different maps ...
104            Map<String, String> mappingsByAnyCharExtension = new HashMap<String, String>();
105            for (Map.Entry<String, String> entry : mappings.entrySet()) {
106                String extensionString = entry.getKey();
107                String mimeType = entry.getValue();
108                assert extensionString != null;
109                assert extensionString.length() != 0;
110                assert mimeType != null;
111                assert mimeType.length() != 0;
112                mappingsByAnyCharExtension.put("." + extensionString, mimeType);
113            }
114            mimeTypesByExtension = Collections.unmodifiableMap(mappingsByAnyCharExtension);
115        }
116    
117        protected static Map<String, String> getDefaultMappings() {
118            Properties extensionsToMimeTypes = new Properties();
119            try {
120                extensionsToMimeTypes.load(ExtensionBasedMimeTypeDetector.class.getResourceAsStream(MIME_TYPE_EXTENSIONS_RESOURCE_PATH));
121            } catch (IOException e) {
122                I18n msg = GraphI18n.unableToAccessResourceFileFromClassLoader;
123                Logger.getLogger(ExtensionBasedMimeTypeDetector.class).warn(e, msg, MIME_TYPE_EXTENSIONS_RESOURCE_PATH);
124            }
125            Map<String, String> mimeTypesByExtension = new HashMap<String, String>();
126            for (Map.Entry<Object, Object> entry : extensionsToMimeTypes.entrySet()) {
127                String mimeType = entry.getKey().toString().trim();
128                String extensionStrings = entry.getValue().toString().toLowerCase().trim();
129                for (String extensionString : extensionStrings.split("\\s+")) {
130                    extensionString = extensionString.trim();
131                    if (extensionString.length() != 0) mimeTypesByExtension.put(extensionString, mimeType);
132                }
133            }
134            return mimeTypesByExtension;
135        }
136    
137        /**
138         * {@inheritDoc}
139         * 
140         * @see org.jboss.dna.graph.mimetype.MimeTypeDetector#mimeTypeOf(java.lang.String, java.io.InputStream)
141         */
142        public String mimeTypeOf( String name,
143                                  InputStream content ) {
144            if (name == null || name.length() == 0) return null;
145            String trimmedName = name.trim();
146            if (trimmedName.length() == 0) return null;
147    
148            // Find the extension ...
149            int indexOfDelimiter = trimmedName.lastIndexOf('.');
150            if (indexOfDelimiter < 1) return null;
151            String extension = trimmedName.substring(indexOfDelimiter).toLowerCase();
152    
153            // Look for a match ...
154            return mimeTypesByExtension.get(extension);
155        }
156    }