下面列出了javax.xml.bind.annotation.XmlList#org.apache.ws.commons.schema.XmlSchema 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* due to a bug, feature, or just plain oddity of JAXB, it isn't good enough
* to just check the form of an element and of its schema. If schema 'a'
* (default unqualified) has a complex type with an element with a ref= to
* schema (b) (default unqualified), JAXB seems to expect to see a
* qualifier, anyway. <br/> So, if the element is local to a complex type,
* all we care about is the default element form of the schema and the local
* form of the element. <br/> If, on the other hand, the element is global,
* we might need to compare namespaces. <br/>
*
* @param element the element.
* @param global if this element is a global element (complex type ref= to
* it, or in a part)
* @param localSchema the schema of the complex type containing the
* reference, only used for the 'odd case'.
* @param elementSchema the schema for the element.
* @return if the element needs to be qualified.
*/
public static boolean isElementQualified(XmlSchemaElement element,
boolean global,
XmlSchema localSchema,
XmlSchema elementSchema) {
QName qn = getElementQualifiedName(element, localSchema);
if (qn == null) {
throw new RuntimeException("isElementQualified on anonymous element.");
}
if (element.isRef()) {
throw new RuntimeException("isElementQualified on the 'from' side of ref=.");
}
if (global) {
return isElementNameQualified(element, elementSchema)
|| (localSchema != null
&& !(qn.getNamespaceURI().equals(localSchema.getTargetNamespace())));
}
return isElementNameQualified(element, elementSchema);
}
private void createRpcEnvelope(XmlSchemaExtractor schemaExtractor, QName operationWrapper) throws ParserException {
// create soap envelope
final XmlSchema soapSchema = schemaExtractor.getTargetSchemas().getSchemaByTargetNamespace(soapVersion.getNamespace());
final List<XmlSchemaSequenceMember> soapEnvelope = getSoapEnvelope(soapSchema);
if (headerParts != null) {
// soap header
final List<XmlSchemaSequenceMember> soapHeader = getXmlSchemaElement(soapSchema, soapEnvelope,
soapVersion.getHeader());
// add header elements
soapHeader.addAll(getPartElements(schemaExtractor, soapSchema, headerParts));
}
// soap body
final List<XmlSchemaSequenceMember> soapBody = getXmlSchemaElement(soapSchema, soapEnvelope, soapVersion.getBody());
// top-level operation wrapper element
final String namespaceURI = operationWrapper.getNamespaceURI();
final XmlSchema operationSchema = schemaExtractor.getOrCreateTargetSchema(namespaceURI);
final List<XmlSchemaSequenceMember> bodySequence = getXmlSchemaElement(operationSchema, soapSchema,
soapBody, operationWrapper.getLocalPart(), true);
// add bodyParts to wrapper element
bodySequence.addAll(getPartElements(schemaExtractor, operationSchema, bodyParts));
}
private void createDocumentEnvelope(XmlSchemaExtractor schemaExtractor, List<XmlSchemaElement> headerElements,
List<XmlSchemaElement> bodyElements) {
// envelope element
final XmlSchema soapSchema = schemaExtractor.getTargetSchemas().getSchemaByTargetNamespace(soapVersion.getNamespace());
final List<XmlSchemaSequenceMember> envelope = getSoapEnvelope(soapSchema);
// check if there is a header included
if (headerElements != null) {
final List<XmlSchemaSequenceMember> headers = getXmlSchemaElement(soapSchema, envelope, soapVersion.getHeader());
headers.addAll(headerElements);
}
// add body wrapper
final List<XmlSchemaSequenceMember> bodySequence = getXmlSchemaElement(soapSchema, envelope, soapVersion.getBody());
bodySequence.addAll(bodyElements);
}
private SchemaInfo createSchemaIfNeeded(String namespace, NamespaceMap nsMap) {
SchemaInfo schemaInfo = serviceInfo.getSchema(namespace);
if (schemaInfo == null) {
XmlSchema xmlSchema = schemas.newXmlSchemaInCollection(namespace);
if (qualifiedSchemas) {
xmlSchema.setElementFormDefault(XmlSchemaForm.QUALIFIED);
}
xmlSchema.setNamespaceContext(nsMap);
schemaInfo = new SchemaInfo(namespace);
schemaInfo.setSchema(xmlSchema);
serviceInfo.addSchema(schemaInfo);
}
return schemaInfo;
}
private static XmlSchemaElement findElement(XmlSchema xmlSchema, QName elName) {
XmlSchemaElement schemaElement = null;
schemaElement = xmlSchema.getElementByName(elName);
if (schemaElement == null) {
String prefix = definition.getPrefix(elName.getNamespaceURI());
QName name = new QName(elName.getNamespaceURI(), prefix + ":" + elName.getLocalPart(), prefix);
schemaElement = xmlSchema.getElementByName(name);
}
if (schemaElement != null) {
return schemaElement;
}
for (XmlSchemaExternal ext : xmlSchema.getExternals()) {
if (!(ext instanceof XmlSchemaImport)) {
schemaElement = findElement(ext.getSchema(), elName);
if (schemaElement != null) {
return schemaElement;
}
}
}
return schemaElement;
}
/**
* Generate an XML Schema using a model of COBOL data items. The model is a
* list of root level items. From these, we only process group items
* (structures) with children.
*
* @param cobolDataItems a list of COBOL data items
* @param targetNamespace the target namespace to use (null for no namespace)
* @return the XML schema
*/
public XmlSchema emitXsd(final List < CobolDataItem > cobolDataItems, final String targetNamespace) {
if (_log.isDebugEnabled()) {
_log.debug("5. Emitting XML Schema from model: {}",
cobolDataItems.toString());
}
XmlSchema xsd = createXmlSchema(getConfig().getXsdEncoding(), targetNamespace);
List < String > nonUniqueCobolNames = getNonUniqueCobolNames(cobolDataItems);
XsdEmitter emitter = new XsdEmitter(xsd, getConfig());
for (CobolDataItem cobolDataItem : cobolDataItems) {
if (getConfig().ignoreOrphanPrimitiveElements()
&& cobolDataItem.getChildren().size() == 0) {
continue;
}
XsdDataItem xsdDataItem = new XsdDataItem(cobolDataItem,
getConfig(), null, 0, nonUniqueCobolNames, _errorHandler);
// Create and add a root element
xsd.getItems().add(emitter.createXmlSchemaElement(xsdDataItem));
}
return xsd;
}
protected XmlSchemaType lookUpType(Part part) {
XmlSchemaType schemaType = null;
for (XmlSchema xmlSchema : xmlSchemaList.getXmlSchemas()) {
if (part.getElementName() != null) {
XmlSchemaElement schemaElement = xmlSchema.getElementByName(part.getElementName());
if (schemaElement != null) {
schemaType = schemaElement.getSchemaType();
}
} else {
if (part.getTypeName() != null) {
schemaType = xmlSchema.getTypeByName(part.getTypeName());
}
}
if (schemaType != null) {
return schemaType;
}
}
return schemaType;
}
protected void generateSchemas(Resource[] schemaResources) throws IOException {
LOG.info("Starting XSD -> NeutralSchema Generator...");
LOG.info("Using XML Schema Directory Path: " + getXsdPath());
// Scan XML Schemas on path
List<XmlSchema> xmlSchemas = parseXmlSchemas(schemaResources, XSD);
// Iterate XML Schemas
for (XmlSchema schema : xmlSchemas) {
loadSchema(schema);
}
LOG.info("Statistics:");
LOG.info("Xml Total Schema Files Parsed: " + xmlSchemas.size());
LOG.info("Xml Total Schema Count: " + schemas.size());
LOG.info("Finished.");
}
private void addExceptionMessage(Class<?> cls, XmlSchema schema, XmlSchemaSequence seq) {
try {
//a subclass could mark the message method as transient
Method m = cls.getMethod("getMessage");
if (!m.isAnnotationPresent(XmlTransient.class)
&& m.getDeclaringClass().equals(Throwable.class)) {
JAXBBeanInfo beanInfo = getBeanInfo(java.lang.String.class);
XmlSchemaElement exEle = new XmlSchemaElement(schema, false);
exEle.setName("message");
exEle.setSchemaTypeName(getTypeName(beanInfo));
exEle.setMinOccurs(0);
seq.getItems().add(exEle);
}
} catch (Exception e) {
//ignore, just won't have the message element
}
}
/**
* Process each element in the input Schema.
* <p/>
*
* @param xmlSchema the XML schema with COBOL annotations
* @return a map of root elements in the XML schema, each one mapped to its
* composite types constituents
* @throws Xsd2ConverterException if parsing the XML schema fails
*/
public Map < String, RootCompositeType > build(XmlSchema xmlSchema)
throws Xsd2ConverterException {
log.debug("visit XML Schema started");
Map < String, RootCompositeType > rootComplexTypes = new LinkedHashMap < String, RootCompositeType >();
for (Entry < QName, XmlSchemaElement > entry : xmlSchema.getElements()
.entrySet()) {
if (entry.getValue().getSchemaType() instanceof XmlSchemaComplexType) {
CobolAnnotations cobolAnnotations = new CobolAnnotations(
entry.getValue());
XmlSchemaComplexType xsdComplexType = (XmlSchemaComplexType) entry
.getValue().getSchemaType();
RootCompositeType compositeTypes = new RootCompositeType(
cobolAnnotations.getCobolName());
String complexTypeName = getComplexTypeName(xsdComplexType);
rootComplexTypes.put(complexTypeName, compositeTypes);
visit(xsdComplexType, compositeTypes, complexTypeName);
}
}
log.debug("visit XML Schema ended");
return rootComplexTypes;
}
/**
* Determines whether the schema has already received (cross) imports for the schemaType
*
* @param schema
* @param schemaType
* @return false if cross imports for schemaType must still be added to schema
*/
private boolean crossImportsAdded(XmlSchema schema, XmlSchemaType schemaType) {
boolean result = true;
if (schemaType != null) {
Set<XmlSchemaType> xmlTypesCheckedForCrossImports;
if (!xmlTypesCheckedForCrossImportsPerSchema.containsKey(schema)) {
xmlTypesCheckedForCrossImports = new HashSet<>();
xmlTypesCheckedForCrossImportsPerSchema.put(schema, xmlTypesCheckedForCrossImports);
} else {
xmlTypesCheckedForCrossImports = xmlTypesCheckedForCrossImportsPerSchema.get(schema);
}
if (!xmlTypesCheckedForCrossImports.contains(schemaType)) {
// cross imports for this schemaType have not yet been added
xmlTypesCheckedForCrossImports.add(schemaType);
result = false;
}
}
return result;
}
public VisitorBase(Scope scopeRef,
Definition defn,
XmlSchema schemaRef,
WSDLASTVisitor wsdlASTVisitor) {
wsdlVisitor = wsdlASTVisitor;
schemas = wsdlVisitor.getSchemas();
scopedNames = wsdlVisitor.getScopedNames();
deferredActions = wsdlVisitor.getDeferredActions();
typeMap = wsdlVisitor.getTypeMap();
manager = wsdlVisitor.getManager();
mapper = wsdlVisitor.getModuleToNSMapper();
scope = scopeRef;
scope.setPrefix(wsdlASTVisitor.getPragmaPrefix());
fullyQualifiedName = null;
schemaType = null;
corbaType = null;
definition = defn;
schema = schemaRef;
}
/**
* extract all complex types from a schema and cache into a map
*/
private void cacheComplexTypes(XmlSchema schema) {
XmlSchemaObjectCollection schemaItems = schema.getItems();
int numElements = schemaItems.getCount();
// Iterate XML Schema items
for (int i = 0; i < numElements; i++) {
XmlSchemaObject schemaObject = schemaItems.getItem(i);
if (schemaObject instanceof XmlSchemaComplexType) {
XmlSchemaComplexType complexType = (XmlSchemaComplexType) schemaObject;
String elementTypeName = complexType.getName();
complexTypes.put(elementTypeName, complexType);
}
}
}
@Override
public void writeSchema(XmlSchema root) {
XmlSchemaSimpleType simple = new XmlSchemaSimpleType(root, true);
simple.setName(getSchemaType().getLocalPart());
XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
restriction.setBaseTypeName(Constants.XSD_STRING);
simple.setContent(restriction);
Object[] constants = getTypeClass().getEnumConstants();
List<XmlSchemaFacet> facets = restriction.getFacets();
for (Object constant : constants) {
XmlSchemaEnumerationFacet f = new XmlSchemaEnumerationFacet();
f.setValue(getValue(constant));
facets.add(f);
}
}
private NeutralSchema parseSimpleType(XmlSchemaSimpleType schemaSimpleType, XmlSchema schema, String name) {
NeutralSchema ns = recursiveParseSimpleType(schemaSimpleType, schema);
if (schemaSimpleType.getName() == null) {
// Type defined in-line. Need to capture it in the element schema set.
int i = 1;
NeutralSchema existing = elementSchemas.get(name + i);
while (existing != null && !schemasEqual(ns, existing)) {
i++;
existing = schemas.get(name + i);
}
ns.setType(name + i);
elementSchemas.put(name + i, ns);
}
return ns;
}
private void addCorbaTypes(Definition definition) throws Exception {
for (XmlSchema xmlSchemaTypes : xmlSchemaList.getXmlSchemas()) {
for (XmlSchemaExternal ext : xmlSchemaTypes.getExternals()) {
addCorbaTypes(ext.getSchema());
// REVISIT: This was preventing certain types from being added to the corba
// typemap even when they are referenced from other parts of the wsdl.
//
// Should this add the corba types if it IS an instance of the XmlSchemaImport
// (and not an XmlSchemaInclude or XmlSchemaRedefine)?
//if (!(extSchema instanceof XmlSchemaImport)) {
// addCorbaTypes(extSchema.getSchema());
//}
}
if (!W3CConstants.NU_SCHEMA_XSD.equals(xmlSchemaTypes.getTargetNamespace())) {
addCorbaTypes(xmlSchemaTypes);
}
}
}
private static void processSchema(XmlSchema schema, OutputStream outputStream,
String contextRoot, org.wso2.micro.core.transports.CarbonHttpRequest request) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
schema.write(baos);
RequestProcessorUtil.writeDocument(baos, outputStream, "annotated-xsd.xsl", contextRoot,
isXSDAnnotated(request));
}
private static final void convertComplexType(final XmlSchemaComplexType complexType, final XmlSchema schema,
final Xsd2UmlConfig config, final Visitor handler, final QName complexTypeName,
final List<TaggedValue> taggedValues) {
final Identifier complexTypeId = config.ensureId(complexTypeName);
final List<Attribute> attributes = new LinkedList<Attribute>();
if (complexType.getContentModel() != null && complexType.getContentModel().getContent() != null) {
final XmlSchemaContent content = complexType.getContentModel().getContent();
if (content instanceof XmlSchemaComplexContentExtension) {
final XmlSchemaComplexContentExtension complexContentExtension = (XmlSchemaComplexContentExtension) content;
attributes.addAll(parseFields(complexContentExtension, schema, config));
// The base of the restriction is interpreted as a UML
// generalization.
final QName base = complexContentExtension.getBaseTypeName();
final Identifier baseId = config.ensureId(base);
// Hack here to support anonymous complex types in the context
// of elements.
// Need to fix the SLI MongoDB schemes so that all types are
// named.
handler.visit(new Generalization(config.getPlugin().nameFromComplexTypeExtension(complexTypeName, base),
complexTypeId, baseId));
} else if (content instanceof XmlSchemaComplexContentRestriction) {
throw new AssertionError(content);
} else if (content instanceof XmlSchemaSimpleContentExtension) {
throw new AssertionError(content);
} else if (content instanceof XmlSchemaSimpleContentRestriction) {
throw new AssertionError(content);
} else {
throw new AssertionError(content);
}
}
attributes.addAll(parseFields(complexType, schema, config));
final String name = config.getPlugin().nameFromSchemaTypeName(complexTypeName);
handler.visit(new ClassType(complexTypeId, name, false, attributes, taggedValues));
}
public XmlSchema getOrCreateTargetSchema(String namespaceURI) {
XmlSchema targetSchema = targetSchemas.getSchemaByTargetNamespace(namespaceURI);
if (targetSchema == null) {
targetSchema = targetSchemas.newXmlSchemaInCollection(namespaceURI);
final XmlSchema sourceSchema = sourceSchemas.getSchemaByTargetNamespace(namespaceURI);
if (sourceSchema != null) {
// copy schema properties from source schema
targetSchema.setElementFormDefault(sourceSchema.getElementFormDefault());
targetSchema.setAttributeFormDefault(sourceSchema.getAttributeFormDefault());
}
}
return targetSchema;
}
private boolean isExistImport(XmlSchema schema, String ns) {
boolean isExist = false;
for (XmlSchemaExternal ext : schema.getExternals()) {
if (ext instanceof XmlSchemaImport) {
XmlSchemaImport xsImport = (XmlSchemaImport)ext;
if (xsImport.getNamespace().equals(ns)) {
isExist = true;
break;
}
}
}
return isExist;
}
public static boolean isSchemaFormQualified(ToolContext context, QName partElement) {
ServiceInfo serviceInfo = context.get(ServiceInfo.class);
SchemaCollection schemaCol = serviceInfo.getXmlSchemaCollection();
XmlSchema schema = schemaCol.getSchemaForElement(partElement);
if (schema != null) {
return schema.getElementFormDefault() == XmlSchemaForm.QUALIFIED;
}
return false;
}
protected void addElement(XmlSchema schema,
XmlSchemaSequence seq, JAXBBeanInfo beanInfo,
QName name, boolean isArray, XmlElement xmlElementAnno) {
XmlSchemaElement el = new XmlSchemaElement(schema, false);
if (isArray) {
el.setMinOccurs(0);
el.setMaxOccurs(Long.MAX_VALUE);
} else {
if (xmlElementAnno == null) {
el.setMinOccurs(0);
el.setNillable(false);
} else {
el.setNillable(xmlElementAnno.nillable());
int minOccurs = xmlElementAnno.required() ? 1 : 0;
el.setMinOccurs(minOccurs);
}
}
if (beanInfo.isElement()) {
QName ename = new QName(beanInfo.getElementNamespaceURI(null),
beanInfo.getElementLocalName(null));
XmlSchemaElement el2 = schemas.getElementByQName(ename);
el.setNillable(false);
el.getRef().setTargetQName(el2.getQName());
} else {
if (xmlElementAnno != null && !StringUtils.isEmpty(xmlElementAnno.name())) {
el.setName(xmlElementAnno.name());
} else {
el.setName(name.getLocalPart());
}
Iterator<QName> itr = beanInfo.getTypeNames().iterator();
if (!itr.hasNext()) {
return;
}
QName typeName = itr.next();
el.setSchemaTypeName(typeName);
}
seq.getItems().add(el);
}
/**
* Is there an import for a particular namespace in a schema?
* @param schema
* @param namespaceUri
*/
public static boolean schemaImportsNamespace(XmlSchema schema, String namespaceUri) {
List<XmlSchemaExternal> externals = schema.getExternals();
for (XmlSchemaExternal what : externals) {
if (what instanceof XmlSchemaImport) {
XmlSchemaImport imp = (XmlSchemaImport)what;
// already there.
if (namespaceUri.equals(imp.getNamespace())) {
return true;
}
}
}
return false;
}
public void validateSchema(Element ele,
String uri,
final OASISCatalogManager catalog,
final SchemaCollection schemaCollection) throws ToolException {
SchemaFactory schemaFact = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFact.setResourceResolver(new LSResourceResolver() {
public LSInput resolveResource(String type,
String namespaceURI,
String publicId,
String systemId,
String baseURI) {
String s = JAXBDataBinding.mapSchemaLocation(systemId, baseURI, catalog);
LOG.fine("validating: " + namespaceURI + " " + systemId + " " + baseURI + " " + s);
if (s == null) {
XmlSchema sc = schemaCollection.getSchemaByTargetNamespace(namespaceURI);
if (sc != null) {
StringWriter writer = new StringWriter();
sc.write(writer);
InputSource src = new InputSource(new StringReader(writer.toString()));
src.setSystemId(sc.getSourceURI());
return new LSInputSAXWrapper(src);
}
throw new ToolException("Schema not found for namespace: " + namespaceURI);
}
return new LSInputSAXWrapper(new InputSource(s));
}
});
DOMSource domSrc = new DOMSource(ele, uri);
try {
schemaFact.newSchema(domSrc);
} catch (SAXException e) {
if (e.getLocalizedMessage().indexOf("src-resolve.4.2") > -1) {
//Ignore schema resolve error and do nothing
} else {
//e.printStackTrace();
throw new ToolException("Schema Error : " + e.getLocalizedMessage(), e);
}
}
}
private static XmlSchemaElement getSchemaObject(WSDLToCorbaBinding wsdlToCorbaBinding, QName typeName) {
SchemaCollection schemaList = wsdlToCorbaBinding.getHelper().getXMLSchemaList();
for (XmlSchema s : schemaList.getXmlSchemas()) {
XmlSchemaElement e = s.getElementByName(typeName);
if (e != null) {
return e;
}
}
return null;
}
/**
* Create an elementInfo that stores information about a global, named,
* element.
*
* @param attribute the element
* @param currentSchema the schema it came from.
* @param schemaCollection the collection of all schemas.
* @param prefixAccumulator the accumulator that assigns prefixes.
* @return
*/
public static AttributeInfo forGlobalAttribute(XmlSchemaAttribute attribute, XmlSchema currentSchema,
SchemaCollection schemaCollection,
NamespacePrefixAccumulator prefixAccumulator) {
AttributeInfo attributeInfo = new AttributeInfo();
attributeInfo.annotated = attribute;
attributeInfo.global = true;
factoryCommon(attribute, currentSchema, schemaCollection, prefixAccumulator, attributeInfo);
return attributeInfo;
}
/**
* This function is not part of the XmlSchema API. Who knows why?
*
* @param namespaceURI targetNamespace
* @return schema, or null.
*/
public XmlSchema getSchemaByTargetNamespace(String namespaceURI) {
for (XmlSchema schema : schemaCollection.getXmlSchemas()) {
if (namespaceURI != null && namespaceURI.equals(schema.getTargetNamespace())
|| namespaceURI == null && schema.getTargetNamespace() == null) {
return schema;
}
}
return null;
}
private Object getSchemaNode(XmlSchema schema, SchemaCollection schemaCollection) {
XmlSchemaSerializer xser = new XmlSchemaSerializer();
xser.setExtReg(schemaCollection.getExtReg());
Document[] docs;
try {
docs = xser.serializeSchema(schema, false);
} catch (XmlSchemaSerializerException e) {
throw new RuntimeException(e);
}
return docs[0].getDocumentElement();
}
@Test
public void testInheritedMapping() throws Exception {
BeanTypeInfo bti = new BeanTypeInfo(GregorianCalendar.class, "http://util.java");
BeanType beanType = new BeanType(bti);
beanType.setSchemaType(new QName("http://util.java{GregorianCalendar}"));
AegisContext context = new AegisContext();
context.initialize();
TypeMapping mapping = context.getTypeMapping();
// we are replacing the default mapping.
mapping.register(beanType);
XmlSchema schema = newXmlSchema("http://util.java");
beanType.writeSchema(schema);
// well, test?
}
public static boolean isAttributeFormQualified(ServiceInfo serviceInfo, String uri) {
if (uri != null) {
SchemaInfo schemaInfo = serviceInfo.getSchema(uri);
if (schemaInfo != null) {
return schemaInfo.isAttributeFormQualified();
}
Iterator<SchemaInfo> it = serviceInfo.getSchemas().iterator();
while (it.hasNext()) {
XmlSchema schema = it.next().getSchema();
return isAttributeFormQualified(schema, uri);
}
}
return false;
}