-
Notifications
You must be signed in to change notification settings - Fork 34
/
XSDToJavaRunner.java
355 lines (318 loc) · 12.8 KB
/
XSDToJavaRunner.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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.maven_plugin;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElementRef;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.XMLFilterImpl;
import com.sun.codemodel.CodeWriter;
import com.sun.codemodel.JCodeModel;
import com.sun.istack.SAXParseException2;
import com.sun.tools.xjc.ErrorReceiver;
import com.sun.tools.xjc.Language;
import com.sun.tools.xjc.Options;
import com.sun.tools.xjc.api.SpecVersion;
import com.sun.tools.xjc.model.Model;
import com.sun.tools.xjc.outline.Outline;
import com.sun.tools.xjc.reader.internalizer.AbstractReferenceFinderImpl;
import com.sun.tools.xjc.reader.internalizer.DOMForest;
import com.sun.tools.xjc.reader.xmlschema.parser.XMLSchemaInternalizationLogic;
import org.apache.xml.resolver.CatalogManager;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.sonatype.plexus.build.incremental.BuildContext;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
/**
*
*/
public class XSDToJavaRunner {
static Class<?> modelLoaderClass;
final String[] args;
final List<String> cpList;
final XJCErrorListener listener;
final File xsdFile;
public XSDToJavaRunner(String[] args, XJCErrorListener listener,
File file, List<String> cp) {
this.args = args;
this.listener = listener;
this.xsdFile = file;
this.cpList = cp;
}
private static File getFile(String s) throws Exception {
File f = new File(s);
if (f.exists()) {
return f;
}
URI uri = new URI(s);
f = new File(uri);
return f;
}
public int run() throws Exception {
List<URL> urls = new ArrayList<URL>();
for (String s : cpList) {
File file = getFile(s);
urls.add(file.toURI().toURL());
}
final ClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls.size()]),
this.getClass().getClassLoader());
CatalogManager cm = new CatalogManager();
cm.setUseStaticCatalog(false);
cm.setIgnoreMissingProperties(true);
final CatalogResolver catResolver = new CatalogResolver(cm) {
public InputSource resolveEntity(String publicId, String systemId) {
String resolved = getResolvedEntity(publicId, systemId);
if (resolved == null) {
return null;
}
URL url;
InputSource iSource = new InputSource(resolved);
iSource.setPublicId(publicId);
try {
if (resolved.startsWith("classpath:")) {
resolved = resolved.substring("classpath:".length());
url = loader.getResource(resolved);
iSource.setSystemId(url.toExternalForm());
} else {
url = new URL(resolved);
}
InputStream iStream = url.openStream();
iSource.setByteStream(iStream);
//System.out.println("Resolved: " + publicId + " " + systemId + " " + url);
return iSource;
} catch (Exception e) {
listener.warning(xsdFile, e);
return null;
}
}
};
final Options opt = new Options() {
@Override
public void addCatalog(File catalogFile) throws IOException {
if (entityResolver == null) {
entityResolver = catResolver;
}
catResolver.getCatalog().parseCatalog(catalogFile.getPath());
}
};
if (checkXmlElementRef()) {
opt.target = SpecVersion.V2_1;
}
opt.setSchemaLanguage(Language.XMLSCHEMA);
opt.parseArguments(args);
Model model = loadModel(opt);
if (model == null) {
listener.message(xsdFile, "Failed to create model");
if (loader instanceof Closeable) {
((Closeable)loader).close();
}
return -1;
}
Outline outline = model.generateCode(opt, listener);
if (outline == null) {
listener.message(xsdFile, "Failed to generate code");
if (loader instanceof Closeable) {
((Closeable)loader).close();
}
return -1;
}
// then print them out
try {
CodeWriter cw = opt.createCodeWriter();
model.codeModel.build(cw);
} catch (IOException e) {
listener.error(e);
if (loader instanceof Closeable) {
((Closeable)loader).close();
}
return -1;
}
if (loader instanceof Closeable) {
((Closeable)loader).close();
}
return 0;
}
private synchronized Class<?> getModelLoaderClass() {
if (modelLoaderClass == null) {
try {
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("com.sun.tools.xjc.ModelLoader");
cc.setName("com.sun.tools.xjc.ModelLoader");
for (CtMethod m : cc.getMethods()) {
if (m.getName().equals("buildDOMForest")) {
m.insertBefore("$1 = new " + CustomizedLogic.class.getName() + "();");
}
}
modelLoaderClass = cc.toClass();
} catch (Throwable t) {
try {
modelLoaderClass = Class.forName("com.sun.tools.xjc.ModelLoader");
} catch (ClassNotFoundException e) {
//ignore
}
}
}
return modelLoaderClass;
}
private Model loadModel(Options opt) {
try {
return (Model)getModelLoaderClass()
.getMethod("load", Options.class, JCodeModel.class, ErrorReceiver.class)
.invoke(null, opt, new JCodeModel(), listener);
} catch (Exception e) {
listener.error("Failed to create model", e);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public static class CustomizedLogic extends XMLSchemaInternalizationLogic {
private static final class ReferenceFinder extends AbstractReferenceFinderImpl {
private Locator locator;
ReferenceFinder(DOMForest parent) {
super(parent);
}
@Override
public void setDocumentLocator(Locator l) {
super.setDocumentLocator(l);
locator = l;
}
@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
throws SAXException {
if (getContentHandler() != null) {
getContentHandler().startElement(namespaceURI, localName, qName, atts);
}
String relativeRef = findExternalResource(namespaceURI, localName, atts);
if (relativeRef == null) {
return; // not found
}
try {
// absolutize URL.
String lsi = locator.getSystemId();
String ref;
URI relRefURI = new URI(relativeRef);
if (relRefURI.isAbsolute()) {
ref = relativeRef;
} else {
if (lsi.startsWith("jar:")) {
int bangIdx = lsi.indexOf('!');
if (bangIdx > 0) {
ref = lsi.substring(0, bangIdx + 1)
+ new URI(lsi.substring(bangIdx + 1)).resolve(new URI(relativeRef)).toString();
} else {
ref = relativeRef;
}
} else {
ref = new URI(lsi).resolve(new URI(relativeRef)).toString();
}
}
if (parent != null) {
ref = Options.normalizeSystemId(ref);
if (parent.get(ref) != null) {
return;
}
InputSource is = null;
// allow entity resolver to find the actual byte stream.
if (parent.getEntityResolver() != null) {
is = parent.getEntityResolver().resolveEntity(null, ref);
}
if (is == null) {
is = new InputSource(ref);
} else {
ref = is.getSystemId();
}
if (parent.get(ref) != null) {
is.getByteStream().close();
return;
}
parent.parse(ref, is, false);
}
} catch (URISyntaxException e) {
String msg = e.getMessage();
if (new File(relativeRef).exists()) {
msg = "Filename is not a URI " + ' ' + msg;
}
SAXParseException spe = new SAXParseException2(
"Unable to parse " + relativeRef + ": " + msg,
locator, e);
fatalError(spe);
throw spe;
} catch (IOException e) {
SAXParseException spe = new SAXParseException2(
"Unable to parse " + relativeRef + ": " + e.getMessage(),
locator, e);
fatalError(spe);
throw spe;
}
}
protected String findExternalResource(String nsURI, String localName, Attributes atts) {
if ("http://www.w3.org/2001/XMLSchema".equals(nsURI)
&& ("import".equals(localName) || "include".equals(localName))) {
return atts.getValue("schemaLocation");
}
return null;
}
}
public XMLFilterImpl createExternalReferenceFinder(DOMForest parent) {
return new ReferenceFinder(parent);
}
}
private boolean checkXmlElementRef() {
try {
//check the version of JAXB-API that is actually being picked up
//so we can set target=2.1 if the 2.1 version of XmlElementRef is picked up
XmlElementRef.class.getMethod("required");
} catch (Throwable t) {
return true;
}
return false;
}
public static void main(String[] args) throws Exception {
List<String> cplist = new ArrayList<String>();
for (int x = 0; x < args.length; x++) {
if ("-classpath".equals(args[x])) {
cplist.add(args[x + 1]);
File file = getFile(args[x + 1]);
if (file.exists()) {
args[x + 1] = file.getAbsolutePath();
}
x++;
}
}
BuildContext context = new XJCBuildContext();
XJCErrorListener listener = new XJCErrorListener(context);
File outputFile = getFile(args[args.length - 1]);
int i = new XSDToJavaRunner(args, listener, outputFile, cplist).run();
System.exit(i);
}
}