001package org.kuali.common.util.properties.rice; 002 003import static com.google.common.base.Preconditions.checkNotNull; 004 005import java.io.File; 006import java.io.IOException; 007import java.io.InputStream; 008import java.util.Properties; 009 010import javax.xml.bind.JAXBContext; 011import javax.xml.bind.JAXBException; 012import javax.xml.bind.Unmarshaller; 013import javax.xml.bind.UnmarshallerHandler; 014import javax.xml.parsers.ParserConfigurationException; 015import javax.xml.parsers.SAXParser; 016import javax.xml.parsers.SAXParserFactory; 017 018import org.apache.commons.io.IOUtils; 019import org.kuali.common.util.LocationUtils; 020import org.xml.sax.InputSource; 021import org.xml.sax.SAXException; 022import org.xml.sax.XMLReader; 023 024public class RiceLoader { 025 026 public static Properties load(File file) { 027 checkNotNull(file, "'file' cannot be null"); 028 return load(file.getAbsolutePath()); 029 } 030 031 public static Properties load(String location) { 032 checkNotNull(location, "'location' cannot be null"); 033 Config config = getConfig(location); 034 return convert(config); 035 } 036 037 protected static Properties convert(Config config) { 038 checkNotNull(config, "'config' cannot be null"); 039 checkNotNull(config.getParams(), "'params' cannot be null"); 040 Properties properties = new Properties(); 041 for (Param param : config.getParams()) { 042 String key = param.getName(); 043 String val = param.getValue(); 044 properties.setProperty(key, val); 045 } 046 return properties; 047 } 048 049 protected static Config getConfig(String location) { 050 InputStream in = null; 051 try { 052 in = LocationUtils.getInputStream(location); 053 return unmarshal(Config.class, in); 054 } catch (IOException e) { 055 throw new IllegalStateException(String.format("unexpected io error -> [%s]", location)); 056 } finally { 057 IOUtils.closeQuietly(in); 058 } 059 } 060 061 @SuppressWarnings("unchecked") 062 protected static <T> T unmarshal(Class<T> type, InputStream in) throws IOException { 063 try { 064 JAXBContext context = JAXBContext.newInstance(type); 065 Unmarshaller unmarshaller = context.createUnmarshaller(); 066 UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler(); 067 SAXParserFactory spf = SAXParserFactory.newInstance(); 068 SAXParser sp = spf.newSAXParser(); 069 XMLReader xr = sp.getXMLReader(); 070 xr.setContentHandler(unmarshallerHandler); 071 InputSource xmlSource = new InputSource(in); 072 xr.parse(xmlSource); 073 return (T) unmarshallerHandler.getResult(); 074 } catch (SAXException e) { 075 throw new IllegalStateException("Unexpected SAX error", e); 076 } catch (ParserConfigurationException e) { 077 throw new IllegalStateException("Unexpected parser configuration error", e); 078 } catch (JAXBException e) { 079 throw new IllegalStateException("Unexpected JAXB error", e); 080 } 081 } 082 083}