use of org.apache.cxf.catalog.OASISCatalogManager in project cxf by apache.
the class SchemaHandler method createSchema.
public static Schema createSchema(List<String> locations, String catalogLocation, final Bus bus) {
SchemaFactory factory = SchemaFactory.newInstance(Constants.URI_2001_SCHEMA_XSD);
Schema s = null;
try {
List<Source> sources = new ArrayList<>();
for (String loc : locations) {
List<URL> schemaURLs = new LinkedList<URL>();
if (loc.lastIndexOf(".") == -1 || loc.lastIndexOf('*') != -1) {
schemaURLs = ClasspathScanner.findResources(loc, "xsd");
} else {
URL url = ResourceUtils.getResourceURL(loc, bus);
if (url != null) {
schemaURLs.add(url);
}
}
if (schemaURLs.isEmpty()) {
throw new IllegalArgumentException("Cannot find XML schema location: " + loc);
}
for (URL schemaURL : schemaURLs) {
Reader r = new BufferedReader(new InputStreamReader(schemaURL.openStream(), StandardCharsets.UTF_8));
StreamSource source = new StreamSource(r);
source.setSystemId(schemaURL.toString());
sources.add(source);
}
}
if (sources.isEmpty()) {
return null;
}
final OASISCatalogManager catalogResolver = OASISCatalogManager.getCatalogManager(bus);
if (catalogResolver != null) {
catalogLocation = catalogLocation == null ? SchemaHandler.DEFAULT_CATALOG_LOCATION : catalogLocation;
URL catalogURL = ResourceUtils.getResourceURL(catalogLocation, bus);
if (catalogURL != null) {
try {
catalogResolver.loadCatalog(catalogURL);
factory.setResourceResolver(new LSResourceResolver() {
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
try {
String resolvedLocation = catalogResolver.resolveSystem(systemId);
if (resolvedLocation == null) {
resolvedLocation = catalogResolver.resolveURI(namespaceURI);
}
if (resolvedLocation == null) {
resolvedLocation = catalogResolver.resolvePublic(publicId != null ? publicId : namespaceURI, systemId);
}
if (resolvedLocation != null) {
InputStream resourceStream = ResourceUtils.getResourceStream(resolvedLocation, bus);
if (resourceStream != null) {
return new LSInputImpl(publicId, systemId, resourceStream);
}
}
} catch (Exception ex) {
// ignore
}
return null;
}
});
} catch (IOException ex) {
throw new IllegalArgumentException("Catalog " + catalogLocation + " can not be loaded", ex);
}
}
}
s = factory.newSchema(sources.toArray(new Source[sources.size()]));
} catch (Exception ex) {
throw new IllegalArgumentException("Failed to load XML schema : " + ex.getMessage(), ex);
}
return s;
}
use of org.apache.cxf.catalog.OASISCatalogManager in project cxf by apache.
the class WSDLGetUtils method updateDefinition.
protected void updateDefinition(Bus bus, Definition def, Map<String, Definition> done, Map<String, SchemaReference> doneSchemas, String base, String docBase, String parentResolvedLocation) {
OASISCatalogManager catalogs = OASISCatalogManager.getCatalogManager(bus);
Collection<List<?>> imports = CastUtils.cast((Collection<?>) def.getImports().values());
for (List<?> lst : imports) {
List<Import> impLst = CastUtils.cast(lst);
for (Import imp : impLst) {
String start = imp.getLocationURI();
String decodedStart;
try {
decodedStart = URLDecoder.decode(start, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new WSDLQueryException(new org.apache.cxf.common.i18n.Message("COULD_NOT_PROVIDE_WSDL", LOG, start), e);
}
String resolvedSchemaLocation = resolveWithCatalogs(catalogs, start, base);
if (resolvedSchemaLocation == null) {
try {
// check to see if it's already in a URL format. If so, leave it.
new URL(start);
} catch (MalformedURLException e) {
try {
start = getLocationURI(start, docBase);
decodedStart = URLDecoder.decode(start, "utf-8");
} catch (Exception e1) {
// ignore
}
if (done.put(decodedStart, imp.getDefinition()) == null) {
if (imp.getDefinition() != null && imp.getDefinition().getDocumentBaseURI() != null) {
done.put(imp.getDefinition().getDocumentBaseURI(), imp.getDefinition());
}
updateDefinition(bus, imp.getDefinition(), done, doneSchemas, base, start, null);
}
}
} else {
if (done.put(decodedStart, imp.getDefinition()) == null) {
done.put(resolvedSchemaLocation, imp.getDefinition());
if (imp.getDefinition() != null && imp.getDefinition().getDocumentBaseURI() != null) {
done.put(imp.getDefinition().getDocumentBaseURI(), imp.getDefinition());
}
updateDefinition(bus, imp.getDefinition(), done, doneSchemas, base, start, resolvedSchemaLocation);
}
}
}
}
/* This doesn't actually work. Setting setSchemaLocationURI on the import
* for some reason doesn't actually result in the new URI being written
* */
Types types = def.getTypes();
if (types != null) {
for (ExtensibilityElement el : CastUtils.cast(types.getExtensibilityElements(), ExtensibilityElement.class)) {
if (el instanceof Schema) {
updateSchemaImports(bus, (Schema) el, docBase, doneSchemas, base, parentResolvedLocation);
}
}
}
}
use of org.apache.cxf.catalog.OASISCatalogManager in project cxf by apache.
the class DynamicClientFactory method createClient.
public Client createClient(String wsdlUrl, QName service, ClassLoader classLoader, QName port, List<String> bindingFiles) {
if (classLoader == null) {
classLoader = Thread.currentThread().getContextClassLoader();
}
LOG.log(Level.FINE, "Creating client from WSDL " + wsdlUrl);
WSDLServiceFactory sf = (service == null) ? (new WSDLServiceFactory(bus, wsdlUrl)) : (new WSDLServiceFactory(bus, wsdlUrl, service));
sf.setAllowElementRefs(allowRefs);
Service svc = sf.create();
// all SI's should have the same schemas
SchemaCollection schemas = svc.getServiceInfos().get(0).getXmlSchemaCollection();
SchemaCompiler compiler = createSchemaCompiler();
InnerErrorListener listener = new InnerErrorListener(wsdlUrl);
Object elForRun = ReflectionInvokationHandler.createProxyWrapper(listener, JAXBUtils.getParamClass(compiler, "setErrorListener"));
compiler.setErrorListener(elForRun);
OASISCatalogManager catalog = bus.getExtension(OASISCatalogManager.class);
hackInNewInternalizationLogic(compiler, catalog);
addSchemas(compiler.getOptions(), compiler, svc.getServiceInfos(), schemas);
addBindingFiles(bindingFiles, compiler);
S2JJAXBModel intermediateModel = compiler.bind();
listener.throwException();
JCodeModel codeModel = intermediateModel.generateCode(null, elForRun);
StringBuilder sb = new StringBuilder();
boolean firstnt = false;
for (Iterator<JPackage> packages = codeModel.packages(); packages.hasNext(); ) {
JPackage jpackage = packages.next();
if (!isValidPackage(jpackage)) {
continue;
}
if (firstnt) {
sb.append(':');
} else {
firstnt = true;
}
sb.append(jpackage.name());
}
JAXBUtils.logGeneratedClassNames(LOG, codeModel);
String packageList = sb.toString();
// our hashcode + timestamp ought to be enough.
String stem = toString() + "-" + System.currentTimeMillis();
File src = new File(tmpdir, stem + "-src");
if (!src.mkdir()) {
throw new IllegalStateException("Unable to create working directory " + src.getPath());
}
try {
Object writer = JAXBUtils.createFileCodeWriter(src);
codeModel.build(writer);
} catch (Exception e) {
throw new IllegalStateException("Unable to write generated Java files for schemas: " + e.getMessage(), e);
}
File classes = new File(tmpdir, stem + "-classes");
if (!classes.mkdir()) {
throw new IllegalStateException("Unable to create working directory " + classes.getPath());
}
StringBuilder classPath = new StringBuilder();
try {
setupClasspath(classPath, classLoader);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
List<File> srcFiles = FileUtils.getFilesRecurse(src, ".+\\.java$");
if (!srcFiles.isEmpty() && !compileJavaSrc(classPath.toString(), srcFiles, classes.toString())) {
LOG.log(Level.SEVERE, new Message("COULD_NOT_COMPILE_SRC", LOG, wsdlUrl).toString());
}
FileUtils.removeDir(src);
URL[] urls = null;
try {
urls = new URL[] { classes.toURI().toURL() };
} catch (MalformedURLException mue) {
throw new IllegalStateException("Internal error; a directory returns a malformed URL: " + mue.getMessage(), mue);
}
final ClassLoader cl = ClassLoaderUtils.getURLClassLoader(urls, classLoader);
JAXBContext context;
Map<String, Object> contextProperties = jaxbContextProperties;
if (contextProperties == null) {
contextProperties = Collections.emptyMap();
}
try {
if (StringUtils.isEmpty(packageList)) {
context = JAXBContext.newInstance(new Class[0], contextProperties);
} else {
context = JAXBContext.newInstance(packageList, cl, contextProperties);
}
} catch (JAXBException jbe) {
throw new IllegalStateException("Unable to create JAXBContext for generated packages: " + jbe.getMessage(), jbe);
}
JAXBDataBinding databinding = new JAXBDataBinding();
databinding.setContext(context);
svc.setDataBinding(databinding);
ClientImpl client = new DynamicClientImpl(bus, svc, port, getEndpointImplFactory(), cl);
ServiceInfo svcfo = client.getEndpoint().getEndpointInfo().getService();
// Setup the new classloader!
ClassLoaderUtils.setThreadContextClassloader(cl);
TypeClassInitializer visitor = new TypeClassInitializer(svcfo, intermediateModel, allowWrapperOps());
visitor.walk();
// delete the classes files
FileUtils.removeDir(classes);
return client;
}
use of org.apache.cxf.catalog.OASISCatalogManager in project cxf by apache.
the class WSDLGetUtils method processSchemaReference.
private void processSchemaReference(SchemaReference schemaReference, Bus bus, Schema schema, String docBase, Map<String, SchemaReference> doneSchemas, String base, String parentResolved) {
OASISCatalogManager catalogs = OASISCatalogManager.getCatalogManager(bus);
String start = findSchemaLocation(doneSchemas, schemaReference, docBase);
String origLocation = schemaReference.getSchemaLocationURI();
if (start != null) {
String decodedStart;
String decodedOrigLocation;
// canonical representation of the import URL for lookup.
try {
decodedStart = URLDecoder.decode(start, "utf-8");
decodedOrigLocation = URLDecoder.decode(origLocation, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new WSDLQueryException(new org.apache.cxf.common.i18n.Message("COULD_NOT_PROVIDE_WSDL", LOG, start), e);
}
if (!doneSchemas.containsKey(decodedStart)) {
String resolvedSchemaLocation = resolveWithCatalogs(catalogs, start, base);
if (resolvedSchemaLocation == null) {
resolvedSchemaLocation = resolveWithCatalogs(catalogs, schemaReference.getSchemaLocationURI(), base);
}
if (resolvedSchemaLocation == null) {
try {
// check to see if it's already in a URL format. If so, leave it.
new URL(start);
} catch (MalformedURLException e) {
doneSchemas.put(decodedStart, schemaReference);
doneSchemas.put(schemaReference.getReferencedSchema().getDocumentBaseURI(), schemaReference);
if (!doneSchemas.containsKey(decodedOrigLocation)) {
doneSchemas.put(decodedOrigLocation, schemaReference);
}
try {
if (!(new URI(origLocation).isAbsolute()) && parentResolved != null) {
resolvedSchemaLocation = resolveRelativePath(parentResolved, decodedOrigLocation);
doneSchemas.put(resolvedSchemaLocation, schemaReference);
}
} catch (URISyntaxException e1) {
// ignore
}
updateSchemaImports(bus, schemaReference.getReferencedSchema(), start, doneSchemas, base, resolvedSchemaLocation);
}
} else if (doneSchemas.put(decodedStart, schemaReference) == null) {
doneSchemas.put(resolvedSchemaLocation, schemaReference);
String p = getAndSaveRelativeSchemaLocationIfCatalogResolved(doneSchemas, resolvedSchemaLocation, schema, schemaReference);
updateSchemaImports(bus, schemaReference.getReferencedSchema(), p, doneSchemas, base, resolvedSchemaLocation);
}
}
}
}
use of org.apache.cxf.catalog.OASISCatalogManager in project cxf by apache.
the class JAXBDataBinding method addSchemas.
private void addSchemas(Options opts, SchemaCompiler schemaCompiler, SchemaCollection schemaCollection) {
Set<String> ids = new HashSet<>();
@SuppressWarnings("unchecked") List<ServiceInfo> serviceList = (List<ServiceInfo>) context.get(ToolConstants.SERVICE_LIST);
for (ServiceInfo si : serviceList) {
for (SchemaInfo sci : si.getSchemas()) {
String key = sci.getSystemId();
if (ids.contains(key)) {
continue;
}
ids.add(key);
}
}
Bus bus = context.get(Bus.class);
OASISCatalogManager catalog = bus.getExtension(OASISCatalogManager.class);
for (XmlSchema schema : schemaCollection.getXmlSchemas()) {
if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(schema.getTargetNamespace())) {
continue;
}
String key = schema.getSourceURI();
if (ids.contains(key)) {
continue;
}
if (!key.startsWith("file:") && !key.startsWith("jar:")) {
XmlSchemaSerializer xser = new XmlSchemaSerializer();
xser.setExtReg(schemaCollection.getExtReg());
Document[] docs;
try {
docs = xser.serializeSchema(schema, false);
} catch (XmlSchemaSerializerException e) {
throw new RuntimeException(e);
}
Element ele = docs[0].getDocumentElement();
if (context.fullValidateWSDL()) {
String uri = null;
try {
uri = docs[0].getDocumentURI();
} catch (Throwable ex) {
// ignore - DOM level 3
}
validateSchema(ele, uri, catalog, schemaCollection);
}
ele = removeImportElement(ele, key, catalog);
try {
docs[0].setDocumentURI(key);
} catch (Throwable t) {
// ignore - DOM level 3
}
InputSource is = new InputSource((InputStream) null);
// key = key.replaceFirst("#types[0-9]+$", "");
is.setSystemId(key);
is.setPublicId(key);
opts.addGrammar(is);
try {
schemaCompiler.parseSchema(key, createNoCDATAReader(StaxUtils.createXMLStreamReader(ele, key)));
} catch (XMLStreamException e) {
throw new ToolException(e);
}
}
}
for (XmlSchema schema : schemaCollection.getXmlSchemas()) {
if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(schema.getTargetNamespace())) {
continue;
}
String key = schema.getSourceURI();
String tns = schema.getTargetNamespace();
String ltns = schema.getLogicalTargetNamespace();
// accepting also a null tns (e.g., reported by apache.ws.xmlschema for no-namespace)
if (ids.contains(key) || (tns == null && !StringUtils.isEmpty(ltns))) {
continue;
}
if (key.startsWith("file:") || key.startsWith("jar:")) {
InputStream in = null;
try {
if (key.startsWith("file:")) {
in = Files.newInputStream(new File(new URI(key)).toPath());
} else {
in = new URL(key).openStream();
}
XMLStreamReader reader = StaxUtils.createXMLStreamReader(key, in);
reader = createNoCDATAReader(new LocationFilterReader(reader, catalog));
InputSource is = new InputSource(key);
opts.addGrammar(is);
schemaCompiler.parseSchema(key, reader);
reader.close();
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
}
}
}
addSchemasForServiceInfos(catalog, serviceList, opts, schemaCompiler, schemaCollection);
}
Aggregations