List of usage examples for org.jdom2 Attribute Attribute
public Attribute(final String name, final String value)
Attribute
with the specified (local) name and value, and does not place the attribute in a Namespace
. From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java
License:Apache License
/** * It generates the XSD file of the targetNamespace given at the constructor, taking into account that * the main namespace is the one given at the constructor. * /*from ww w . jav a 2s . co m*/ * @param schema the schema object * @param configuration the inference configuration * * @return a JDOM2 {@link Document} object containing the XSD contents. * * @see SchemaDocumentGenerator#generateSchemaDocument(Schema, XSDInferenceConfiguration) */ @Override public Document generateSchemaDocument(Schema schema, XSDInferenceConfiguration configuration) { // if(!configuration.getElementsGlobal()==false || // !configuration.getComplexTypesGlobal()==true || // !configuration.getSimpleTypesGlobal()==true // ) // throw new UnsupportedOperationException("Not implemented yet."); // checkArgument(schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(mainNamespace), "The main namespace must be a known namespace"); checkArgument(schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(targetNamespace), "The target namespace must be a known namespace"); // checkArgument(!schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(XSD_NAMESPACE_URI),"The XSD namespace must not be a known namespace"); // checkArgument(!schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(XSI_NAMESPACE_URI),"The XSI namespace must not be a known namespace"); Map<String, String> namespaceURIToPrefixMappings = schema.getSolvedNamespaceMappings(); if (configuration.getSkipNamespaces().contains(targetNamespace)) { throw new IllegalArgumentException("This is an skipped namespace, so its XSD should not be generated"); } if (targetNamespace.equals(XSD_NAMESPACE_URI)) System.err.println( "The XML Schema namespace is being considered as a target namespace in your documents. Independing of the inferred schemas, the only valid XSD for an XSD would be the normative one present at its first RFC"); Namespace xsdNamespace = Namespace.getNamespace(XSD_NAMESPACE_PREFIX.replace(":", ""), XSD_NAMESPACE_URI); List<Namespace> namespaceDeclarations = getNamespaceDeclarations(namespaceURIToPrefixMappings, xsdNamespace); Element elementSchema = new Element("schema", xsdNamespace); for (int i = 0; i < namespaceDeclarations.size(); i++) { Namespace currentNamespace = namespaceDeclarations.get(i); elementSchema.addNamespaceDeclaration(currentNamespace); String currentNamespaceUri = currentNamespace.getURI(); if (!targetNamespace.equals(mainNamespace) && !currentNamespaceUri.equals(mainNamespace)) continue; if (currentNamespace.equals(Namespace.XML_NAMESPACE) && (!schema.getAttributes().containsRow(XSDInferenceConfiguration.XML_NAMESPACE_URI) && !schema.getElements().containsRow(XSDInferenceConfiguration.XML_NAMESPACE_URI))) { continue; } if (currentNamespaceUri.equals(XSD_NAMESPACE_URI) && !namespaceURIToPrefixMappings.containsKey(XSD_NAMESPACE_URI)) continue; if (targetNamespace.equals(currentNamespaceUri) || (currentNamespaceUri.equals("") && (fileNameGenerator == null))) continue; if (currentNamespaceUri.equals("") && !currentNamespaceUri.equals(mainNamespace) && !schema.getElements().containsRow("")) continue; Element importElement = new Element("import", xsdNamespace); if (!currentNamespaceUri.equals("")) { Attribute namespaceAttr = new Attribute("namespace", currentNamespaceUri); importElement.setAttribute(namespaceAttr); } if (fileNameGenerator != null && !configuration.getSkipNamespaces().contains(currentNamespaceUri)) { String fileName = fileNameGenerator.getSchemaDocumentFileName(currentNamespaceUri, namespaceURIToPrefixMappings); Attribute schemaLocationAttr = new Attribute("schemaLocation", fileName); importElement.setAttribute(schemaLocationAttr); } elementSchema.addContent(importElement); } if (!targetNamespace.equals("")) { Attribute targetNamespaceAttr = new Attribute("targetNamespace", targetNamespace); elementSchema.setAttribute(targetNamespaceAttr); } SortedSet<SimpleType> sortedSimpleTypes = new TreeSet<>(new SimpleTypeComparator()); sortedSimpleTypes.addAll(schema.getSimpleTypes().values()); SortedSet<ComplexType> sortedComplexTypes = new TreeSet<>(new ComplexTypeComparator()); sortedComplexTypes.addAll(schema.getComplexTypes().values()); //CONTINUE FROM HERE: Generate sorted sets for SchemaElement and SchemaAttribute objects and use them where needed. Attribute elementFormDefault = new Attribute("elementFormDefault", "qualified"); elementSchema.setAttribute(elementFormDefault); Document resultingDocument = new Document(elementSchema); if (targetNamespace.equals(mainNamespace)) { //First, we declare global SimpleTypes. //If simpleTypesGlobal is true, any enumeration will be declared as a global simple type. //if not, simple types of complex types which have attributes but not children will be declared globally //(due to limitations of XSD, they may not be declared locally together with the attributes info) if (configuration.getSimpleTypesGlobal()) { for (SimpleType simpleType : sortedSimpleTypes) { if (!simpleType.isEnum() || simpleType.isEmpty()) continue; Element simpleTypeElement = generateSimpleType(simpleType, false, configuration, xsdNamespace); elementSchema.addContent(simpleTypeElement); } } else { for (ComplexType complexType : sortedComplexTypes) { SimpleType simpleType = complexType.getTextSimpleType(); if (complexType.getAttributeList().isEmpty() || !(complexType.getAutomaton().nodeCount() == 0) || !simpleType.isEnum() || simpleType.isEmpty()) continue; Element simpleTypeElement = generateSimpleType(simpleType, false, configuration, xsdNamespace); elementSchema.addContent(simpleTypeElement); } } //Global complexType elements are only generated in the main schema (i.e. the one whose targetNamespace is equal to mainNamespace) if (configuration.getComplexTypesGlobal()) { for (ComplexType complexType : sortedComplexTypes) { boolean hasNoChildren = complexType.getRegularExpression().equals(new EmptyRegularExpression()); boolean hasNoAttributes = complexType.getAttributeList().size() == 0; boolean hasNoComments = complexType.getComments().size() == 0; // boolean simpleTypeIsNotEmpty = !complexType.getTextSimpleType().isEmpty(); boolean simpleTypeIsWhiteSpaceOnlyOrEmpty = !(complexType.getTextSimpleType().isEmpty() || complexType.getTextSimpleType().consistOnlyOfWhitespaceCharacters()); if (hasNoChildren && hasNoAttributes && simpleTypeIsWhiteSpaceOnlyOrEmpty && hasNoComments) continue; //Because the elements which are linked to this ComplexType at our internal model //will be linked to an XSD simple type elsewhere, either a builtin or a custom one. Element complexTypeElement = generateComplexType(configuration, complexType, false, targetNamespace, namespaceURIToPrefixMappings, mainNamespace, xsdNamespace); elementSchema.addContent(complexTypeElement); } } } //If there are many namespaces and the workaround is disabled, we must declare global attributes. //If the targetNamespace is not the mainNamespace, we must declare all the attributes. //if the target namespace is the main namespace, we do not need to declare anything, because the complex types which hold the attributes //are also in the main namespace. if ((namespaceURIToPrefixMappings.size() - configuration.getSkipNamespaces().size()) > 1) { SortedMap<String, SchemaAttribute> globalAttributeCandidates = new TreeMap<>( schema.getAttributes().row(targetNamespace)); if (!targetNamespace.equals(mainNamespace) && !targetNamespace.equals("")) { globalAttributesLoop: for (Map.Entry<String, SchemaAttribute> schemaAttributeEntry : globalAttributeCandidates .entrySet()) { SchemaAttribute schemaAttribute = schemaAttributeEntry.getValue(); //First, we check if the attribute has been already declared when the workaround is disabled. //If so, we update the "use" property. //The type should have been already merged. if (!configuration.getStrictValidRootDefinitionWorkaround()) { List<Element> alreadyGeneratedAttributeElements = elementSchema.getChildren("attribute", xsdNamespace); for (int i = 0; i < alreadyGeneratedAttributeElements.size(); i++) { Element currentAttributeElement = alreadyGeneratedAttributeElements.get(i); if (currentAttributeElement.getAttributeValue("name") .equals(schemaAttribute.getName())) { continue globalAttributesLoop; } } } Element attributeOrAttributeGroupElement = generateAttribute(schemaAttribute, true, configuration, namespaceURIToPrefixMappings, targetNamespace, mainNamespace, schemaAttributeEntry.getKey(), xsdNamespace); elementSchema.addContent(attributeOrAttributeGroupElement); } } } //Now, we declare global elements. //An element will be declared globally if and only if: //1-elementsGlobal is true in the configuration //2-The element is a valid root //3-The element is in a namespace other than the main namespace. Note that the element WILL be surrounded by the corresponding group if the workaround is enabled. //Another important remark: Iterating over a set copy implies iterating over DISTINCT SchemaElements, so if two keys pointed to equal SchemaElements, we would generate it only once- SortedSet<SchemaElement> schemaElementsAtTargetNamespace = new TreeSet<>(new SchemaElementComparator()); schemaElementsAtTargetNamespace.addAll(schema.getElements().row(targetNamespace).values()); globalSchemaElementsLoop: for (SchemaElement schemaElement : schemaElementsAtTargetNamespace) { // if(!configuration.getElementsGlobal()&& // !schemaElement.isValidRoot()&& // (targetNamespace.equals(mainNamespace)||configuration.getStrictValidRootDefinitionWorkaround())) if (!configuration.getElementsGlobal() && !schemaElement.isValidRoot() && (targetNamespace.equals(mainNamespace))) continue; // for(Element currentElement:elementSchema.getContent(Filters.element("element",xsdNamespace))){ // if(schemaElement.getName().equals(currentElement.getAttributeValue("name"))) // continue globalSchemaElementsLoop; // } String possibleGroupName = schemaElement.getName() + configuration.getTypeNamesAncestorsSeparator() + schemaElement.getType().getName(); for (Element currentElement : elementSchema.getContent(Filters.element("group", xsdNamespace))) { if (possibleGroupName.equals(currentElement.getAttributeValue("name"))) continue globalSchemaElementsLoop; } Element elementOrGroupElement = generateElement(schemaElement, true, configuration, targetNamespace, mainNamespace, null, namespaceURIToPrefixMappings, xsdNamespace); if (elementOrGroupElement.getName().equals("element")) { for (Element currentElement : elementSchema.getChildren("element", xsdNamespace)) { if (schemaElement.getName().equals(currentElement.getAttributeValue("name"))) continue globalSchemaElementsLoop; } } elementSchema.addContent(elementOrGroupElement); } return resultingDocument; }
From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java
License:Apache License
/** * Method that generates a complexType tag, wherever it has to be generated and in the correct way * @param configuration the inference configuration * @param complexType the complex type to which the tag will be generated * @param anonymous whether this complex type must be anonymous (i.e. it must not have a 'name' attribute) * @param targetNamespace the target namespace which is currently being generated * @param namespaceURIToPrefixMappings solved mappings between namespace URIs and prefixes * @param mainNamespace main namespace/* w ww . j a va 2 s . com*/ * @param xsdNamespace namespace of the XML Schema * @return a JDOM2 {@link Element} which describes the complex type */ private Element generateComplexType(XSDInferenceConfiguration configuration, ComplexType complexType, boolean anonymous, String targetNamespace, Map<String, String> namespaceURIToPrefixMappings, String mainNamespace, Namespace xsdNamespace) { Element complexTypeElement = new Element("complexType", xsdNamespace); for (String commentOnComplexType : ImmutableSortedSet.copyOf(complexType.getComments())) { complexTypeElement.addContent(new Comment(commentOnComplexType)); } if (!anonymous) { Attribute complexTypeNameAttr = new Attribute("name", ""); complexTypeNameAttr.setValue(complexType.getName()); complexTypeElement.setAttribute(complexTypeNameAttr); } SimpleType simpleType = complexType.getTextSimpleType(); boolean hasChildren = !complexType.getRegularExpression().equals(new EmptyRegularExpression()); boolean hasNonWhitespaceSimpleContent = !simpleType.isEmpty() && !simpleType.consistOnlyOfWhitespaceCharacters(); if (hasChildren) { //Mixed complex type. As far as I know, XSD does not allow to constraint simple content on mixed types if (hasNonWhitespaceSimpleContent) { Attribute mixedAttr = new Attribute("mixed", ""); mixedAttr.setValue("true"); complexTypeElement.setAttribute(mixedAttr); } Element childrenContent = generateRegexpRepresentation(complexType.getRegularExpression(), configuration, targetNamespace, mainNamespace, complexType, namespaceURIToPrefixMappings, xsdNamespace); if (childrenContent.getName().equals("element")) { Element unwrappedChildrenContent = childrenContent; childrenContent = new Element("sequence", xsdNamespace); childrenContent.addContent(unwrappedChildrenContent); } complexTypeElement.addContent(childrenContent); List<Element> attributesInfo = generateAttributeList(complexType, targetNamespace, mainNamespace, configuration, namespaceURIToPrefixMappings, xsdNamespace); complexTypeElement.addContent(attributesInfo); } else if (complexType.getAttributeList().size() > 0 && !simpleType.isEmpty()) { Element simpleContentElement = new Element("simpleContent", xsdNamespace); Element extensionElement = new Element("extension", xsdNamespace); Attribute extensionBaseAttr = new Attribute("base", ""); String simpleTypeRepresentationName = complexType.getTextSimpleType() .getRepresentationName(configuration.getTypeNamesAncestorsSeparator()); if (!simpleTypeRepresentationName.contains(XSD_NAMESPACE_PREFIX) && !namespaceURIToPrefixMappings.get(mainNamespace).equals("")) { simpleTypeRepresentationName = namespaceURIToPrefixMappings.get(mainNamespace) + ":" + simpleTypeRepresentationName; } extensionBaseAttr.setValue(simpleTypeRepresentationName); extensionElement.setAttribute(extensionBaseAttr); List<Element> attributesInfo = generateAttributeList(complexType, targetNamespace, mainNamespace, configuration, namespaceURIToPrefixMappings, xsdNamespace); extensionElement.addContent(attributesInfo); simpleContentElement.addContent(extensionElement); complexTypeElement.addContent(simpleContentElement); } else if (complexType.getAttributeList().size() > 0) { List<Element> attributesInfo = generateAttributeList(complexType, targetNamespace, mainNamespace, configuration, namespaceURIToPrefixMappings, xsdNamespace); complexTypeElement.addContent(attributesInfo); } //If the complex type consists of a non empty simple type without either children or attributes, no complexType tag would be generated, so it is not handled here return complexTypeElement; }
From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java
License:Apache License
/** * Generates an element that describes an attribute (including name, type and optionality) * @param schemaAttribute the attribute to describe * @param isGlobal whether it will be declared globally or not * @param configuration the inference configuration * @param namespaceURIToPrefixMappings the solved mappings between namespace URIs and prefixes * @param targetNamespace the target namespace of the XSD that is being currently generated * @param mainNamespace the main namespace * @param schemaAttributeKey the key used at the {@link Schema} attributes structures, which will be * also used to name attribute groups used at inter-namespace importing and exporting when the * workaround is enabled.//from w w w. j ava 2 s . c o m * @param xsdNamespace the XSD namespace * @return a JDOM2 {@link Element} describing the attribute */ private Element generateAttribute(SchemaAttribute schemaAttribute, boolean isGlobal, XSDInferenceConfiguration configuration, Map<String, String> namespaceURIToPrefixMappings, String targetNamespace, String mainNamespace, String schemaAttributeKey, Namespace xsdNamespace) { Element attributeElement = new Element("attribute", xsdNamespace); boolean workaround = configuration.getStrictValidRootDefinitionWorkaround(); boolean belongsToSkippedNamespace = configuration.getSkipNamespaces().contains( schemaAttribute.getNamespace()) || schemaAttribute.getNamespace().equals(xsdNamespace.getURI()); if ((schemaAttribute.getNamespace().equals(mainNamespace) || schemaAttribute.getNamespace().equals("")) || (isGlobal && (!workaround))) { fillNormalAttributeElement(schemaAttribute, attributeElement, configuration, namespaceURIToPrefixMappings, targetNamespace, mainNamespace, isGlobal, xsdNamespace); return attributeElement; } else if (!isGlobal && (!workaround || belongsToSkippedNamespace)) { Attribute attributeRefAttr = new Attribute("ref", ""); String namespacePrefix = namespaceURIToPrefixMappings.get(schemaAttribute.getNamespace()); String attributeRefValue = schemaAttribute.getName(); if (!namespacePrefix.equals("")) attributeRefValue = namespacePrefix + ":" + attributeRefValue; attributeRefAttr.setValue(attributeRefValue); attributeElement.setAttribute(attributeRefAttr); return attributeElement; } else { Element attributeGroupElement = new Element("attributeGroup", xsdNamespace); if (isGlobal) { Attribute attributeGroupNameAttr = new Attribute("name", ""); attributeGroupNameAttr.setValue(schemaAttributeKey); attributeGroupElement.setAttribute(attributeGroupNameAttr); fillNormalAttributeElement(schemaAttribute, attributeElement, configuration, namespaceURIToPrefixMappings, targetNamespace, mainNamespace, isGlobal, xsdNamespace); attributeGroupElement.addContent(attributeElement); return attributeGroupElement; } else { Attribute attributeGroupRefAttr = new Attribute("ref", ""); String namespacePrefix = namespaceURIToPrefixMappings.get(schemaAttribute.getNamespace()); String refValue = ""; if (!namespacePrefix.equals("")) refValue = namespacePrefix + ":"; refValue += schemaAttributeKey; attributeGroupRefAttr.setValue(refValue); attributeGroupElement.setAttribute(attributeGroupRefAttr); Attribute attributeUseAttr = new Attribute("use", ""); String attributeUseValue = schemaAttribute.isOptional() ? "optional" : "required"; attributeUseAttr.setValue(attributeUseValue); attributeElement.setAttribute(attributeUseAttr); return attributeGroupElement; } } }
From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java
License:Apache License
/** * Fills an already created 'attribute' element (a future element called 'attribute' on the schema document) in a situation * such that it should have a name and a type, via 'type' attribute or a nested simpleType tag (depending on the configuration). * @param schemaAttribute the source SchemaAttribute * @param attributeElement the 'attribute' element * @param configuration the inference configuration * @param namespaceURIToPrefixMappings the resolved namespaceURIToPrefixMappings * @param targetNamespace the target namespace of the current schema * @param mainNamespace the default namespace of the inference * @param isGlobal whether the attribute is being declared at the top of the schema (global) or not (because it is local, it means, declared into its enclosing complex type). * @param xsdNamespace namespace URI for XML Schema Documents *//*from ww w .j a v a 2s . c om*/ private void fillNormalAttributeElement(SchemaAttribute schemaAttribute, Element attributeElement, XSDInferenceConfiguration configuration, Map<String, String> namespaceURIToPrefixMappings, String targetNamespace, String mainNamespace, boolean isGlobal, Namespace xsdNamespace) { Attribute attributeNameAttr = new Attribute("name", ""); attributeNameAttr.setValue(schemaAttribute.getName()); attributeElement.setAttribute(attributeNameAttr); if (configuration.getSimpleTypesGlobal() || !schemaAttribute.getSimpleType().isEnum()) { Attribute attributeTypeAttr = new Attribute("type", ""); String simpleTypeRepresentationName = schemaAttribute.getSimpleType() .getRepresentationName(configuration.getTypeNamesAncestorsSeparator()); if (!simpleTypeRepresentationName.startsWith(XSD_NAMESPACE_PREFIX) && !namespaceURIToPrefixMappings.get(mainNamespace).equals("")) { simpleTypeRepresentationName = namespaceURIToPrefixMappings.get(mainNamespace) + ":" + simpleTypeRepresentationName; } attributeTypeAttr.setValue(simpleTypeRepresentationName); if (!schemaAttribute.getSimpleType().isEmpty()) attributeElement.setAttribute(attributeTypeAttr); } else { Element simpleType = generateSimpleType(schemaAttribute.getSimpleType(), true, configuration, xsdNamespace); attributeElement.addContent(simpleType); } if (!(isGlobal && !configuration.getStrictValidRootDefinitionWorkaround())) { Attribute attributeUseAttr = new Attribute("use", ""); String attributeUseValue = schemaAttribute.isOptional() ? "optional" : "required"; attributeUseAttr.setValue(attributeUseValue); attributeElement.setAttribute(attributeUseAttr); } //If the namespace of the attribute (which should be equals to the target namespace in this method) //is prefixed, this attribute should be marked as qualified. //Globally declared attributes (which may only happen if they belong to an auxiliary namespace and the workaround is disabled) //are always qualified and it is prohibited to include the attribute 'form' (even with the value 'qualified'), so we omit it. if ((schemaAttribute.getNamespace() != null) && (!schemaAttribute.getNamespace().equals("")) && (!namespaceURIToPrefixMappings.get(schemaAttribute.getNamespace()).equals("")) && !(isGlobal && !configuration.getStrictValidRootDefinitionWorkaround())) { Attribute attribtueFormAttr = new Attribute("form", "qualified"); attributeElement.setAttribute(attribtueFormAttr); } }
From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java
License:Apache License
/** * Generates an element that describes a {@link SimpleType}, whenever it is necessary. * @param simpleType the simple type to describe * @param anonymous whether it must be anonymous (lack of a 'name' attribute) or not * @param configuration the inference configuration * @param xsdNamespace the XSD namespace * @return a JDOM2 {@link Element} that describes the {@link SimpleType} *//*from w w w.j av a 2 s . c o m*/ private Element generateSimpleType(SimpleType simpleType, boolean anonymous, XSDInferenceConfiguration configuration, Namespace xsdNamespace) { checkArgument(simpleType.isEnum()); checkArgument(!simpleType.isEmpty()); Element simpleTypeElement = new Element("simpleType", xsdNamespace); if (!anonymous) { Attribute simpleTypeNameAttr = new Attribute("name", ""); simpleTypeNameAttr .setValue(simpleType.getRepresentationName(configuration.getTypeNamesAncestorsSeparator())); simpleTypeElement.setAttribute(simpleTypeNameAttr); //System.err.println(simpleType.getRepresentationName("-")); } Element restrictionElement = new Element("restriction", xsdNamespace); Attribute restrictionBaseAttr = new Attribute("base", ""); restrictionBaseAttr.setValue(simpleType.getBuiltinType()); restrictionElement.setAttribute(restrictionBaseAttr); SortedSet<String> values = new TreeSet<>(); for (String value : simpleType) { values.add(value); } for (String value : values) { Element enumerationElement = new Element("enumeration", xsdNamespace); Attribute enumerationValueAttr = new Attribute("value", ""); enumerationValueAttr.setValue(value); enumerationElement.setAttribute(enumerationValueAttr); restrictionElement.addContent(enumerationElement); } simpleTypeElement.addContent(restrictionElement); return simpleTypeElement; }
From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java
License:Apache License
/** * It a generates a XSD representation of a {@link RegularExpression}. It is called recursively to generate * subexpressions until one of them is a {@link SchemaElement}, then, {@link XMLSchemaDocumentGenerator#generateElement(SchemaElement, boolean, XSDInferenceConfiguration, String, String, ComplexType, Map, Namespace)} * is called (so it is not possible to recures infinitely if the {@link RegularExpression} is well defined. * This method is built in a way that allows to append its results directly to a <i>complexType</i> tag without errors. * @param regexp the regular expression to represent * @param configuration the inference configuration * @param targetNamespace the target namespace of the XSD that is currently being generated * @param mainNamespace the main namespace * @param complexType the complex type that contains the regular expression * @param namespaceURIToPrefixMappings solved mappings between namespace URIs and prefixes * @param xsdNamespace XSD namespace// ww w . j av a 2 s. co m * @return a JDOM2 {@link Element} that describes the given {@link RegularExpression} */ private Element generateRegexpRepresentation(RegularExpression regexp, XSDInferenceConfiguration configuration, String targetNamespace, String mainNamespace, ComplexType complexType, Map<String, String> namespaceURIToPrefixMappings, Namespace xsdNamespace) { boolean isSchemaElement = regexp instanceof SchemaElement; boolean isMultipleRegularExpression = regexp instanceof MultipleRegularExpression; boolean isSingularRegularExpression = regexp instanceof SingularRegularExpression; boolean isEmptyRegularExpression = regexp instanceof EmptyRegularExpression; if (isSchemaElement) { return generateElement((SchemaElement) regexp, false, configuration, targetNamespace, mainNamespace, complexType, namespaceURIToPrefixMappings, xsdNamespace); } else if (isMultipleRegularExpression) { String elementName; if (regexp instanceof All) { elementName = "all"; } else if (regexp instanceof Choice) { elementName = "choice"; } else if (regexp instanceof Sequence) { elementName = "sequence"; } else { throw new IllegalArgumentException("Unknown kind of MultipleRegularExpression: " + regexp); } Element currentElement = new Element(elementName, xsdNamespace); for (int i = 0; i < regexp.elementCount(); i++) { Element currentElementChild = generateRegexpRepresentation(regexp.getElement(i), configuration, targetNamespace, mainNamespace, complexType, namespaceURIToPrefixMappings, xsdNamespace); if (regexp instanceof All && currentElementChild != null) { All regexpAsAll = (All) regexp; // If a test fails due to children order diferences unde <all/> tags, modify code around here to ensure that elements inside <all/> elements follow the same order. if (regexpAsAll.getMinOccurs() == 0) { Attribute minOccursAttribute = new Attribute("minOccurs", "0"); currentElementChild.setAttribute(minOccursAttribute); } } if (currentElementChild != null) { currentElement.addContent(currentElementChild); } } return currentElement; } else if (isSingularRegularExpression) { RegularExpression regexpChild = regexp.getElement(0); if (!((regexpChild instanceof MultipleRegularExpression) || (regexpChild instanceof SchemaElement))) { throw new IllegalArgumentException( "A child of a SingularRegularExpression may only be an SchemaElement or a MultipleRegularExpression. \nPrevious optimization steps should have avoided other combinations."); } Element generatedChild = generateRegexpRepresentation(regexpChild, configuration, targetNamespace, mainNamespace, complexType, namespaceURIToPrefixMappings, xsdNamespace); Attribute minOccursAttr = new Attribute("minOccurs", ""); Attribute maxOccursAttr = new Attribute("maxOccurs", ""); if (regexp instanceof Optional) { minOccursAttr.setValue("0"); maxOccursAttr.setValue("1"); } else if (regexp instanceof Repeated) { minOccursAttr.setValue("0"); maxOccursAttr.setValue("unbounded"); } else if (regexp instanceof RepeatedAtLeastOnce) { minOccursAttr.setValue("1"); maxOccursAttr.setValue("unbounded"); } else { throw new IllegalArgumentException("Unknown kind of SingularRegularExpression: " + regexp); } generatedChild.setAttribute(maxOccursAttr); generatedChild.setAttribute(minOccursAttr); return generatedChild; } else if (isEmptyRegularExpression) { return null; } throw new IllegalArgumentException("Unknown kind of RegularExpression: " + regexp); }
From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java
License:Apache License
/** * Generates an {@link Element} that describes the {@link SchemaElement} given. * @param schemaElement the schema element to be represented * @param isGlobal whether this element is being declared globally * @param configuration the inference configuration * @param targetNamespace the target namespace of the XSD that is currently being generated * @param mainNamespace the main namespace * @param parentComplexType the complex type under which this element may occur (if any). If it may not occur under any complex type (because it is a root element, for example), null must be passed. * @param namespaceURIToPrefixMappings solved mappings between namespace URIs and prefixes * @param xsdNamespace XSD namespace/*ww w. j ava2s .c o m*/ * @return a JDOM2 {@link Element} that describes the given {@link SchemaElement} */ private Element generateElement(SchemaElement schemaElement, boolean isGlobal, XSDInferenceConfiguration configuration, String targetNamespace, String mainNamespace, ComplexType parentComplexType, Map<String, String> namespaceURIToPrefixMappings, Namespace xsdNamespace) { //This variables and the isGlobal parameter will be used to calculate the conditions which will determine what element (of the future schema document) should be generated. boolean elementsGlobal = configuration.getElementsGlobal(); boolean namespacesDiffer = !mainNamespace.equals(schemaElement.getNamespace()); boolean workaround = configuration.getStrictValidRootDefinitionWorkaround(); boolean isValidRoot = schemaElement.isValidRoot(); boolean belongsToSkippedNamespace = configuration.getSkipNamespaces() .contains(schemaElement.getNamespace()); //These are the conditions boolean avoidWorkaround = isValidRoot || belongsToSkippedNamespace; boolean normalElement = (elementsGlobal && isGlobal) || (!elementsGlobal && isGlobal && namespacesDiffer && (!(workaround && !avoidWorkaround))) || (!elementsGlobal && !isGlobal && !namespacesDiffer) || (isGlobal && isValidRoot); boolean referencingAnElement = (elementsGlobal && !isGlobal) || (!elementsGlobal && !isGlobal && namespacesDiffer && (!(workaround && !avoidWorkaround))); boolean referencingAGroup = (!elementsGlobal && !isGlobal && namespacesDiffer && (workaround && !avoidWorkaround)); boolean grouppedElement = (!elementsGlobal && isGlobal && namespacesDiffer && (workaround && !avoidWorkaround)); if (referencingAnElement) { Element elementElement = new Element("element", xsdNamespace); Attribute elementRefAttr = new Attribute("ref", ""); String refValue = schemaElement.getName(); String prefix = namespaceURIToPrefixMappings.get(schemaElement.getNamespace()); if (!prefix.equals("")) { refValue = prefix + ":" + refValue; } elementRefAttr.setValue(refValue); elementElement.setAttribute(elementRefAttr); return elementElement; } else { String possibleGroupName = schemaElement.getName() + configuration.getTypeNamesAncestorsSeparator() + schemaElement.getType().getName(); if (normalElement || grouppedElement) { Element elementElement = new Element("element", xsdNamespace); Attribute elementNameAttr = new Attribute("name", ""); elementNameAttr.setValue(schemaElement.getName()); elementElement.setAttribute(elementNameAttr); boolean isSimpleElement = (schemaElement.getType() .getRegularExpression() instanceof EmptyRegularExpression); isSimpleElement = isSimpleElement && schemaElement.getType().getAttributeList().isEmpty(); isSimpleElement = isSimpleElement && !schemaElement.getType().getTextSimpleType().isEmpty(); if (isSimpleElement) { if (configuration.getSimpleTypesGlobal() || !schemaElement.getType().getTextSimpleType().isEnum()) { Attribute elementTypeAttr = new Attribute("type", ""); String typeStr = schemaElement.getType().getTextSimpleType() .getRepresentationName(configuration.getTypeNamesAncestorsSeparator()); if (!namespaceURIToPrefixMappings.get(mainNamespace).equals("") && !(typeStr.startsWith(XSD_NAMESPACE_PREFIX))) { typeStr = namespaceURIToPrefixMappings.get(mainNamespace) + ":" + typeStr; } elementTypeAttr.setValue(typeStr); elementElement.setAttribute(elementTypeAttr); } else { Element elementSimpleTypeElement = generateSimpleType( schemaElement.getType().getTextSimpleType(), true, configuration, xsdNamespace); elementElement.addContent(elementSimpleTypeElement); } } else { if (configuration.getComplexTypesGlobal()) { Attribute elementTypeAttr = new Attribute("type", ""); String typeStr = schemaElement.getType().getName(); if (!namespaceURIToPrefixMappings.get(mainNamespace).equals("")) { typeStr = namespaceURIToPrefixMappings.get(mainNamespace) + ":" + typeStr; } elementTypeAttr.setValue(typeStr); elementElement.setAttribute(elementTypeAttr); } else { Element elementComplexTypeElement = generateComplexType(configuration, schemaElement.getType(), true, targetNamespace, namespaceURIToPrefixMappings, mainNamespace, xsdNamespace); elementElement.addContent(elementComplexTypeElement); } } if (grouppedElement) { Element elementGroup = new Element("group", xsdNamespace); Attribute groupNameAttr = new Attribute("name", ""); groupNameAttr.setValue(possibleGroupName); elementGroup.setAttribute(groupNameAttr); Element sequenceInGroupElement = new Element("sequence", xsdNamespace); sequenceInGroupElement.addContent(elementElement); elementGroup.addContent(sequenceInGroupElement); return elementGroup; } else { return elementElement; } } else if (referencingAGroup) { Element elementGroup = new Element("group", xsdNamespace); Attribute groupRefAttr = new Attribute("ref", ""); String groupQName = possibleGroupName; String namespacePrefix = namespaceURIToPrefixMappings.get(schemaElement.getNamespace()); if (!namespacePrefix.equals("")) groupQName = namespacePrefix + ":" + groupQName; groupRefAttr.setValue(groupQName); elementGroup.setAttribute(groupRefAttr); return elementGroup; } else { throw new IllegalArgumentException("The parameters given have lead to an invalid situation"); } } }
From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.statisticsgeneration.StatisticResultsDocGeneratorImpl.java
License:Apache License
/** * This method generates an element which contains the representation of a basic statistics entry. Depending on which basic statistics entry is going to * be represented, the element could have a different name, different identifying attributes(like path, name, namespace, value...). * @param elementName the name of the generated element * @param path the path where the entry comes from (if it comes from a path), if it is not null, a 'path' attribute is generated with this value, else, no 'path' attribute is generated. * @param name the name of the source node (if it comes from a complex type statistics entry), if it is not null, a 'name' attribute is generated with this value, else, no 'name' attribute is generated. * @param namespace the namespace of the source node (if it comes from a complex type statistics entry), if it is not null, a 'namespace' attribute is generated with this value, else, no 'namespace' attribute is generated. * @param value the value which the entry is related to (if it is related to a value), if it is not null, a 'value' child element with this value is generated (and xml:space attribute set to 'preserve'), else, no 'value' element is generated. * @param entry the entry to represent// www.j a v a2 s .c o m * @param generateConditionedStatistics flag to indicate whether conditioned statistics info should be generated and attached to the element * @param generateNonZeroRatio flag to indicate whether non zero ratio info should be generated and attached to the element * @return the representation of the BasicStatisticsEntry object, as a JDOM2 element */ protected Element generateBasicStatisticsEntryBasedElement(String elementName, String path, String name, String namespace, String value, BasicStatisticsEntry entry, boolean generateConditionedStatistics, boolean generateNonZeroRatio) { Element generatedElement = new Element(elementName, STATISTICS_NAMESPACE); if (path != null) { Attribute pathAttr = new Attribute("path", path); generatedElement.setAttribute(pathAttr); } if (value != null) { Element valueElement = new Element("value", STATISTICS_NAMESPACE); valueElement.setText(value); Attribute spaceAttribute = new Attribute("space", "preserve", Namespace.XML_NAMESPACE); valueElement.setAttribute(spaceAttribute); generatedElement.addContent(valueElement); } if (name != null) { Attribute nameAttr = new Attribute("name", name); generatedElement.setAttribute(nameAttr); } if (namespace != null) { Attribute namespaceAttr = new Attribute("namespace", namespace); generatedElement.setAttribute(namespaceAttr); } // Element averageElement = new Element("average", STATISTICS_NAMESPACE); // averageElement.setText(entry.getAverage()+""); // atPathElement.addContent(averageElement); Attribute averageAttribute = new Attribute("average", roundingFormat.format(entry.getAverage()) + ""); generatedElement.setAttribute(averageAttribute); Set<ValueAndFrequency> mode = entry.getMode(); if (!mode.isEmpty()) { Element modeElement = new Element("modes", STATISTICS_NAMESPACE); for (ValueAndFrequency modeValue : mode) { Element valueElement = new Element("modeValue", STATISTICS_NAMESPACE); valueElement.setText(roundingFormat.format(modeValue.getValue()) + ""); Attribute valueFreqAttr = new Attribute("frequency", modeValue.getFrequency() + ""); valueElement.setAttribute(valueFreqAttr); modeElement.addContent(valueElement); } generatedElement.addContent(modeElement); } // Element maxElement=new Element("max",STATISTICS_NAMESPACE); // ValueAndFrequency max = entry.getMax(); // maxElement.setText(max.getValue()+""); // Attribute maxFreqAttr = new Attribute("frequency", max.getFrequency()+""); // maxElement.setAttribute(maxFreqAttr); // generatedElement.addContent(maxElement); Attribute maxAttribute = new Attribute("max", roundingFormat.format(entry.getMax().getValue()) + ""); generatedElement.setAttribute(maxAttribute); Attribute maxFrequencyAttribute = new Attribute("frequencyOfMax", entry.getMax().getFrequency() + ""); generatedElement.setAttribute(maxFrequencyAttribute); // Element minElement=new Element("min",STATISTICS_NAMESPACE); // ValueAndFrequency min = entry.getMin(); // minElement.setText(min.getValue()+""); // Attribute minFreqAttr = new Attribute("frequency", min.getFrequency()+""); // minElement.setAttribute(minFreqAttr); // generatedElement.addContent(minElement); Attribute minAttribute = new Attribute("min", roundingFormat.format(entry.getMin().getValue()) + ""); generatedElement.setAttribute(minAttribute); Attribute minFrequencyAttribute = new Attribute("frequencyOfMin", entry.getMin().getFrequency() + ""); generatedElement.setAttribute(minFrequencyAttribute); // Element varianceElement = new Element("variance", STATISTICS_NAMESPACE); // varianceElement.setText(entry.getVariance()+""); // generatedElement.addContent(varianceElement); Attribute varianceAttribute = new Attribute("variance", roundingFormat.format(entry.getVariance()) + ""); generatedElement.setAttribute(varianceAttribute); // Element standardDeviationAverageRatioElement = new Element("standardDeviationAverageRatio", STATISTICS_NAMESPACE); // standardDeviationAverageRatioElement.setText(entry.getStandardDeviationAverageRatio()+""); // generatedElement.addContent(standardDeviationAverageRatioElement); Attribute standardDeviationAverageRatioAttribute = new Attribute("standardDeviationAverageRatio", roundingFormat.format(entry.getStandardDeviationAverageRatio()) + ""); generatedElement.setAttribute(standardDeviationAverageRatioAttribute); if (generateConditionedStatistics) { Attribute conditionedAverageAttribute = new Attribute("conditionedAverage", roundingFormat.format(entry.getConditionedAverage()) + ""); generatedElement.setAttribute(conditionedAverageAttribute); Attribute conditionedVarianceAttribute = new Attribute("conditionedVariance", roundingFormat.format(entry.getConditionedVariance()) + ""); generatedElement.setAttribute(conditionedVarianceAttribute); Attribute conditionedStandardDeviationAverageRatioAttribute = new Attribute( "conditionedStandardDeviationAverageRatio", roundingFormat.format(entry.getConditionedStandardDeviationAverageRatio()) + ""); generatedElement.setAttribute(conditionedStandardDeviationAverageRatioAttribute); // Element conditionedStandardDeviationAverageRatioElement = new Element("conditionedStandardDeviationAverageRatio", STATISTICS_NAMESPACE); // conditionedStandardDeviationAverageRatioElement.setText(entry.getConditionedStandardDeviationAverageRatio()+""); // generatedElement.addContent(conditionedStandardDeviationAverageRatioElement); // // Element conditionedAverageElement = new Element("conditionedAverage", STATISTICS_NAMESPACE); // conditionedAverageElement.setText(entry.getConditionedAverage()+""); // generatedElement.addContent(conditionedAverageElement); // // Element conditionedVarianceElement = new Element("conditionedVariance", STATISTICS_NAMESPACE); // conditionedVarianceElement.setText(entry.getConditionedVariance()+""); // generatedElement.addContent(conditionedVarianceElement); } if (generateNonZeroRatio) { Attribute nonZeroRatioAttribute = new Attribute("presenceRatio", roundingFormat.format(entry.getNonZeroRatio()) + ""); generatedElement.setAttribute(nonZeroRatioAttribute); // Element nonZeroRatio = new Element("presenceRatio", STATISTICS_NAMESPACE); // nonZeroRatio.setText(""+entry.getNonZeroRatio()); // generatedElement.addContent(nonZeroRatio); } // Element totalElement = new Element("total", STATISTICS_NAMESPACE); // totalElement.setText(entry.getTotal()+""); // generatedElement.addContent(totalElement); Attribute totalAttribute = new Attribute("total", roundingFormat.format(entry.getTotal()) + ""); generatedElement.setAttribute(totalAttribute); return generatedElement; }
From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.statisticsgeneration.StatisticResultsDocGeneratorImpl.java
License:Apache License
/** * This method generates an element with the root occurrences info * @param rootElementsInfo the root elements info of the statistics * @return An element with all the information described */// w ww . j av a 2 s .co m protected Element generateRootElementsOccurrencesElement(Map<SchemaElement, Integer> rootElementsInfo) { Element element = new Element("rootElementsInfo", STATISTICS_NAMESPACE); for (SchemaElement rootElement : rootElementsInfo.keySet()) { Element currentRootInfoElement = new Element("rootElement", STATISTICS_NAMESPACE); Attribute currentRootName = new Attribute("name", rootElement.getName()); currentRootInfoElement.setAttribute(currentRootName); Attribute currentRootNamespace = new Attribute("namespace", rootElement.getNamespace()); currentRootInfoElement.setAttribute(currentRootNamespace); Attribute currentRootOccurrences = new Attribute("occurrences", rootElementsInfo.get(rootElement).toString()); currentRootInfoElement.setAttribute(currentRootOccurrences); element.addContent(currentRootInfoElement); } return element; }
From source file:eu.himeros.hocr.HocrInfoAggregator.java
License:Open Source License
private void makeCompliantHocr() { xpath = XPathFactory.instance().compile("//ns:span[@id|@idx]", Filters.element(), null, Namespace.getNamespace("ns", "http://www.w3.org/1999/xhtml")); List<Element> elements = xpath.evaluate(root); int spanId = 0; for (Element span : elements) { if (span.getAttribute("idx") != null) { try { span = span.getChildren().get(0); } catch (Exception ex) { // }/* w ww .j a va 2s . c o m*/ } LinkedList<Attribute> attributeLl = new LinkedList(span.getParentElement().getAttributes()); attributeLl.addFirst(new Attribute("id", "w_" + spanId++)); span.getParentElement().setAttributes(attributeLl); String[] suggestions = null; String title = span.getAttributeValue("title"); if (title != null) { suggestions = title.split(" "); } if (suggestions == null) { suggestions = new String[] { "" }; } Element ins = new Element("ins", xmlns); ins.setAttribute("class", "alt"); ins.setAttribute("title", makeNlp(span.getAttributeValue("class"))); ins.setText(span.getText()); span.removeContent(); span.addContent(ins); span.setAttribute("class", "alternatives"); span.removeAttribute("uc"); span.removeAttribute("occ"); span.removeAttribute("title"); span.removeAttribute("anchor"); span.removeAttribute("anchor-id"); span.removeAttribute("id"); span.getParentElement().removeAttribute("idx"); span.removeAttribute("whole"); span.getParentElement().removeAttribute("whole"); if (title == null || "".equals(title)) { continue; } double score = 0.90; for (String suggestion : suggestions) { if (suggestion == null || "".equals(suggestion)) { continue; } Element del = new Element("del", xmlns); del.setAttribute("title", "nlp " + String.format("%.2f", score).replaceAll(",", ".")); score = score - 0.01; suggestion = suggestion.replaceAll(l1PunctMarkFilter, ""); Matcher leftMatcher = l1LeftPunctMarkPattern.matcher(ins.getText()); if (leftMatcher.matches()) { suggestion = leftMatcher.group(1) + suggestion; } Matcher rightMatcher = l1RightPunctMarkPattern.matcher(ins.getText()); if (rightMatcher.matches()) { String ngtSymbol = ""; if (suggestion.endsWith("\u261a")) { ngtSymbol = "\u261a"; suggestion = suggestion.substring(0, suggestion.length() - 1); } suggestion = suggestion + rightMatcher.group(1) + ngtSymbol; } ///!!!! if (suggestion.endsWith("\u261a") && ins.getParentElement().getParentElement() .getAttributeValue("lang", Namespace.XML_NAMESPACE) != null) { String buff = suggestion.substring(0, suggestion.length() - 1); sa.align(buff, ins.getText()); double sim = 1 - sa.getEditDistance() / Math.max((double) buff.length(), (double) ins.getText().length()); if (sim > 0.6) { suggestion = ins.getText() + "\u261b"; ins.setText(buff); ins.setAttribute("title", "nlp 0.70"); } } del.addContent(suggestion); span.addContent(del); } } }