forked from dita-ot/dita-ot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXsltModule.java
380 lines (350 loc) · 12.8 KB
/
XsltModule.java
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
* This file is part of the DITA Open Toolkit project.
*
* Copyright 2013 Jarno Elovirta
*
* See the accompanying LICENSE file for applicable license.
*/
package org.dita.dost.module;
import static org.dita.dost.util.Constants.FILE_EXTENSION_TEMP;
import static org.dita.dost.util.FileUtils.replaceExtension;
import static org.dita.dost.util.LangUtils.pair;
import static org.dita.dost.util.XMLUtils.toErrorReporter;
import static org.dita.dost.util.XMLUtils.toMessageListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;
import net.sf.saxon.s9api.*;
import net.sf.saxon.trans.UncheckedXPathException;
import net.sf.saxon.trans.XPathException;
import org.apache.tools.ant.types.XMLCatalog;
import org.apache.tools.ant.util.FileNameMapper;
import org.dita.dost.exception.DITAOTException;
import org.dita.dost.exception.UncheckedDITAOTException;
import org.dita.dost.pipeline.AbstractPipelineInput;
import org.dita.dost.pipeline.AbstractPipelineOutput;
import org.dita.dost.util.CatalogUtils;
import org.dita.dost.util.ChainedURIResolver;
import org.dita.dost.util.Job;
import org.xmlresolver.Resolver;
/**
* XSLT processing module.
*
* <p>The module matches Ant's XSLT task with the following exceptions:</p>
* <ul>
* <li>If source and destination directories are same, transformation results are saved to a temporary file
* and the original source file is replaced after a successful transformation.</li>
* <li>If no {@code extension} attribute is set, the target file extension is the same as the source file extension.</li>
* </ul>
*
*/
public final class XsltModule extends AbstractPipelineModuleImpl {
private XsltExecutable templates;
private final Map<String, String> params = new HashMap<>();
private final Properties properties = new Properties();
private Source style;
private File in;
private File out;
private File destDir;
private File baseDir;
private Collection<File> includes;
private String filenameparameter;
private String filedirparameter;
private boolean reloadstylesheet;
private URIResolver catalog;
private URIResolver uriResolver;
private FileNameMapper mapper;
private String extension;
private XsltTransformer t;
private Processor processor;
private boolean parallel;
private void init() {
if (catalog == null) {
final Resolver catalogResolver = CatalogUtils.getCatalogResolver();
catalog = catalogResolver;
}
uriResolver = new ChainedURIResolver(job.getStore(), catalog);
if (fileInfoFilter != null) {
final Collection<Job.FileInfo> res = job.getFileInfo(fileInfoFilter);
includes = new ArrayList<>(res.size());
for (final Job.FileInfo f : res) {
includes.add(f.file);
}
baseDir = job.tempDir;
}
}
@Override
public AbstractPipelineOutput execute(AbstractPipelineInput input) throws DITAOTException {
init();
if ((includes == null || includes.isEmpty()) && (in == null)) {
return null;
}
if (destDir != null) {
logger.debug("Transforming into " + destDir.getAbsolutePath());
}
processor = xmlUtils.getProcessor();
final XsltCompiler xsltCompiler = processor.newXsltCompiler();
xsltCompiler.setURIResolver(uriResolver);
xsltCompiler.setErrorReporter(toErrorReporter(logger));
logger.info("Loading stylesheet " + style.getSystemId());
try {
templates = xsltCompiler.compile(style);
} catch (SaxonApiException e) {
throw new RuntimeException("Failed to compile stylesheet '" + style.getSystemId() + "': " + e.getMessage(), e);
}
if (in != null) {
transform(in, out);
} else if (parallel) {
try {
final List<Entry<File, File>> tmps = includes
.stream()
.parallel()
.map(include -> {
try {
final File in = baseDir.toPath().resolve(include.toPath()).toFile();
final File out = getOutput(include.getPath());
if (out == null) {
return null;
}
final XsltTransformer transformer = getTransformer();
if (in.equals(out)) {
final File tmp = new File(out.getAbsolutePath() + FILE_EXTENSION_TEMP);
transform(in, tmp, transformer);
return pair(tmp, out);
} else {
transform(in, out, transformer);
return null;
}
} catch (DITAOTException e) {
throw new UncheckedDITAOTException(e);
}
})
.filter(Objects::nonNull)
.toList();
for (Entry<File, File> entry : tmps) {
try {
logger.info("Move " + entry.getKey().toURI() + " to " + entry.getValue().toURI());
job.getStore().move(entry.getKey().toURI(), entry.getValue().toURI());
} catch (IOException e) {
logger.error(
String.format(
"Failed to move %s to %s: %s",
entry.getKey().toURI(),
entry.getValue().toURI(),
e.getMessage()
),
e
);
}
}
} catch (UncheckedDITAOTException e) {
throw e.getDITAOTException();
}
} else {
for (final File include : includes) {
final File in = new File(baseDir, include.getPath());
final File out = getOutput(include.getPath());
if (out == null) {
continue;
}
transform(in, out);
}
}
return null;
}
private File getOutput(final String path) {
File out = destDir.toPath().resolve(path).toFile();
if (mapper != null) {
final String[] outs = mapper.mapFileName(path);
if (outs == null) {
return null;
}
if (outs.length > 1) {
throw new RuntimeException("XSLT module only support one to one output mapping");
}
out = destDir.toPath().resolve(outs[0]).toFile();
} else if (extension != null) {
out = new File(replaceExtension(out.getAbsolutePath(), extension));
}
return out;
}
private XsltTransformer getTransformer() throws DITAOTException {
try {
XsltTransformer transformer = templates.load();
// final URIResolver resolver = Configuration.DEBUG
// ? new XMLUtils.DebugURIResolver(uriResolver)
// : uriResolver;
transformer.setErrorReporter(toErrorReporter(logger));
transformer.setURIResolver(uriResolver);
transformer.setMessageListener(toMessageListener(logger, processingMode));
return transformer;
} catch (final Exception e) {
throw new DITAOTException("Failed to create Transformer: " + e.getMessage(), e);
}
}
private void transform(final File in, final File out) throws DITAOTException {
if (reloadstylesheet || t == null) {
logger.info("Loading stylesheet " + style.getSystemId());
t = getTransformer();
}
transform(in, out, t);
}
private void transform(final File in, final File out, final XsltTransformer t) throws DITAOTException {
final boolean same = in.getAbsolutePath().equals(out.getAbsolutePath());
for (Entry<String, String> e : params.entrySet()) {
logger.debug("Set parameter " + e.getKey() + " to '" + e.getValue() + "'");
t.setParameter(new QName(e.getKey()), new XdmAtomicValue(e.getValue()));
}
if (filenameparameter != null) {
logger.debug("Set parameter " + filenameparameter + " to '" + in.getName() + "'");
t.setParameter(new QName(filenameparameter), new XdmAtomicValue(in.getName()));
}
if (filedirparameter != null) {
final Path rel = job.tempDir.toPath().relativize(in.getAbsoluteFile().toPath()).getParent();
final String v = rel != null ? rel.toString() : ".";
logger.debug("Set parameter " + filedirparameter + " to '" + v + "'");
t.setParameter(new QName(filedirparameter), new XdmAtomicValue(v));
}
if (properties.isEmpty()) {
try {
if (same) {
logger.info("Processing " + in.toURI());
job.getStore().transform(in.toURI(), t);
} else {
logger.info("Processing " + in.toURI() + " to " + out.toURI());
job.getStore().transform(in.toURI(), out.toURI(), t);
}
} catch (final UncheckedXPathException e) {
logger.error("Failed to transform document: " + e.getXPathException().getMessageAndLocation(), e);
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
logger.error("Failed to transform document: " + e.getMessage(), e);
}
return;
}
final File tmp = same ? new File(out.getAbsolutePath() + ".tmp" + Long.toString(System.currentTimeMillis())) : out;
if (same) {
logger.info("Processing " + in.toURI());
logger.debug("Processing " + in.toURI() + " to " + tmp.toURI());
} else {
logger.info("Processing " + in.toURI() + " to " + tmp.toURI());
}
Destination destination = null;
try {
final Source source = job.getStore().getSource(in.toURI());
t.setSource(source);
destination = job.getStore().getDestination(tmp.toURI());
if (same) {
destination.setDestinationBaseURI(out.toURI());
}
if (destination instanceof final Serializer serializer) {
for (final String key : properties.stringPropertyNames()) {
serializer.setOutputProperty(new QName(key), properties.getProperty(key));
}
}
t.setDestination(destination);
t.transform();
if (same) {
logger.debug("Moving " + tmp.getAbsolutePath() + " to " + out.getAbsolutePath());
job.getStore().move(tmp.toURI(), out.toURI());
}
} catch (final UncheckedXPathException e) {
logger.error("Failed to transform document: " + e.getXPathException().getMessageAndLocation(), e);
logger.debug("Remove " + tmp.toURI());
try {
job.getStore().delete(tmp.toURI());
} catch (final IOException e1) {
logger.error("Failed to clean up after failed transformation: " + e1, e1);
}
} catch (final RuntimeException e) {
throw e;
} catch (final SaxonApiException e) {
try {
throw e.getCause();
} catch (final XPathException cause) {
logger.error("Failed to transform document: " + cause.getMessageAndLocation(), e);
} catch (Throwable throwable) {
logger.error("Failed to transform document: " + e.getMessage(), e);
}
logger.debug("Remove " + tmp.toURI());
try {
job.getStore().delete(tmp.toURI());
} catch (final IOException e1) {
logger.error("Failed to clean up after failed transformation: " + e1, e1);
}
} catch (final Exception e) {
logger.error("Failed to transform document: " + e.getMessage(), e);
logger.debug("Remove " + tmp.toURI());
try {
job.getStore().delete(tmp.toURI());
} catch (final IOException e1) {
logger.error("Failed to clean up after failed transformation: " + e1, e1);
}
} finally {
try {
destination.close();
} catch (SaxonApiException e) {
throw new DITAOTException(e);
}
}
}
/**
* @deprecated use {@link #setStyle(Source)} instead
*/
@Deprecated
public void setStyle(final File style) {
this.style = new StreamSource(style);
}
public void setStyle(final Source style) {
this.style = style;
}
public void setParam(final String key, final String value) {
params.put(key, value);
}
public void setOutputProperty(final String name, final String value) {
properties.setProperty(name, value);
}
public void setIncludes(final Collection<File> includes) {
this.includes = includes;
}
public void setDestinationDir(final File destDir) {
this.destDir = destDir;
}
public void setSorceDir(final File baseDir) {
this.baseDir = baseDir;
}
public void setFilenameParam(final String filenameparameter) {
this.filenameparameter = filenameparameter;
}
public void setFiledirParam(final String filedirparameter) {
this.filedirparameter = filedirparameter;
}
public void setReloadstylesheet(final boolean reloadstylesheet) {
this.reloadstylesheet = reloadstylesheet;
}
public void setSource(final File in) {
this.in = in;
}
public void setResult(final File out) {
this.out = out;
}
public void setXMLCatalog(final XMLCatalog xmlcatalog) {
this.catalog = xmlcatalog;
}
public void setMapper(final FileNameMapper mapper) {
this.mapper = mapper;
}
public void setExtension(final String extension) {
this.extension = extension.startsWith(".") ? extension : ("." + extension);
}
public void setParallel(final boolean parallel) {
this.parallel = parallel;
}
}