Skip to content

Commit

Permalink
#172 pre-calculate transformer
Browse files Browse the repository at this point in the history
  • Loading branch information
yegor256 committed Aug 25, 2022
1 parent ec692e1 commit 9ffcc70
Showing 1 changed file with 30 additions and 19 deletions.
49 changes: 30 additions & 19 deletions src/main/java/com/jcabi/xml/XSLDocument.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
Expand Down Expand Up @@ -139,6 +140,13 @@ public final class XSLDocument implements XSL {
*/
private final transient String sid;

/**
* Cached transformer.
* @since 0.26
*/
private final transient AtomicReference<Transformer> cached =
new AtomicReference<>();

/**
* Public ctor, from XML as a source.
* @param src XSL document body
Expand Down Expand Up @@ -417,27 +425,30 @@ private void transformInto(final XML xml, final Result result) {
* @return The transformer
*/
private Transformer transformer() {
final Transformer trans;
synchronized (XSLDocument.TFACTORY) {
XSLDocument.TFACTORY.setURIResolver(this.sources);
try {
trans = XSLDocument.TFACTORY.newTransformer(
new StreamSource(new StringReader(this.xsl), this.sid)
);
} catch (final TransformerConfigurationException ex) {
throw new IllegalArgumentException(
String.format(
"Failed to create transformer by %s",
XSLDocument.TFACTORY.getClass().getName()
),
ex
);
if (this.cached.get() == null) {
final Transformer trans;
synchronized (XSLDocument.TFACTORY) {
XSLDocument.TFACTORY.setURIResolver(this.sources);
try {
trans = XSLDocument.TFACTORY.newTransformer(
new StreamSource(new StringReader(this.xsl), this.sid)
);
} catch (final TransformerConfigurationException ex) {
throw new IllegalArgumentException(
String.format(
"Failed to create transformer by %s",
XSLDocument.TFACTORY.getClass().getName()
),
ex
);
}
}
for (final Map.Entry<String, Object> ent : this.params.entrySet()) {
trans.setParameter(ent.getKey(), ent.getValue());
}
this.cached.set(XSLDocument.forSaxon(trans));
}
for (final Map.Entry<String, Object> ent : this.params.entrySet()) {
trans.setParameter(ent.getKey(), ent.getValue());
}
return XSLDocument.forSaxon(trans);
return this.cached.get();
}

/**
Expand Down

0 comments on commit 9ffcc70

Please sign in to comment.