private static synchronized final HashMap < String , String > readExtensionMappings ( String mappingFile ) throws Exception { HashMap < String , String > extensionMappings = new HashMap < String , String > ( ) ; DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; Document doc = factory . newDocumentBuilder ( ) . parse ( new File ( mappingFile ) ) ; Element root = doc . getDocumentElement ( ) ; // "mime-mapping" elements are children of root NodeList mappingNodes = root . getChildNodes ( ) ; for ( int i = 0 ; i < mappingNodes . getLength ( ) ; i ++ ) { Node mappingNode = mappingNodes . item ( i ) ; // check it's a mime-mapping element if ( mappingNode . getNodeType ( ) == Node . ELEMENT_NODE && mappingNode . getNodeName ( ) . equals ( "mime-mapping" ) ) { // look for child elements "extension" and "mime-type" and get values from text nodes String extension = null ; String mimeType = null ; NodeList nl = mappingNode . getChildNodes ( ) ; for ( int j = 0 ; j < nl . getLength ( ) ; j ++ ) { Node n = nl . item ( j ) ; if ( n . getNodeType ( ) == Node . ELEMENT_NODE ) { // assuming here that extension and mime-type nodes only have text content (no attrs etc) if ( n . getNodeName ( ) . equals ( "extension" ) ) { extension = n . getFirstChild ( ) . getNodeValue ( ) ; } else { if ( n . getNodeName ( ) . equals ( "mime-type" ) ) { mimeType = n . getFirstChild ( ) . getNodeValue ( ) ; } } } } // if we've got an extension and mime-type, and it's not in the list, add it. if ( extension != null && mimeType != null ) { if ( ! extensionMappings . containsKey ( mimeType ) ) { extensionMappings . put ( mimeType , extension ) ; } else { logger . warn ( "Duplicate extension " + extension + " found for mime-type " + mimeType + " in " + mappingFile ) ; } } else { logger . warn ( "Element mime-mapping is missing child elements mime-type and/or extension in " + mappingFile ) ; } } } return extensionMappings ; }
Read the extensions mappings from config file