Skip to content

Commit 59ee845

Browse files
authored
Apply XSLT Templates caching optimization from PR #1231
1 parent 243cdcf commit 59ee845

1 file changed

Lines changed: 26 additions & 3 deletions

File tree

src/main/java/org/quickfixj/codegenerator/MessageCodeGenerator.java

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import javax.xml.parsers.DocumentBuilder;
2828
import javax.xml.parsers.DocumentBuilderFactory;
2929
import javax.xml.parsers.ParserConfigurationException;
30+
import javax.xml.transform.Templates;
3031
import javax.xml.transform.Transformer;
3132
import javax.xml.transform.TransformerConfigurationException;
3233
import javax.xml.transform.TransformerException;
@@ -50,6 +51,7 @@
5051
import java.util.List;
5152
import java.util.Map;
5253
import java.util.Set;
54+
import java.util.concurrent.ConcurrentHashMap;
5355

5456
import javax.xml.XMLConstants;
5557

@@ -220,18 +222,39 @@ private void generateComponentClasses(Task task) throws ParserConfigurationExcep
220222
}
221223
}
222224

225+
private final TransformerFactory transformerFactory = new net.sf.saxon.TransformerFactoryImpl();
226+
227+
private final Map<String, Templates> templatesCache = new ConcurrentHashMap<>();
228+
223229
private Transformer createTransformer(Task task, String xsltFile)
224230
throws TransformerFactoryConfigurationError, TransformerConfigurationException {
225-
StreamSource styleSource;
231+
final String cacheKey;
232+
final StreamSource styleSource;
226233
File xslt = new File(task.getTransformDirectory() + "/" + xsltFile);
227234
if (xslt.exists()) {
235+
cacheKey = xslt.getAbsolutePath();
228236
styleSource = new StreamSource(xslt);
229237
} else {
230238
logInfo("Loading predefined xslt file:" + xsltFile);
239+
cacheKey = "classpath:" + xsltFile;
231240
styleSource = new StreamSource(this.getClass().getResourceAsStream(xsltFile));
232241
}
233-
TransformerFactory transformerFactory = new net.sf.saxon.TransformerFactoryImpl();
234-
return transformerFactory.newTransformer(styleSource);
242+
243+
try {
244+
Templates templates = templatesCache.computeIfAbsent(cacheKey, k -> {
245+
try {
246+
return transformerFactory.newTemplates(styleSource);
247+
} catch (TransformerConfigurationException e) {
248+
throw new CodeGenerationException(e);
249+
}
250+
});
251+
return templates.newTransformer();
252+
} catch (CodeGenerationException e) {
253+
if (e.getCause() instanceof TransformerConfigurationException) {
254+
throw (TransformerConfigurationException) e.getCause();
255+
}
256+
throw e;
257+
}
235258
}
236259

237260
private final Map<String, Document> specificationCache = new HashMap<>();

0 commit comments

Comments
 (0)