View Javadoc

1   package pl.psnc.dl.ege.webapp.config;
2   
3   import java.io.File;
4   import java.io.FileInputStream;
5   import java.util.HashMap;
6   import java.util.Map;
7   
8   import org.xml.sax.Attributes;
9   import org.xml.sax.InputSource;
10  import org.xml.sax.SAXException;
11  import org.xml.sax.XMLReader;
12  import org.xml.sax.helpers.DefaultHandler;
13  import org.xml.sax.helpers.XMLReaderFactory;
14  
15  /**
16   * Provides mime to file extension map.
17   * Map parameters are read from .xml configuration file.
18   * 
19   * @author mariuszs
20   *
21   */
22  public final class MimeExtensionProvider extends DefaultHandler
23  {
24  	private static MimeExtensionProvider instance = null;
25  	
26  	private static final Map<String,String> MIME_EXT_MAP = new HashMap<String,String>();
27  	
28  	private MimeExtensionProvider(String configFile){
29  		try{
30  			XMLReader xmlReader = XMLReaderFactory.createXMLReader();
31  			xmlReader.setContentHandler(this);
32  			xmlReader.parse(new InputSource(new FileInputStream(new File(configFile))));
33  		}catch(Throwable e){
34  			throw new RuntimeException(e.getMessage());
35  		}
36  	}
37  	
38  	public static MimeExtensionProvider getInstance(String configPath){
39  		if(instance == null){
40  			return new MimeExtensionProvider(configPath);
41  		}
42  		return instance;
43  	}
44  	
45  	@Override
46  	public void startElement(String uri, String localName, String name,
47  			Attributes attributes)
48  		throws SAXException
49  	{
50  		String mime = attributes.getValue("mime");
51  		String fileExt = attributes.getValue("ext");
52  		MIME_EXT_MAP.put(mime, fileExt);
53  	}
54  	
55  	public String getFileExtension(String mimeType){
56  		String response = MIME_EXT_MAP.get(mimeType);
57  		if(response == null){
58  			return "";
59  		}
60  		return response;
61  	}
62  }