Java JAXB Unmarshaller

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

import java.io.IOException;
  
import java.io.InputStream;

import javax.xml.bind.JAXBContext;
  
import javax.xml.bind.JAXBElement;
  
import javax.xml.bind.Unmarshaller;
  
import javax.xml.parsers.DocumentBuilder;
  
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.context.support.GenericApplicationContext;
  
import org.w3c.dom.Document;

public class ConfigReader {
   
public final <T>T read(Class<T> t, String filePath) throws ISException {
   
InputStream input;
   
try {
   
input = new GenericApplicationContext()
   
.getResource(filePath).getInputStream();
   
} catch (IOException e) {
   
throw new ISException(e);
   
}
   
return read(input, t);
   
}

public final <T>T read(InputStream inputStream, Class<T> t) throws ISException {
   
T root = null;
   
synchronized (this) {
   
try {
   
if (inputStream != null) {
   
final DocumentBuilderFactory dbf = DocumentBuilderFactory
   
.newInstance();
   
dbf.setNamespaceAware(true);
   
final JAXBContext context = JAXBContext.newInstance(t);
   
final Unmarshaller unmarshaller = context
   
.createUnmarshaller();
   
final DocumentBuilder documentBuilder = dbf
   
.newDocumentBuilder();
   
final Document doc = documentBuilder.parse(inputStream);

final JAXBElement<T> rootElement = unmarshaller.unmarshal(
   
doc, t);

root = rootElement.getValue();
   
}
   
} catch (Exception e) {
   
throw new ISException(e);
   
}
   
}
   
return root;
   
}
  
}