Skip to content

Commit 298396c

Browse files
Optimise performance by instantiating context only once
1 parent 727ce56 commit 298396c

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

application/src/ext/java/org/opentripplanner/ext/ojp/trias/OjpToTriasTransformer.java

+12-5
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ class OjpToTriasTransformer {
2929
"trias_to_ojp2.0_request.xslt"
3030
);
3131

32+
private static final JAXBContext CONTEXT = jaxbContext();
33+
3234
static String transform(OJP ojp) {
3335
var writer = new StringWriter();
3436
transform(ojp, writer);
@@ -37,8 +39,7 @@ static String transform(OJP ojp) {
3739

3840
static void transform(OJP ojp, Writer writer) {
3941
try {
40-
var context = JAXBContext.newInstance(OJP.class);
41-
var marshaller = context.createMarshaller();
42+
var marshaller = CONTEXT.createMarshaller();
4243

4344
// Convert Java object to XML string
4445
var outputStream = new ByteArrayOutputStream();
@@ -53,8 +54,6 @@ static void transform(OJP ojp, Writer writer) {
5354
}
5455

5556
static OJP triasToOjp(String trias) throws JAXBException, TransformerException {
56-
var context = JAXBContext.newInstance(OJP.class);
57-
5857
var xmlSource = new StreamSource(
5958
new ByteArrayInputStream(trias.getBytes(StandardCharsets.UTF_8))
6059
);
@@ -64,7 +63,7 @@ static OJP triasToOjp(String trias) throws JAXBException, TransformerException {
6463
transformer.transform(xmlSource, new StreamResult(writer));
6564
var transformedXml = writer.toString(StandardCharsets.UTF_8);
6665

67-
var unmarshaller = context.createUnmarshaller();
66+
var unmarshaller = CONTEXT.createUnmarshaller();
6867
return (OJP) unmarshaller.unmarshal(
6968
new ByteArrayInputStream(transformedXml.getBytes(StandardCharsets.UTF_8))
7069
);
@@ -87,4 +86,12 @@ static Templates loadTemplate(String name) {
8786
throw new RuntimeException(e);
8887
}
8988
}
89+
90+
private static JAXBContext jaxbContext() {
91+
try {
92+
return JAXBContext.newInstance(OJP.class);
93+
} catch (JAXBException e) {
94+
throw new RuntimeException(e);
95+
}
96+
}
9097
}

0 commit comments

Comments
 (0)