1 package org.kuali.common.util.properties.rice;
2
3 import static com.google.common.base.Preconditions.checkNotNull;
4
5 import java.io.File;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.util.Properties;
9
10 import javax.xml.bind.JAXBContext;
11 import javax.xml.bind.JAXBException;
12 import javax.xml.bind.Unmarshaller;
13 import javax.xml.bind.UnmarshallerHandler;
14 import javax.xml.parsers.ParserConfigurationException;
15 import javax.xml.parsers.SAXParser;
16 import javax.xml.parsers.SAXParserFactory;
17
18 import org.apache.commons.io.IOUtils;
19 import org.kuali.common.util.LocationUtils;
20 import org.xml.sax.InputSource;
21 import org.xml.sax.SAXException;
22 import org.xml.sax.XMLReader;
23
24 public class RiceLoader {
25
26 public static Properties load(File file) {
27 checkNotNull(file, "'file' cannot be null");
28 return load(file.getAbsolutePath());
29 }
30
31 public static Properties load(String location) {
32 checkNotNull(location, "'location' cannot be null");
33 Config config = getConfig(location);
34 return convert(config);
35 }
36
37 protected static Properties convert(Config config) {
38 checkNotNull(config, "'config' cannot be null");
39 checkNotNull(config.getParams(), "'params' cannot be null");
40 Properties properties = new Properties();
41 for (Param param : config.getParams()) {
42 String key = param.getName();
43 String val = param.getValue();
44 properties.setProperty(key, val);
45 }
46 return properties;
47 }
48
49 protected static Config getConfig(String location) {
50 InputStream in = null;
51 try {
52 in = LocationUtils.getInputStream(location);
53 return unmarshal(Config.class, in);
54 } catch (IOException e) {
55 throw new IllegalStateException(String.format("unexpected io error -> [%s]", location));
56 } finally {
57 IOUtils.closeQuietly(in);
58 }
59 }
60
61 @SuppressWarnings("unchecked")
62 protected static <T> T unmarshal(Class<T> type, InputStream in) throws IOException {
63 try {
64 JAXBContext context = JAXBContext.newInstance(type);
65 Unmarshaller unmarshaller = context.createUnmarshaller();
66 UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler();
67 SAXParserFactory spf = SAXParserFactory.newInstance();
68 SAXParser sp = spf.newSAXParser();
69 XMLReader xr = sp.getXMLReader();
70 xr.setContentHandler(unmarshallerHandler);
71 InputSource xmlSource = new InputSource(in);
72 xr.parse(xmlSource);
73 return (T) unmarshallerHandler.getResult();
74 } catch (SAXException e) {
75 throw new IllegalStateException("Unexpected SAX error", e);
76 } catch (ParserConfigurationException e) {
77 throw new IllegalStateException("Unexpected parser configuration error", e);
78 } catch (JAXBException e) {
79 throw new IllegalStateException("Unexpected JAXB error", e);
80 }
81 }
82
83 }