Example usage for org.jdom2 Namespace equals

List of usage examples for org.jdom2 Namespace equals

Introduction

In this page you can find the example usage for org.jdom2 Namespace equals.

Prototype

@Override
public boolean equals(final Object ob) 

Source Link

Document

This tests for equality - Two Namespaces are equal if and only if their URIs are byte-for-byte equals.

Usage

From source file:com.sun.syndication.io.impl.RSS10Parser.java

License:Open Source License

/**
 * Indicates if a JDom document is an RSS instance that can be parsed with the parser.
 * <p/>//from w w  w  . ja  va 2  s  .c  o  m
 * It checks for RDF ("http://www.w3.org/1999/02/22-rdf-syntax-ns#") and
 * RSS ("http://purl.org/rss/1.0/") namespaces being defined in the root element.
 *
 * @param document document to check if it can be parsed with this parser implementation.
 * @return <b>true</b> if the document is RSS1., <b>false</b> otherwise.
 */
public boolean isMyType(Document document) {
    boolean ok = false;

    Element rssRoot = document.getRootElement();
    Namespace defaultNS = rssRoot.getNamespace();
    List additionalNSs = rssRoot.getAdditionalNamespaces();

    ok = defaultNS != null && defaultNS.equals(getRDFNamespace());
    if (ok) {
        if (additionalNSs == null) {
            ok = false;
        } else {
            ok = false;
            for (int i = 0; !ok && i < additionalNSs.size(); i++) {
                ok = getRSSNamespace().equals(additionalNSs.get(i));
            }
        }
    }
    return ok;
}

From source file:com.sun.syndication.io.impl.RSS20wNSParser.java

License:Open Source License

public boolean isMyType(Document document) {
    Element rssRoot = document.getRootElement();
    Namespace defaultNS = rssRoot.getNamespace();
    boolean ok = defaultNS != null && defaultNS.equals(getRSSNamespace());
    if (ok) {/*from  w  w w  .  j a v a  2 s  .  c  o  m*/
        ok = super.isMyType(document);
    }
    return ok;
}

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.
 * // w ww  .  j  av  a2s  .c o  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:org.artifactory.version.converter.NamespaceConverter.java

License:Open Source License

@Override
@SuppressWarnings({ "unchecked" })
public void convert(Document doc) {
    // change the xsd uri and schema location
    String currentXsdUri = ArtifactoryConfigVersion.getCurrent().getXsdUri();
    String currentXsdLocation = ArtifactoryConfigVersion.getCurrent().getXsdLocation();
    Namespace ns = Namespace.getNamespace(currentXsdUri);
    Element root = doc.getRootElement();
    // Check that schema instance namespace is there before adding schema location...
    Namespace schemaInstanceNS = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    List<Namespace> namespaces = root.getAdditionalNamespaces();
    boolean hasSchemaInstanceNS = false;
    for (Namespace namespace : namespaces) {
        // The equality is only on URI so hardcoded prefix does not impact
        if (namespace.equals(schemaInstanceNS)) {
            hasSchemaInstanceNS = true;/*from www .ja va2  s  .c o  m*/
        }
    }
    if (!hasSchemaInstanceNS) {
        root.addNamespaceDeclaration(schemaInstanceNS);
    }
    root.setAttribute("schemaLocation", currentXsdUri + " " + currentXsdLocation, schemaInstanceNS);

    changeNameSpace(root, ns);
}

From source file:org.mycore.common.xml.MCRXPathBuilder.java

License:Open Source License

/**
 * Returns the namespace prefix for this element, followed by a ":", or the empty string if no namespace prefix known.
 *//* w ww.j  av a2s. c  om*/
public static String getNamespacePrefix(Element element) {
    Namespace nsElement = element.getNamespace();
    for (Namespace ns : MCRConstants.getStandardNamespaces())
        if (ns.equals(nsElement))
            return ns.getPrefix() + ":";

    String prefix = nsElement.getPrefix();
    if ((prefix != null) && !prefix.isEmpty())
        return prefix + ":";
    else
        return "";
}

From source file:org.mycore.frontend.editor.MCREditorSubmission.java

License:Open Source License

private String getNamespacePrefix(Namespace ns) {
    if (ns == null || ns.equals(Namespace.NO_NAMESPACE)) {
        return "";
    }// w w w.  j av  a  2  s  .c o m
    for (String key : nsMap.keySet()) {
        if (ns.equals(nsMap.get(key))) {
            return key + ":";
        }
    }
    String msg = "Namespace " + ns.getURI()
            + " used in editor source input, but not declared in editor definition. Using: " + ns.getPrefix();
    LOGGER.warn(msg);
    return ns.getPrefix() + ":";
}

From source file:org.mycore.frontend.editor.MCREditorSubmission.java

License:Open Source License

private void buildTargetXML() {
    Element root;// w w  w  . j  a  v  a  2  s  . co m
    if (variables.size() > 0) {
        root = buildElement(((MCREditorVariable) variables.get(0)).getPathElements()[0]);
    } else {
        root = buildElement(rootName.replace("/", ""));
    }

    for (Object variable : variables) {
        MCREditorVariable var = (MCREditorVariable) variable;

        Element parent = root;
        String[] elements = var.getPathElements();

        for (int j = 1; j < elements.length; j++) {
            String name = elements[j];

            if (name.endsWith("]")) {
                int pos = name.lastIndexOf("[");
                name = name.substring(0, pos) + "_XXX_" + name.substring(pos + 1, name.length() - 1);
            }

            Namespace ns = getNamespace(name);
            if (!ns.equals(Namespace.NO_NAMESPACE)) {
                name = name.substring(name.indexOf(":") + 1);
            }
            Element child = parent.getChild(name, ns);

            if (child == null) {
                child = new Element(name, ns);
                parent.addContent(child);
            }

            parent = child;
        }

        Object node;

        if (!var.isAttribute()) {
            parent.addContent(var.getValue());
            node = parent;
        } else {
            LOGGER.debug("Setting attribute " + var.getPath() + " = " + var.getValue());
            setAttribute(parent, var.getAttributeName(), var.getValue());
            node = parent.getAttribute(var.getAttributeName());
        }

        FileItem file = parms == null ? null : parms.getFileItem(var.getPath());

        if (file != null) {
            file2node.put(file, node);
            node2file.put(node, file);
        }
    }

    renameRepeatedElements(root);
    xml = new Document(root);
}

From source file:org.mycore.frontend.editor.MCREditorSubmission.java

License:Open Source License

/**
 * Builds a new XML element for data output. The name may contain a
 * namespace prefix, which is resolved to a namespace then.
 *//*w w  w. ja v a  2 s. c o m*/
private Element buildElement(String name) {
    Namespace ns = getNamespace(name);
    if (!ns.equals(Namespace.NO_NAMESPACE)) {
        name = name.substring(name.indexOf(":") + 1);
    }
    return new Element(name, ns);
}

From source file:org.mycore.frontend.editor.MCREditorSubmission.java

License:Open Source License

/**
 * Sets attribute value of the given parent element. The name may contain a
 * namespace prefix, which is resolved to a namespace then.
 *//*  w  w w .  j av  a  2s .  c om*/
private void setAttribute(Element parent, String name, String value) {
    Namespace ns = getNamespace(name);
    if (!ns.equals(Namespace.NO_NAMESPACE)) {
        name = name.substring(name.indexOf(":") + 1);
    }
    parent.setAttribute(name, value, ns);
}

From source file:org.rometools.feed.module.mediarss.io.RSS20YahooParser.java

License:Open Source License

/**
 * Indicates if a JDom document is an RSS instance that can be parsed with the parser.
 * <p/>//from  w w  w.  ja va2s  .c  om
 * It checks for RDF ("http://www.w3.org/1999/02/22-rdf-syntax-ns#") and
 * RSS ("http://purl.org/rss/1.0/") namespaces being defined in the root element.
 *
 * @param document document to check if it can be parsed with this parser implementation.
 * @return <b>true</b> if the document is RSS1., <b>false</b> otherwise.
 */
public boolean isMyType(Document document) {
    boolean ok = false;

    Element rssRoot = document.getRootElement();
    Namespace defaultNS = rssRoot.getNamespace();
    List additionalNSs = rssRoot.getAdditionalNamespaces();

    ok = (defaultNS != null) && defaultNS.equals(getRSSNamespace());

    return ok;
}