1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.jboss.as.quickstart.cdi.extension;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.util.logging.Logger;
22
23 import javax.enterprise.event.Observes;
24 import javax.enterprise.inject.spi.Extension;
25 import javax.enterprise.inject.spi.ProcessInjectionTarget;
26 import javax.xml.parsers.DocumentBuilder;
27 import javax.xml.parsers.DocumentBuilderFactory;
28 import javax.xml.parsers.ParserConfigurationException;
29
30 import org.jboss.as.quickstart.cdi.extension.model.Creature;
31 import org.w3c.dom.Document;
32 import org.w3c.dom.Element;
33 import org.xml.sax.SAXException;
34
35
36
37
38 public class CreatureExtension implements Extension {
39 private final Document document;
40 private final Logger log = Logger.getLogger(CreatureExtension.class.getName());
41
42 public CreatureExtension() {
43 try {
44 InputStream creatureDefs = CreatureExtension.class.getClassLoader().getResourceAsStream("creatures.xml");
45 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
46 DocumentBuilder builder = factory.newDocumentBuilder();
47 document = builder.parse(creatureDefs);
48 } catch (ParserConfigurationException e) {
49 throw new RuntimeException("Error building xml parser, aborting", e);
50 } catch (SAXException e) {
51 throw new RuntimeException("SAX exception while parsing xml file", e);
52 } catch (IOException e) {
53 throw new RuntimeException("Error reading or parsing xml file", e);
54 }
55 }
56
57
58
59
60
61
62 <X extends Creature> void processInjectionTarget(@Observes ProcessInjectionTarget<X> pit) {
63 Class<? extends Creature> klass = pit.getAnnotatedType().getJavaClass();
64 log.info("Setting up injection target for " + klass);
65 final Element entry = (Element) document.getElementsByTagName(klass.getSimpleName().toLowerCase()).item(0);
66 pit.setInjectionTarget(new XmlBackedWrappedInjectionTarget<X>(pit.getInjectionTarget(), entry));
67 }
68 }