Example usage for javax.xml.namespace QName getNamespaceURI

List of usage examples for javax.xml.namespace QName getNamespaceURI

Introduction

In this page you can find the example usage for javax.xml.namespace QName getNamespaceURI.

Prototype

public String getNamespaceURI() 

Source Link

Document

Get the Namespace URI of this QName.

Usage

From source file:com.evolveum.midpoint.prism.xml.GlobalDynamicNamespacePrefixMapper.java

@Override
public QName setQNamePrefixExplicit(QName qname) {
    String namespace = qname.getNamespaceURI();
    String prefix = getPrefixExplicit(namespace);
    if (prefix == null) {
        return qname;
    }//from w  ww .j  a v  a  2s .  c  o m
    return new QName(qname.getNamespaceURI(), qname.getLocalPart(), prefix);
}

From source file:org.fcrepo.serialization.JcrXmlSerializer.java

private void validateJCRXML(final File file) throws InvalidSerializationFormatException, IOException {
    int depth = 0;
    try (final FileInputStream fis = new FileInputStream(file)) {
        final XMLEventReader reader = XMLInputFactory.newFactory().createXMLEventReader(fis);
        while (reader.hasNext()) {
            final XMLEvent event = reader.nextEvent();
            if (event.isStartElement()) {
                depth++;/*from  w ww.j  a va2s. com*/
                final StartElement startElement = event.asStartElement();
                final Attribute nameAttribute = startElement
                        .getAttributeByName(new QName("http://www.jcp.org/jcr/sv/1.0", "name"));
                if (depth == 1 && nameAttribute != null && "jcr:content".equals(nameAttribute.getValue())) {
                    throw new InvalidSerializationFormatException(
                            "Cannot import JCR/XML starting with content node.");
                }
                if (depth == 1 && nameAttribute != null && "jcr:frozenNode".equals(nameAttribute.getValue())) {
                    throw new InvalidSerializationFormatException("Cannot import historic versions.");
                }
                final QName name = startElement.getName();
                if (!(name.getNamespaceURI().equals("http://www.jcp.org/jcr/sv/1.0")
                        && (name.getLocalPart().equals("node") || name.getLocalPart().equals("property")
                                || name.getLocalPart().equals("value")))) {
                    throw new InvalidSerializationFormatException(
                            "Unrecognized element \"" + name.toString() + "\", in import XML.");
                }
            } else {
                if (event.isEndElement()) {
                    depth--;
                }
            }
        }
        reader.close();
    } catch (XMLStreamException e) {
        throw new InvalidSerializationFormatException(
                "Unable to parse XML" + (e.getMessage() != null ? " (" + e.getMessage() + ")." : "."));
    }
}

From source file:com.twinsoft.convertigo.engine.migration.Migration7_0_0.java

public static void migrate(final String projectName) {
    try {/*from  w  ww.  j a v a2  s  .  c  o m*/
        Map<String, Reference> referenceMap = new HashMap<String, Reference>();
        XmlSchema projectSchema = null;

        Project project = Engine.theApp.databaseObjectsManager.getOriginalProjectByName(projectName, false);

        // Copy all xsd files to project's xsd directory
        File destDir = new File(project.getXsdDirPath());
        copyXsdOfProject(projectName, destDir);

        String projectWsdlFilePath = Engine.PROJECTS_PATH + "/" + projectName + "/" + projectName + ".wsdl";
        File wsdlFile = new File(projectWsdlFilePath);

        String projectXsdFilePath = Engine.PROJECTS_PATH + "/" + projectName + "/" + projectName + ".xsd";
        File xsdFile = new File(projectXsdFilePath);

        if (xsdFile.exists()) {
            // Load project schema from old XSD file
            XmlSchemaCollection collection = new XmlSchemaCollection();
            collection.setSchemaResolver(new DefaultURIResolver() {
                public InputSource resolveEntity(String targetNamespace, String schemaLocation,
                        String baseUri) {
                    // Case of a c8o project location
                    if (schemaLocation.startsWith("../") && schemaLocation.endsWith(".xsd")) {
                        try {
                            String targetProjectName = schemaLocation.substring(3,
                                    schemaLocation.indexOf("/", 3));
                            File pDir = new File(Engine.PROJECTS_PATH + "/" + targetProjectName);
                            if (pDir.exists()) {
                                File pFile = new File(Engine.PROJECTS_PATH + schemaLocation.substring(2));
                                // Case c8o project is already migrated
                                if (!pFile.exists()) {
                                    Document doc = Engine.theApp.schemaManager
                                            .getSchemaForProject(targetProjectName).getSchemaDocument();
                                    DOMSource source = new DOMSource(doc);
                                    StringWriter writer = new StringWriter();
                                    StreamResult result = new StreamResult(writer);
                                    TransformerFactory.newInstance().newTransformer().transform(source, result);
                                    StringReader reader = new StringReader(writer.toString());
                                    return new InputSource(reader);
                                }
                            }
                            return null;
                        } catch (Exception e) {
                            Engine.logDatabaseObjectManager
                                    .warn("[Migration 7.0.0] Unable to find schema location \"" + schemaLocation
                                            + "\"", e);
                            return null;
                        }
                    } else if (schemaLocation.indexOf("://") == -1 && schemaLocation.endsWith(".xsd")) {
                        return super.resolveEntity(targetNamespace, schemaLocation,
                                Engine.PROJECTS_PATH + "/" + projectName);
                    }
                    return super.resolveEntity(targetNamespace, schemaLocation, baseUri);
                }

            });
            projectSchema = SchemaUtils.loadSchema(new File(projectXsdFilePath), collection);
            ConvertigoError.updateXmlSchemaObjects(projectSchema);
            SchemaMeta.setCollection(projectSchema, collection);

            for (Connector connector : project.getConnectorsList()) {
                for (Transaction transaction : connector.getTransactionsList()) {
                    try {
                        // Migrate transaction in case of a Web Service consumption project
                        if (transaction instanceof XmlHttpTransaction) {
                            XmlHttpTransaction xmlHttpTransaction = (XmlHttpTransaction) transaction;
                            String reqn = xmlHttpTransaction.getResponseElementQName();
                            if (!reqn.equals("")) {
                                boolean useRef = reqn.indexOf(";") == -1;
                                // Doc/Literal case
                                if (useRef) {
                                    try {
                                        String[] qn = reqn.split(":");
                                        QName refName = new QName(
                                                projectSchema.getNamespaceContext().getNamespaceURI(qn[0]),
                                                qn[1]);
                                        xmlHttpTransaction.setXmlElementRefAffectation(new XmlQName(refName));
                                    } catch (Exception e) {
                                    }
                                }
                                // RPC case
                                else {
                                    int index, index2;
                                    try {
                                        index = reqn.indexOf(";");
                                        String opName = reqn.substring(0, index);
                                        if ((index2 = reqn.indexOf(";", index + 1)) != -1) {
                                            String eltName = reqn.substring(index + 1, index2);
                                            String eltType = reqn.substring(index2 + 1);
                                            String[] qn = eltType.split(":");

                                            QName typeName = new QName(
                                                    projectSchema.getNamespaceContext().getNamespaceURI(qn[0]),
                                                    qn[1]);
                                            String responseElementQName = opName + ";" + eltName + ";" + "{"
                                                    + typeName.getNamespaceURI() + "}"
                                                    + typeName.getLocalPart();
                                            xmlHttpTransaction.setResponseElementQName(responseElementQName);
                                        }
                                    } catch (Exception e) {
                                    }
                                }
                            }
                        }

                        // Retrieve required XmlSchemaObjects for transaction
                        QName requestQName = new QName(project.getTargetNamespace(),
                                transaction.getXsdRequestElementName());
                        QName responseQName = new QName(project.getTargetNamespace(),
                                transaction.getXsdResponseElementName());
                        LinkedHashMap<QName, XmlSchemaObject> map = new LinkedHashMap<QName, XmlSchemaObject>();
                        XmlSchemaWalker dw = XmlSchemaWalker.newDependencyWalker(map, true, false);
                        dw.walkByElementRef(projectSchema, requestQName);
                        dw.walkByElementRef(projectSchema, responseQName);

                        // Create transaction schema
                        String targetNamespace = projectSchema.getTargetNamespace();
                        String prefix = projectSchema.getNamespaceContext().getPrefix(targetNamespace);
                        XmlSchema transactionSchema = SchemaUtils.createSchema(prefix, targetNamespace,
                                XsdForm.unqualified.name(), XsdForm.unqualified.name());

                        // Add required prefix declarations
                        List<String> nsList = new LinkedList<String>();
                        for (QName qname : map.keySet()) {
                            String nsURI = qname.getNamespaceURI();
                            if (!nsURI.equals(Constants.URI_2001_SCHEMA_XSD)) {
                                if (!nsList.contains(nsURI)) {
                                    nsList.add(nsURI);
                                }
                            }
                            String nsPrefix = qname.getPrefix();
                            if (!nsURI.equals(targetNamespace)) {
                                NamespaceMap nsMap = SchemaUtils.getNamespaceMap(transactionSchema);
                                if (nsMap.getNamespaceURI(nsPrefix) == null) {
                                    nsMap.add(nsPrefix, nsURI);
                                    transactionSchema.setNamespaceContext(nsMap);
                                }
                            }
                        }

                        // Add required imports
                        for (String namespaceURI : nsList) {
                            XmlSchemaObjectCollection includes = projectSchema.getIncludes();
                            for (int i = 0; i < includes.getCount(); i++) {
                                XmlSchemaObject xmlSchemaObject = includes.getItem(i);
                                if (xmlSchemaObject instanceof XmlSchemaImport) {
                                    if (((XmlSchemaImport) xmlSchemaObject).getNamespace()
                                            .equals(namespaceURI)) {

                                        // do not allow import with same ns !
                                        if (namespaceURI.equals(project.getTargetNamespace()))
                                            continue;

                                        String location = ((XmlSchemaImport) xmlSchemaObject)
                                                .getSchemaLocation();

                                        // This is a convertigo project reference
                                        if (location.startsWith("../")) {
                                            // Copy all xsd files to xsd directory
                                            String targetProjectName = location.substring(3,
                                                    location.indexOf("/", 3));
                                            copyXsdOfProject(targetProjectName, destDir);
                                        }

                                        // Add reference
                                        addReferenceToMap(referenceMap, namespaceURI, location);

                                        // Add import
                                        addImport(transactionSchema, namespaceURI, location);
                                    }
                                }
                            }
                        }

                        QName responseTypeQName = new QName(project.getTargetNamespace(),
                                transaction.getXsdResponseTypeName());

                        // Add required schema objects
                        for (QName qname : map.keySet()) {
                            if (qname.getNamespaceURI().equals(targetNamespace)) {
                                XmlSchemaObject ob = map.get(qname);

                                if (qname.getLocalPart().startsWith("ConvertigoError"))
                                    continue;
                                transactionSchema.getItems().add(ob);

                                // Add missing response error element and attributes
                                if (qname.equals(responseTypeQName)) {
                                    Transaction.addSchemaResponseObjects(transactionSchema,
                                            (XmlSchemaComplexType) ob);
                                }
                            }
                        }

                        // Add missing ResponseType (with document)
                        if (map.containsKey(responseTypeQName)) {
                            Transaction.addSchemaResponseType(transactionSchema, transaction);
                        }

                        // Add everything
                        if (map.isEmpty()) {
                            Transaction.addSchemaObjects(transactionSchema, transaction);
                        }

                        // Add c8o error objects (for internal xsd edition only)
                        ConvertigoError.updateXmlSchemaObjects(transactionSchema);

                        // Save schema to file
                        String transactionXsdFilePath = transaction.getSchemaFilePath();
                        new File(transaction.getSchemaFileDirPath()).mkdirs();
                        SchemaUtils.saveSchema(transactionXsdFilePath, transactionSchema);
                    } catch (Exception e) {
                        Engine.logDatabaseObjectManager
                                .error("[Migration 7.0.0] An error occured while migrating transaction \""
                                        + transaction.getName() + "\"", e);
                    }

                    if (transaction instanceof TransactionWithVariables) {
                        TransactionWithVariables transactionVars = (TransactionWithVariables) transaction;
                        handleRequestableVariable(transactionVars.getVariablesList());

                        // Change SQLQuery variables : i.e. {id} --> {{id}}
                        if (transaction instanceof SqlTransaction) {
                            String sqlQuery = ((SqlTransaction) transaction).getSqlQuery();

                            sqlQuery = sqlQuery.replaceAll("\\{([a-zA-Z0-9_]+)\\}", "{{$1}}");
                            ((SqlTransaction) transaction).setSqlQuery(sqlQuery);
                        }

                    }
                }
            }
        } else {// Should only happen for projects which version <= 4.6.0 
            XmlSchemaCollection collection = new XmlSchemaCollection();
            String prefix = project.getName() + "_ns";
            projectSchema = SchemaUtils.createSchema(prefix, project.getNamespaceUri(),
                    XsdForm.unqualified.name(), XsdForm.unqualified.name());
            ConvertigoError.addXmlSchemaObjects(projectSchema);
            SchemaMeta.setCollection(projectSchema, collection);

            for (Connector connector : project.getConnectorsList()) {
                for (Transaction transaction : connector.getTransactionsList()) {
                    if (transaction instanceof TransactionWithVariables) {
                        TransactionWithVariables transactionVars = (TransactionWithVariables) transaction;
                        handleRequestableVariable(transactionVars.getVariablesList());
                    }
                }
            }
        }

        // Handle sequence objects
        for (Sequence sequence : project.getSequencesList()) {
            handleSteps(projectSchema, referenceMap, sequence.getSteps());
            handleRequestableVariable(sequence.getVariablesList());
        }

        // Add all references to project
        if (!referenceMap.isEmpty()) {
            for (Reference reference : referenceMap.values())
                project.add(reference);
        }

        // Delete XSD file
        if (xsdFile.exists())
            xsdFile.delete();

        // Delete WSDL file
        if (wsdlFile.exists())
            wsdlFile.delete();

    } catch (Exception e) {
        Engine.logDatabaseObjectManager
                .error("[Migration 7.0.0] An error occured while migrating project \"" + projectName + "\"", e);
    }
}

From source file:com.evolveum.midpoint.model.common.expression.ExpressionVariables.java

public Object get(QName name) {
    if (name != null && StringUtils.isBlank(name.getNamespaceURI())) {
        QName fullQName = QNameUtil.resolveNs(name, variables.keySet());
        if (fullQName != null) {
            return variables.get(fullQName);
        }/*from   ww w  .j a  v  a2 s  .c  o m*/
    }
    return variables.get(name);
}

From source file:org.eclipse.winery.repository.resources.AbstractComponentsResource.java

/**
 * @return an instance of the requested resource
 *//* w  w  w  .j ava2  s .  c  o  m*/
public AbstractComponentInstanceResource getComponentInstaceResource(QName qname) {
    return this.getComponentInstaceResource(qname.getNamespaceURI(), qname.getLocalPart(), false);
}

From source file:com.amalto.core.load.io.XMLStreamUnwrapper.java

/**
 * Moves to next record in stream and stores it in {@link #stringWriter}.
 *//*ww  w .j a  v  a 2s .c  o  m*/
private void moveToNext() {
    try {
        XMLStreamWriter writer = xmlOutputFactory.createXMLStreamWriter(stringWriter);
        boolean hasMadeChanges;
        do {
            if (!reader.hasNext()) {
                break;
            }
            hasMadeChanges = false; // Keep a state to skip line feeds
            final XMLEvent event = reader.nextEvent();
            if (event.isEndElement()) {
                level--;
            } else if (event.isStartElement()) {
                level++;
            } else if (event.isEndDocument()) {
                level--;
            }
            if (level >= RECORD_LEVEL) {
                if (event.isEndElement()) {
                    writer.writeEndElement();
                    hasMadeChanges = true;
                } else if (event.isStartElement()) {
                    final StartElement startElement = event.asStartElement();
                    final QName name = startElement.getName();
                    writer.writeStartElement(name.getNamespaceURI(), name.getLocalPart());
                    boolean isRecordRootElement = (RECORD_LEVEL == level - 1);
                    if (isRecordRootElement) {
                        for (int i = 0; i < rootNamespaceList.size(); i++) {
                            Namespace namespace = rootNamespaceList.get(i);
                            writer.writeNamespace(namespace.getPrefix(), namespace.getNamespaceURI());
                        }
                    }
                    // Declare namespaces (if any)
                    final Iterator elementNamespaces = startElement.getNamespaces();
                    while (elementNamespaces.hasNext()) {
                        Namespace elementNamespace = (Namespace) elementNamespaces.next();
                        if (isRecordRootElement) {
                            if (rootNamespaceList.size() > 0) {
                                for (int i = 0; i < rootNamespaceList.size(); i++) {
                                    Namespace namespace = rootNamespaceList.get(i);
                                    if (!namespace.getPrefix().equals(elementNamespace.getPrefix())
                                            || !namespace.getNamespaceURI()
                                                    .equals(elementNamespace.getNamespaceURI())) {
                                        writer.writeNamespace(elementNamespace.getPrefix(),
                                                elementNamespace.getNamespaceURI());
                                    }
                                }
                            } else {
                                writer.writeNamespace(elementNamespace.getPrefix(),
                                        elementNamespace.getNamespaceURI());
                            }
                        } else {
                            writer.writeNamespace(elementNamespace.getPrefix(),
                                    elementNamespace.getNamespaceURI());
                        }
                    }
                    // Write attributes
                    final Iterator attributes = startElement.getAttributes();
                    while (attributes.hasNext()) {
                        Attribute attribute = (Attribute) attributes.next();
                        QName attributeName = attribute.getName();
                        String value = attribute.getValue();
                        if (StringUtils.isEmpty(attributeName.getNamespaceURI())) {
                            writer.writeAttribute(attributeName.getLocalPart(), value);
                        } else {
                            writer.writeAttribute(attributeName.getNamespaceURI(), attributeName.getLocalPart(),
                                    value);
                        }
                    }
                    hasMadeChanges = true;
                } else if (event.isCharacters()) {
                    final String text = event.asCharacters().getData().trim();
                    if (!text.isEmpty()) {
                        writer.writeCharacters(text);
                        hasMadeChanges = true;
                    }
                }
            }
        } while (level > RECORD_LEVEL || !hasMadeChanges);
        writer.flush();
    } catch (XMLStreamException e) {
        throw new RuntimeException("Unexpected parsing exception.", e);
    }
}

From source file:com.evolveum.midpoint.prism.path.CanonicalItemPath.java

private void addToSegments(QName name) {
    if (!QNameUtil.hasNamespace(name)) {
        segments.add(new Segment(name, null, null));
        return;/* w  w  w  .  j a  va 2s .  co m*/
    }
    String namespace = name.getNamespaceURI();
    int index = 0;
    Integer shortcut = null;
    for (Segment segment : segments) {
        if (namespace.equals(segment.name.getNamespaceURI())) {
            shortcut = index = segment.index;
            break;
        }
        if (QNameUtil.hasNamespace(segment.name) && segment.shortcut == null) {
            // we found a unique non-empty namespace! (so increase the index)
            index++;
        }
    }
    segments.add(new Segment(name, index, shortcut));
}

From source file:com.ibm.soatf.component.soap.builder.SampleXmlUtil.java

private static String formatQName(XmlCursor xmlc, QName qName) {
    XmlCursor parent = xmlc.newCursor();
    parent.toParent();/*from   w w  w.  j a  va  2  s  .co m*/
    String prefix = parent.prefixForNamespace(qName.getNamespaceURI());
    parent.dispose();
    String name;
    if (prefix == null || prefix.length() == 0)
        name = qName.getLocalPart();
    else
        name = prefix + ":" + qName.getLocalPart();
    return name;
}

From source file:com.amalto.core.history.accessor.AttributeAccessor.java

private Node getAttribute() {
    Node parentNode = parent.getNode();
    if (parentNode == null) {
        throw new IllegalStateException(
                "Could not find a parent node in document (check if document has a root element)."); //$NON-NLS-1$
    }//from  w w w  . j  av  a 2s.c  o  m
    NamedNodeMap attributes = parentNode.getAttributes();
    if (attributes == null) {
        throw new IllegalStateException("Could not find attributes on parent node."); //$NON-NLS-1$
    }

    QName qName = getQName(document.asDOM());
    Node attribute = attributes.getNamedItemNS(qName.getNamespaceURI(), qName.getLocalPart());
    if (attribute == null) {
        // Look up with namespace didn't work, falls back to standard getNamedItem
        attribute = attributes.getNamedItem(qName.getLocalPart());
    }
    return attribute;
}

From source file:StAXEventTreeViewer.java

public void buildTree(DefaultTreeModel treeModel, DefaultMutableTreeNode current, File file)
        throws XMLStreamException, FileNotFoundException {

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLEventReader reader = inputFactory.createXMLEventReader(new FileInputStream(file));
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        switch (event.getEventType()) {
        case XMLStreamConstants.START_DOCUMENT:
            StartDocument startDocument = (StartDocument) event;
            DefaultMutableTreeNode version = new DefaultMutableTreeNode(startDocument.getVersion());
            current.add(version);//from   www  . j ava2s. com

            current.add(new DefaultMutableTreeNode(startDocument.isStandalone()));
            current.add(new DefaultMutableTreeNode(startDocument.standaloneSet()));
            current.add(new DefaultMutableTreeNode(startDocument.encodingSet()));
            current.add(new DefaultMutableTreeNode(startDocument.getCharacterEncodingScheme()));
            break;
        case XMLStreamConstants.START_ELEMENT:
            StartElement startElement = (StartElement) event;
            QName elementName = startElement.getName();

            DefaultMutableTreeNode element = new DefaultMutableTreeNode(elementName.getLocalPart());
            current.add(element);
            current = element;

            if (!elementName.getNamespaceURI().equals("")) {
                String prefix = elementName.getPrefix();
                if (prefix.equals("")) {
                    prefix = "[None]";
                }
                DefaultMutableTreeNode namespace = new DefaultMutableTreeNode(
                        "prefix=" + prefix + ",URI=" + elementName.getNamespaceURI());
                current.add(namespace);
            }

            for (Iterator it = startElement.getAttributes(); it.hasNext();) {
                Attribute attr = (Attribute) it.next();
                DefaultMutableTreeNode attribute = new DefaultMutableTreeNode("Attribute (name="
                        + attr.getName().getLocalPart() + ",value=" + attr.getValue() + "')");
                String attURI = attr.getName().getNamespaceURI();
                if (!attURI.equals("")) {
                    String attPrefix = attr.getName().getPrefix();
                    if (attPrefix.equals("")) {
                        attPrefix = "[None]";
                    }
                    attribute.add(new DefaultMutableTreeNode("prefix = " + attPrefix + ", URI = " + attURI));
                }
                current.add(attribute);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            current = (DefaultMutableTreeNode) current.getParent();
            break;
        case XMLStreamConstants.CHARACTERS:
            Characters characters = (Characters) event;
            if (!characters.isIgnorableWhiteSpace() && !characters.isWhiteSpace()) {
                String data = characters.getData();
                if (data.length() != 0) {
                    current.add(new DefaultMutableTreeNode(characters.getData()));
                }
            }
            break;
        case XMLStreamConstants.DTD:
            DTD dtde = (DTD) event;
            current.add(new DefaultMutableTreeNode(dtde.getDocumentTypeDeclaration()));
        default:
            System.out.println(event.getClass().getName());
        }
    }
}