-
Notifications
You must be signed in to change notification settings - Fork 1
/
TranslatorImpl.java
320 lines (290 loc) · 14.2 KB
/
TranslatorImpl.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
/*
* Copyright (C) 2013 Max Planck Institute for Psycholinguistics
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package nl.mpi.translation.tools;
import com.google.common.base.Strings;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import net.sf.saxon.Configuration;
import net.sf.saxon.TransformerFactoryImpl;
import nl.mpi.translation.tools.util.TranslationServiceErrorListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implemenation of Rest translation library to convert CMDI into IMDI and
* vice-versa.
* <br/><br/>
* This class uses STAx for parsing the input document and Saxon as XSLT
* processor. The transformer for the underlying XSLT stylesheet is cached in a
* Template object.<br/>
* Saxon is used to provide an XSLT 2.0 implementation.
*
* @author andmor <andre.moreira@mpi.nl>
* @author Twan Goosen <twan.goosen@mpi.nl>
*
*/
public class TranslatorImpl implements Translator {
private final static Logger logger = LoggerFactory.getLogger(TranslatorImpl.class);
private final static String SAXON_TRANSFORMER_IMPL_CLASS_NAME = "net.sf.saxon.TransformerFactoryImpl";
private final static String SAXON_MESSAGE_EMITTER_CLASSNAME = "net.sf.saxon.serialize.MessageWarner";
private final static URL DEFAULT_CMDI2IMDI_XSLT = TranslatorImpl.class.getClassLoader().getResource("templates/cmdi2imdi/cmdi2imdiMaster.xslt");
private final static URL DEFAULT_IMDI2CMDI_XSLT = TranslatorImpl.class.getClassLoader().getResource("templates/imdi2cmdi/imdi2cmdi.xslt");
private final static Pattern CMDI_URL_PATTERN = Pattern.compile("^.*\\.cmdi(\\?.*)?$", Pattern.CASE_INSENSITIVE);
private final static Pattern IMDI_URL_PATTERN = Pattern.compile("^.*\\.imdi(\\?.*)?$", Pattern.CASE_INSENSITIVE);
private final TransformerFactory transfFactory;
private final XMLInputFactory xmlInputFactory;
private final Templates cmdi2imdiCachedXSLT;
private final Templates imdi2cmdiCachedXSLT;
private Map<String, Object> transformationParameters;
private final UrlStreamResolver urlStreamResolver;
public TranslatorImpl(UrlStreamResolver urlStreamResolver) throws TransformerConfigurationException, IOException {
this(DEFAULT_IMDI2CMDI_XSLT, DEFAULT_CMDI2IMDI_XSLT, urlStreamResolver);
}
/**
*
* @param imdi2cmdiXsltPath path to local file location of the IMDI to CMDI
* transformation stylesheet (null to use default)
* @param cmdi2imdiXsltPath path to local file location of the CMDI to IMDI
* transformation stylesheet (null to use default)
* @param urlStreamResolver
* @throws MalformedURLException
* @throws TransformerConfigurationException
* @throws IOException
*/
public TranslatorImpl(String imdi2cmdiXsltPath, String cmdi2imdiXsltPath, UrlStreamResolver urlStreamResolver) throws MalformedURLException, TransformerConfigurationException, IOException {
this(
(Strings.isNullOrEmpty(imdi2cmdiXsltPath) ? DEFAULT_IMDI2CMDI_XSLT : new File(imdi2cmdiXsltPath).toURI().toURL()),
(Strings.isNullOrEmpty(cmdi2imdiXsltPath) ? DEFAULT_CMDI2IMDI_XSLT : new File(cmdi2imdiXsltPath).toURI().toURL()),
urlStreamResolver);
}
/**
* Initializes the translator with the specified stylesheets
*
* @param imdi2CmdiXsltLocation location of the IMDI to CMDI transformation
* stylesheet (cannot be null)
* @param cmdi2ImdiXsltLocation location of the CMDI to IMDI transformation
* stylesheet (cannot be null)
* @throws TransformerConfigurationException
* @throws IOException
*/
public TranslatorImpl(final URL imdi2CmdiXsltLocation, final URL cmdi2ImdiXsltLocation, UrlStreamResolver urlStreamResolver) throws TransformerConfigurationException, IOException {
this.urlStreamResolver = urlStreamResolver;
transfFactory = createTransformerFactory();
transfFactory.setErrorListener(new TranslationServiceErrorListener(logger));
logger.debug("Instantiated XML transformer factory of type {}", transfFactory.getClass());
if (transfFactory instanceof TransformerFactoryImpl) {
logger.debug("Telling Saxon to send messages as warnings to logger");
final Configuration tfConfig = ((TransformerFactoryImpl) transfFactory).getConfiguration();
tfConfig.setMessageEmitterClass(SAXON_MESSAGE_EMITTER_CLASSNAME);
}
xmlInputFactory = XMLInputFactory.newInstance();
logger.debug("Instantiated XML input factory of type {}", xmlInputFactory.getClass());
cmdi2imdiCachedXSLT = initTemplates(cmdi2ImdiXsltLocation);
imdi2cmdiCachedXSLT = initTemplates(imdi2CmdiXsltLocation);
logger.info("Translator initialized");
logger.debug("Using XSLT Transformer: '{}'", cmdi2imdiCachedXSLT.getClass());
logger.info("Using CMDI2IMDI stylesheet: '{}'", cmdi2ImdiXsltLocation);
logger.info("Using IMDI2CMDI stylesheet: '{}'", imdi2CmdiXsltLocation);
}
private Templates initTemplates(URL xsltURL) throws FileNotFoundException, TransformerConfigurationException, IOException {
if (xsltURL == null) {
throw new FileNotFoundException("CMDI2IMDI stylesheet: '" + xsltURL
+ "' (no such file or directory)");
}
//Create a source with the stylesheet
final Source sourceXSLT = new StreamSource(xsltURL.openStream(), xsltURL.toExternalForm());
//Create a cached transformer
return transfFactory.newTemplates(sourceXSLT);
}
/**
* Creates a new transformer factory, using Saxon as the preferred
* implementation. Falls back to the default procedure through
* {@link TransformerFactory#newInstance()}.
*
* @return an implementation instance of TransformerFactory, never null
* @throws TransformerFactoryConfigurationError as thrown by {@link TransformerFactory#newInstance()
* } in case the Saxon implementation cannot be instantiated
*/
private TransformerFactory createTransformerFactory() throws TransformerFactoryConfigurationError {
try {
// Try Saxon first:
logger.debug("Trying to get instance of '{}' transformer implementation", SAXON_TRANSFORMER_IMPL_CLASS_NAME);
return TransformerFactory.newInstance(SAXON_TRANSFORMER_IMPL_CLASS_NAME, null);
} catch (TransformerFactoryConfigurationError tfc) {
// Backup plan: use whatever is available to Java through the default procedure
logger.warn("Could not load class for Saxon transformer, trying default as backup. This will probably lead to runtime errors!");
logger.debug("javax.xml.transform.TransformerFactory={}", System.getProperty("javax.xml.transform.TransformerFactory"));
logger.debug("Exception thrown by TransformerFactory.newInstance()", tfc);
return TransformerFactory.newInstance();
}
}
/**
* This method reads an CMDI XML document form the supplied URL and returns
* it converted to IMDI. If the input document specified by
* <b>cmdiFileURL</b> has <i>.imdi</i> extension, the original file is
* returned.
*
* @param cmdiFileURL - The URL pointing to the CMDI file to convert.
* @param serviceURI
* @return IMDI file converted from CMDI.
* @throws TransformerException
* @throws XMLStreamException
* @throws IOException
*/
@Override
public String getIMDI(URL cmdiFileURL, String serviceURI) throws TransformerException, XMLStreamException, IOException {
//set up input
final InputStream input = urlStreamResolver.getStream(cmdiFileURL);
try {
final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(input, "UTF-8");
try {
final Source source = new StAXSource(xmlStreamReader);
//set up output
final StringWriter sw = new StringWriter();
final Result result = new StreamResult(sw);
final String inputUrl = cmdiFileURL.toString();
//return the original document for documents already with imdi extension.
if (isImdiURl(inputUrl)) {
logger.warn("Input document seems to be already IMDI! Returning original document.");
writeURLContentsToStream(cmdiFileURL, sw);
} else {
if (!isCmdiUrl(inputUrl)) {
logger.info("Input document language could not be confirmed! CMDI assumed.");
}
//translate document
transform(cmdi2imdiCachedXSLT, source, result, serviceURI, inputUrl);
}
sw.flush();
return sw.toString();
} finally {
xmlStreamReader.close();
}
} finally {
input.close();
}
}
/**
* This method reads an IMDI XML document form the supplied URL and returns
* it converted to CMDI. If the input document specified by
* <b>imdiFileURL</b> has <i>.cmdi</i> extension, the original file is
* returned.
*
* @param imdiFileURL - The URL pointing to the IMDI file to convert.
* @param serviceURI
* @return CMDI file converted from IMDI.
* @throws TransformerException
* @throws XMLStreamException
* @throws IOException
*/
@Override
public String getCMDI(URL imdiFileURL, String serviceURI) throws TransformerException, XMLStreamException, IOException {
//set up input
final InputStream input = urlStreamResolver.getStream(imdiFileURL);
try {
XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(input, "UTF-8");
try {
final Source source = new StAXSource(xmlStreamReader);
//set up output
final StringWriter sw = new StringWriter();
final Result result = new StreamResult(sw);
final String inputUrl = imdiFileURL.toString();
//return the original document for documents already with cmdi extension.
if (isCmdiUrl(inputUrl)) {
logger.warn("Input document seems to be already CMDI! Returning original document.");
writeURLContentsToStream(imdiFileURL, sw);
} else {
if (!isImdiURl(inputUrl)) {
logger.info("Input document language could not be confirmed! IMDI assumed.");
}
transform(imdi2cmdiCachedXSLT, source, result, serviceURI, inputUrl);
}
sw.flush();
return sw.toString();
} finally {
xmlStreamReader.close();
}
} finally {
input.close();
}
}
private void transform(final Templates templates, final Source source, final Result result, String serviceURI, final String inputUrl) throws TransformerException, TransformerConfigurationException {
final Transformer transformer = templates.newTransformer();
if (serviceURI != null) {
transformer.setParameter("service-base-uri", serviceURI);
}
if (inputUrl != null) {
transformer.setParameter("source-location", inputUrl);
}
if (transformationParameters != null) {
for (Entry<String, Object> param : transformationParameters.entrySet()) {
logger.trace("Setting additional transformation parameter: {} = '{}'", param.getKey(), param.getValue());
transformer.setParameter(param.getKey(), param.getValue());
}
}
transformer.transform(source, result);
}
private void writeURLContentsToStream(URL cmdiFileURL, StringWriter sw) throws IOException {
final InputStream urlInputStream = cmdiFileURL.openConnection().getInputStream();
try {
final BufferedReader rd = new BufferedReader(new InputStreamReader(urlInputStream, "UTF-8"));
try {
String line;
while ((line = rd.readLine()) != null) {
sw.write(line);
}
} finally {
rd.close();
}
} finally {
urlInputStream.close();
}
}
@Override
public void setTransformationParameters(Map<String, Object> params) {
this.transformationParameters = params;
}
private static boolean isCmdiUrl(String cmdiFileURL) {
return CMDI_URL_PATTERN.matcher(cmdiFileURL).matches();
}
private static boolean isImdiURl(String imdiFileURL) {
return IMDI_URL_PATTERN.matcher(imdiFileURL).matches();
}
}