use of org.apache.cxf.common.xmlschema.SchemaCollection in project cxf by apache.
the class WSDLServiceBuilderTest method testSchema.
@Test
public void testSchema() throws Exception {
setUpBasic();
SchemaCollection schemas = serviceInfo.getXmlSchemaCollection();
assertNotNull(schemas);
assertEquals(1, serviceInfo.getSchemas().size());
SchemaInfo schemaInfo = serviceInfo.getSchemas().iterator().next();
assertNotNull(schemaInfo);
assertEquals(schemaInfo.getNamespaceURI(), "http://apache.org/hello_world_soap_http/types");
assertEquals(schemas.read(schemaInfo.getElement()).getTargetNamespace(), "http://apache.org/hello_world_soap_http/types");
// add below code to test the creation of javax.xml.validation.Schema
// with schema in serviceInfo
Schema schema = EndpointReferenceUtils.getSchema(serviceInfo);
assertNotNull(schema);
control.verify();
}
use of org.apache.cxf.common.xmlschema.SchemaCollection 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.common.xmlschema.SchemaCollection in project cxf by apache.
the class WadlGenerator method getSchemaCollection.
private SchemaCollection getSchemaCollection(ResourceTypes resourceTypes, JAXBContext context) {
if (context == null) {
return null;
}
SchemaCollection xmlSchemaCollection = new SchemaCollection();
Collection<DOMSource> schemas = new HashSet<>();
List<String> targetNamespaces = new ArrayList<>();
try {
for (DOMResult r : JAXBUtils.generateJaxbSchemas(context, CastUtils.cast(Collections.emptyMap(), String.class, DOMResult.class))) {
Document doc = (Document) r.getNode();
ElementQNameResolver theResolver = createElementQNameResolver(context);
String tns = doc.getDocumentElement().getAttribute("targetNamespace");
String tnsPrefix = doc.getDocumentElement().lookupPrefix(tns);
if (tnsPrefix == null) {
String tnsDecl = doc.getDocumentElement().getAttribute("xmlns:tns");
tnsPrefix = tnsDecl != null && tnsDecl.equals(tns) ? "tns:" : "";
} else {
tnsPrefix += ":";
}
if (supportJaxbXmlType) {
for (Class<?> cls : resourceTypes.getAllTypes().keySet()) {
if (isXmlRoot(cls)) {
continue;
}
XmlType root = cls.getAnnotation(XmlType.class);
if (root != null) {
QName typeName = theResolver.resolve(cls, new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
if (typeName != null && tns.equals(typeName.getNamespaceURI())) {
QName elementName = resourceTypes.getXmlNameMap().get(cls);
if (elementName == null) {
elementName = typeName;
}
Element newElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:element");
newElement.setAttribute("name", elementName.getLocalPart());
newElement.setAttribute("type", tnsPrefix + typeName.getLocalPart());
if (Modifier.isAbstract(cls.getModifiers()) && resourceTypes.getSubstitutions().values().contains(cls)) {
newElement.setAttribute("abstract", "true");
}
doc.getDocumentElement().appendChild(newElement);
}
}
}
if (supportJaxbSubstitutions) {
for (Map.Entry<Class<?>, Class<?>> entry : resourceTypes.getSubstitutions().entrySet()) {
QName typeName = theResolver.resolve(entry.getKey(), new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
for (Element element : DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(), Constants.URI_2001_SCHEMA_XSD, "element")) {
if (element.getAttribute("name").equals(typeName.getLocalPart())) {
QName groupName = theResolver.resolve(entry.getValue(), new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
if (groupName != null) {
element.setAttribute("substitutionGroup", tnsPrefix + groupName.getLocalPart());
}
}
}
}
}
}
if (supportCollections && !resourceTypes.getCollectionMap().isEmpty()) {
for (Map.Entry<Class<?>, QName> entry : resourceTypes.getCollectionMap().entrySet()) {
QName colQName = entry.getValue();
if (colQName == null) {
colQName = theResolver.resolve(entry.getKey(), new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
if (colQName != null) {
colQName = new QName(colQName.getNamespaceURI(), colQName.getLocalPart() + "s", colQName.getPrefix());
}
}
if (colQName == null) {
continue;
}
if (tns.equals(colQName.getNamespaceURI())) {
QName typeName = theResolver.resolve(entry.getKey(), new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
if (typeName != null) {
Element newElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:element");
newElement.setAttribute("name", colQName.getLocalPart());
Element ctElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:complexType");
newElement.appendChild(ctElement);
Element seqElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:sequence");
ctElement.appendChild(seqElement);
Element xsElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:element");
seqElement.appendChild(xsElement);
xsElement.setAttribute("ref", tnsPrefix + typeName.getLocalPart());
xsElement.setAttribute("minOccurs", "0");
xsElement.setAttribute("maxOccurs", "unbounded");
doc.getDocumentElement().appendChild(newElement);
}
}
}
}
DOMSource source = new DOMSource(doc, r.getSystemId());
schemas.add(source);
if (!StringUtils.isEmpty(tns)) {
targetNamespaces.add(tns);
}
}
} catch (IOException e) {
LOG.fine("No schema can be generated");
return null;
}
boolean hackAroundEmptyNamespaceIssue = false;
for (DOMSource r : schemas) {
hackAroundEmptyNamespaceIssue = addSchemaDocument(xmlSchemaCollection, targetNamespaces, (Document) r.getNode(), r.getSystemId(), hackAroundEmptyNamespaceIssue);
}
return xmlSchemaCollection;
}
use of org.apache.cxf.common.xmlschema.SchemaCollection in project cxf by apache.
the class JavaScriptContainer method execute.
@SuppressWarnings("unchecked")
public void execute() throws ToolException {
if (hasInfoOption()) {
return;
}
buildToolContext();
validate(context);
WSDLConstants.WSDLVersion version = getWSDLVersion();
String wsdlURL = (String) context.get(ToolConstants.CFG_WSDLURL);
List<ServiceInfo> serviceList = (List<ServiceInfo>) context.get(ToolConstants.SERVICE_LIST);
if (serviceList == null) {
serviceList = new ArrayList<>();
PluginLoader pluginLoader = PluginLoader.newInstance();
// for JavaScript generation, we always use JAX-WS.
FrontEndProfile frontend = pluginLoader.getFrontEndProfile("jaxws");
// Build the ServiceModel from the WSDLModel
if (version == WSDLConstants.WSDLVersion.WSDL11) {
AbstractWSDLBuilder builder = frontend.getWSDLBuilder();
builder.setContext(context);
builder.setBus(getBus());
context.put(Bus.class, getBus());
builder.build(URIParserUtil.getAbsoluteURI(wsdlURL));
builder.customize();
Definition definition = builder.getWSDLModel();
context.put(Definition.class, definition);
builder.validate(definition);
WSDLServiceBuilder serviceBuilder = new WSDLServiceBuilder(getBus());
String serviceName = (String) context.get(ToolConstants.CFG_SERVICENAME);
if (serviceName != null) {
List<ServiceInfo> services = serviceBuilder.buildServices(definition, getServiceQName(definition));
serviceList.addAll(services);
} else if (definition.getServices().size() > 0) {
serviceList = serviceBuilder.buildServices(definition);
} else {
serviceList = serviceBuilder.buildMockServices(definition);
}
} else {
// TODO: wsdl2.0 support
throw new ToolException("Only WSDL 1.1 supported");
}
}
if (serviceList.isEmpty()) {
throw new ToolException("Did not find any services in WSDL");
}
Map<String, InterfaceInfo> interfaces = new LinkedHashMap<String, InterfaceInfo>();
ServiceInfo service0 = serviceList.get(0);
SchemaCollection schemaCollection = service0.getXmlSchemaCollection();
context.put(ToolConstants.XML_SCHEMA_COLLECTION, schemaCollection);
context.put(ToolConstants.PORTTYPE_MAP, interfaces);
context.put(ClassCollector.class, new ClassCollector());
WSDLToJavaScriptProcessor processor = new WSDLToJavaScriptProcessor();
for (ServiceInfo service : serviceList) {
context.put(ServiceInfo.class, service);
validate(service);
processor.setEnvironment(context);
processor.process();
}
}
use of org.apache.cxf.common.xmlschema.SchemaCollection in project cxf by apache.
the class ValidatorUtil method getSchemaList.
/**
* Get a list of schemas found in a wsdl Document.
* The list will include any schemas from imported wsdls.
*
* @param document The wsdl Document.
* @param baseURI The URI of the wsdl. Allows schemas with relative
* paths to be resolved.
* @return XmlSchemaCollection list
* @throws IOException
* @throws SAXException
*/
public static List<SchemaCollection> getSchemaList(Document document, String baseURI) throws IOException, SAXException {
List<SchemaCollection> schemaList = new ArrayList<>();
if (document == null) {
return schemaList;
}
synchronized (document) {
// URL might need encoding for special characters.
baseURI = URLEncoder.encode(baseURI, "utf-8");
SchemaCollection schemaCol = new SchemaCollection();
schemaCol.setBaseUri(baseURI);
List<Element> elemList = DOMUtils.findAllElementsByTagNameNS(document.getDocumentElement(), WSDLConstants.NS_SCHEMA_XSD, "schema");
for (Element schemaEl : elemList) {
String tns = schemaEl.getAttribute("targetNamespace");
try {
schemaCol.read(schemaEl, tns);
} catch (RuntimeException ex) {
LOG.log(Level.WARNING, "SCHEMA_READ_FAIL", tns);
// in the baseURI here.
try {
schemaCol.read(schemaEl, baseURI);
} catch (RuntimeException ex2) {
LOG.log(Level.WARNING, "SCHEMA_READ_FAIL", baseURI);
continue;
}
}
}
schemaList.add(schemaCol);
// Now add schemas from imported wsdl files.
Map<String, Document> wsdlImports = getImportedWsdlMap(document, baseURI);
for (Document wsdlImport : wsdlImports.values()) {
schemaList.addAll(getSchemaList(wsdlImport, baseURI));
}
}
return schemaList;
}
Aggregations