Example usage for org.w3c.dom Node lookupNamespaceURI

List of usage examples for org.w3c.dom Node lookupNamespaceURI

Introduction

In this page you can find the example usage for org.w3c.dom Node lookupNamespaceURI.

Prototype

public String lookupNamespaceURI(String prefix);

Source Link

Document

Look up the namespace URI associated to the given prefix, starting from this node.

Usage

From source file:Main.java

/**
 * @param the//ww w  .  j  a  va2 s . c  om
 *            node to create the name from, never <code>null</code>
 * @return the node of the name as qualified name, never <code>null</code>
 */
public static QName buildQName(Node node) {
    String localPart;
    String nsName;
    String name = node.getTextContent();
    int indexOfColon = name.indexOf(':');
    if (indexOfColon > 0) {
        localPart = name.substring(indexOfColon + 1);
        nsName = node.lookupNamespaceURI(name.substring(0, indexOfColon));
    } else {
        localPart = name;
        // return default namespace URI if any
        nsName = node.lookupNamespaceURI(null);
    }
    return new QName(nsName, localPart);
}

From source file:Main.java

private static Document documentFromSoapBody(SOAPBodyElement element,
        HashMap<String, String> namespaceDeclarations) throws ParserConfigurationException {
    Document document = dbf.newDocumentBuilder().newDocument();
    Node node = document.importNode(element, true);
    document.appendChild(node);//from w w w .  j  av a2s  .  co m

    for (String prefix : namespaceDeclarations.keySet()) {
        String uri = namespaceDeclarations.get(prefix);
        if (node.lookupNamespaceURI(prefix) == null) {
            document.getDocumentElement().setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + prefix,
                    uri);
        }
    }
    return document;
}

From source file:Main.java

static String[] typeDescription(String type, String defaultNameSpace, Node node) throws SAXParseException {
    final String typeNameSpace;
    final String typeName;
    String[] split = type.split(":");
    switch (split.length) {
    case 1://from  w ww.j  a v  a 2 s . c  o  m
        typeNameSpace = defaultNameSpace;
        typeName = split[0];
        break;
    case 2:
        typeNameSpace = node.lookupNamespaceURI(split[0]);
        typeName = split[1];
        break;
    default:
        throw new SAXParseException("Illegal type format: " + type, null);
    }
    return new String[] { typeNameSpace, typeName };
}

From source file:XMLUtils.java

public static QName getQName(String value, Node node) {
    if (value == null) {
        return null;
    }/*from  w ww .  j  a v  a  2 s.co  m*/

    int index = value.indexOf(":");

    if (index == -1) {
        return new QName(value);
    }

    String prefix = value.substring(0, index);
    String localName = value.substring(index + 1);
    String ns = node.lookupNamespaceURI(prefix);

    if (ns == null || localName == null) {
        throw new RuntimeException("Invalid QName in mapping: " + value);
    }

    return new QName(ns, localName, prefix);
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionNamespaceContextHelpers.java

/**
 * /*w w  w  . j  a  v  a 2s  .com*/
 * This method will return a namespace map from an attribute parameter node.  Each attribute parameter
 * will have its own namespace map to facilitate xpath processing.
 * 
 * @param attributeXpathValue
 * @param node
 * @return
 * @throws Exception
 */
public static Map<String, String> returnNamespaceMapFromNode(String attributeXpathValue, Node node)
        throws Exception {
    LOG.debug("Attribute parameter xpath value: " + attributeXpathValue);

    Map<String, String> namespaceMap = new HashMap<String, String>();

    //Get all prefixes from the xpath statement
    Set<String> prefixes = returnPrefixes(attributeXpathValue);

    //Lookup prefixes and add to namespace map
    for (String prefix : prefixes) {
        LOG.debug("Prefix returned from 'returnPrefixes' method : " + prefix);

        String namespace = node.lookupNamespaceURI(prefix);

        LOG.debug("Namespace Prefix: " + prefix + ", Namespace: " + namespace);

        namespaceMap.put(prefix, namespace);

    }

    return namespaceMap;
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static String findNamespace(Node domNode, String prefix) {
    String ns = null;//w ww  .ja va 2s  .  c o m
    if (domNode != null) {
        if (prefix == null || prefix.isEmpty()) {
            ns = domNode.lookupNamespaceURI(null);
        } else {
            ns = domNode.lookupNamespaceURI(prefix);
        }
        if (ns != null) {
            return ns;
        }
    }
    return ns;
}

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

private QName getQName(Document domDocument) {
    QName qName;/*  w ww . j  a  v  a 2  s  .  co m*/
    String prefix = StringUtils.substringBefore(attributeName, ":"); //$NON-NLS-1$
    String name = StringUtils.substringAfter(attributeName, ":"); //$NON-NLS-1$
    if (name.isEmpty()) {
        // No prefix (so prefix is attribute name due to substring calls).
        String attributeNamespaceURI = domDocument.getDocumentURI();
        if (attributeNamespaceURI == null || attributeNamespaceURI.isEmpty()) {
            Node attributeNode = getAttributeNode(domDocument);
            if (attributeNode != null) {
                attributeNamespaceURI = attributeNode.getNamespaceURI();
            }
        }
        qName = new QName(attributeNamespaceURI, prefix);
    } else {
        String attributeNamespaceURI = domDocument.lookupNamespaceURI(prefix);
        if (attributeNamespaceURI == null || attributeNamespaceURI.isEmpty()) {
            Node attributeNode = getAttributeNode(domDocument);
            if (attributeNode != null) {
                attributeNamespaceURI = attributeNode.lookupNamespaceURI(prefix);
            }
        }
        qName = new QName(attributeNamespaceURI, name, prefix);
    }
    return qName;
}

From source file:com.evolveum.midpoint.prism.marshaller.ItemPathHolder.java

private String findNamespace(String prefix, Node domNode, Map<String, String> namespaceMap) {

    String ns = null;//w  ww  .ja va2  s.c om

    if (explicitNamespaceDeclarations != null) {
        if (prefix == null) {
            ns = explicitNamespaceDeclarations.get("");
        } else {
            ns = explicitNamespaceDeclarations.get(prefix);
        }
        if (ns != null) {
            return ns;
        }
    }

    if (namespaceMap != null) {
        if (prefix == null) {
            ns = namespaceMap.get("");
        } else {
            ns = namespaceMap.get(prefix);
        }
        if (ns != null) {
            return ns;
        }
    }

    if (domNode != null) {
        if (StringUtils.isNotEmpty(prefix)) {
            ns = domNode.lookupNamespaceURI(prefix);
        } else {
            // we don't want the default namespace declaration (xmlns="...") to propagate into path expressions
            // so here we do not try to obtain the namespace from the document
        }
        if (ns != null) {
            return ns;
        }
    }

    return ns;
}

From source file:org.accada.epcis.repository.capture.CaptureOperationsModule.java

/**
 * Takes an XML document node, parses it as EPCIS event and inserts the data
 * into the database. The parse routine is generic for all event types; the
 * query generation part has some if/elses to take care of different event
 * parameters./*from  ww  w . j a  v  a2 s .  c  o  m*/
 * 
 * @param eventNode
 *            The current event node.
 * @param eventType
 *            The current event type.
 * @throws Exception
 * @throws DOMException
 */
private void handleEvent(Session session, final Node eventNode, final String eventType)
        throws DOMException, SAXException, InvalidFormatException {
    if (eventNode == null) {
        // nothing to do
        return;
    } else if (eventNode.getChildNodes().getLength() == 0) {
        throw new SAXException("Event element '" + eventNode.getNodeName() + "' has no children elements.");
    }
    Node curEventNode = null;

    // A lot of the initialized variables have type URI. This type isn't to
    // compare with the URI-Type of the standard. In fact, most of the
    // variables having type URI are declared as Vocabularies in the
    // Standard. Commonly, we use String for the Standard-Type URI.

    Timestamp eventTime = null;
    Timestamp recordTime = new Timestamp(System.currentTimeMillis());
    String eventTimeZoneOffset = null;
    String action = null;
    String parentId = null;
    Long quantity = null;
    String bizStepUri = null;
    String dispositionUri = null;
    String readPointUri = null;
    String bizLocationUri = null;
    String epcClassUri = null;

    List<String> epcs = null;
    List<BusinessTransaction> bizTransList = null;
    List<EventFieldExtension> fieldNameExtList = new ArrayList<EventFieldExtension>();

    for (int i = 0; i < eventNode.getChildNodes().getLength(); i++) {
        curEventNode = eventNode.getChildNodes().item(i);
        String nodeName = curEventNode.getNodeName();

        if (nodeName.equals("#text") || nodeName.equals("#comment")) {
            // ignore text or comments
            LOG.debug("  ignoring text or comment: '" + curEventNode.getTextContent().trim() + "'");
            continue;
        }

        LOG.debug("  handling event field: '" + nodeName + "'");
        if (nodeName.equals("eventTime")) {
            String xmlTime = curEventNode.getTextContent();
            LOG.debug("    eventTime in xml is '" + xmlTime + "'");
            try {
                eventTime = TimeParser.parseAsTimestamp(xmlTime);
            } catch (ParseException e) {
                throw new SAXException("Invalid date/time (must be ISO8601).", e);
            }
            LOG.debug("    eventTime parsed as '" + eventTime + "'");
        } else if (nodeName.equals("recordTime")) {
            // ignore recordTime
        } else if (nodeName.equals("eventTimeZoneOffset")) {
            eventTimeZoneOffset = checkEventTimeZoneOffset(curEventNode.getTextContent());
        } else if (nodeName.equals("epcList") || nodeName.equals("childEPCs")) {
            epcs = handleEpcs(eventType, curEventNode);
        } else if (nodeName.equals("bizTransactionList")) {
            bizTransList = handleBizTransactions(session, curEventNode);
        } else if (nodeName.equals("action")) {
            action = curEventNode.getTextContent();
            if (!action.equals("ADD") && !action.equals("OBSERVE") && !action.equals("DELETE")) {
                throw new SAXException("Encountered illegal 'action' value: " + action);
            }
        } else if (nodeName.equals("bizStep")) {
            bizStepUri = curEventNode.getTextContent();
        } else if (nodeName.equals("disposition")) {
            dispositionUri = curEventNode.getTextContent();
        } else if (nodeName.equals("readPoint")) {
            Element attrElem = (Element) curEventNode;
            Node id = attrElem.getElementsByTagName("id").item(0);
            readPointUri = id.getTextContent();
        } else if (nodeName.equals("bizLocation")) {
            Element attrElem = (Element) curEventNode;
            Node id = attrElem.getElementsByTagName("id").item(0);
            bizLocationUri = id.getTextContent();
        } else if (nodeName.equals("epcClass")) {
            epcClassUri = curEventNode.getTextContent();
        } else if (nodeName.equals("quantity")) {
            quantity = Long.valueOf(curEventNode.getTextContent());
        } else if (nodeName.equals("parentID")) {
            checkEpcOrUri(curEventNode.getTextContent(), false);
            parentId = curEventNode.getTextContent();
        } else {
            String[] parts = nodeName.split(":");
            if (parts.length == 2) {
                LOG.debug("    treating unknown event field as extension.");
                String prefix = parts[0];
                String localname = parts[1];
                // String namespace =
                // document.getDocumentElement().getAttribute("xmlns:" +
                // prefix);
                String namespace = curEventNode.lookupNamespaceURI(prefix);
                String value = curEventNode.getTextContent();
                EventFieldExtension evf = new EventFieldExtension(prefix, namespace, localname, value);
                fieldNameExtList.add(evf);
            } else {
                // this is not a valid extension
                throw new SAXException("    encountered unknown event field: '" + nodeName + "'.");
            }
        }
    }
    if (eventType.equals(EpcisConstants.AGGREGATION_EVENT)) {
        // for AggregationEvents, the parentID is only optional for
        // action=OBSERVE
        if (parentId == null && ("ADD".equals(action) || "DELETE".equals(action))) {
            throw new InvalidFormatException("'parentID' is required if 'action' is ADD or DELETE");
        }
    }

    String nodeName = eventNode.getNodeName();
    VocabularyElement bizStep = bizStepUri != null
            ? getOrInsertVocabularyElement(session, EpcisConstants.BUSINESS_STEP_ID, String.valueOf(bizStepUri))
            : null;
    VocabularyElement disposition = dispositionUri != null
            ? getOrInsertVocabularyElement(session, EpcisConstants.DISPOSITION_ID,
                    String.valueOf(dispositionUri))
            : null;
    VocabularyElement readPoint = readPointUri != null
            ? getOrInsertVocabularyElement(session, EpcisConstants.READ_POINT_ID, String.valueOf(readPointUri))
            : null;
    VocabularyElement bizLocation = bizLocationUri != null
            ? getOrInsertVocabularyElement(session, EpcisConstants.BUSINESS_LOCATION_ID,
                    String.valueOf(bizLocationUri))
            : null;
    VocabularyElement epcClass = epcClassUri != null
            ? getOrInsertVocabularyElement(session, EpcisConstants.EPC_CLASS_ID, String.valueOf(epcClassUri))
            : null;

    BaseEvent be;
    if (nodeName.equals(EpcisConstants.AGGREGATION_EVENT)) {
        AggregationEvent ae = new AggregationEvent();
        ae.setParentId(parentId);
        ae.setChildEpcs(epcs);
        ae.setAction(Action.valueOf(action));
        be = ae;
    } else if (nodeName.equals(EpcisConstants.OBJECT_EVENT)) {
        ObjectEvent oe = new ObjectEvent();
        oe.setAction(Action.valueOf(action));
        if (epcs != null && epcs.size() > 0) {
            oe.setEpcList(epcs);
        }
        be = oe;
    } else if (nodeName.equals(EpcisConstants.QUANTITY_EVENT)) {
        QuantityEvent qe = new QuantityEvent();
        qe.setEpcClass((EPCClass) epcClass);
        if (quantity != null) {
            qe.setQuantity(quantity.longValue());
        }
        be = qe;
    } else if (nodeName.equals(EpcisConstants.TRANSACTION_EVENT)) {
        TransactionEvent te = new TransactionEvent();
        te.setParentId(parentId);
        te.setEpcList(epcs);
        te.setAction(Action.valueOf(action));
        be = te;
    } else {
        throw new SAXException("Encountered unknown event element '" + nodeName + "'.");
    }

    be.setEventTime(eventTime);
    be.setRecordTime(recordTime);
    be.setEventTimeZoneOffset(eventTimeZoneOffset);
    be.setBizStep((BusinessStepId) bizStep);
    be.setDisposition((DispositionId) disposition);
    be.setBizLocation((BusinessLocationId) bizLocation);
    be.setReadPoint((ReadPointId) readPoint);
    if (bizTransList != null && bizTransList.size() > 0) {
        be.setBizTransList(bizTransList);
    }
    if (!fieldNameExtList.isEmpty()) {
        be.setExtensions(fieldNameExtList);
    }

    session.save(be);
}

From source file:org.apache.ode.utils.DOMUtils.java

/**
 * Parse the text in the cloneChild for any embedded prefixes, and define it in it's parent element
 *
 * @param sourceNode/*from  w  w  w  .  j a  v  a  2 s.  c  o  m*/
 * @param clonedNode
 * @param clonedChild
 */
private static void parseEmbeddedPrefixes(Node sourceNode, Node clonedNode, Node clonedChild) {
    Element clonedElement = null;
    if (clonedNode instanceof Attr) {
        clonedElement = ((Attr) clonedNode).getOwnerElement();
    } else if (clonedNode instanceof Element) {
        clonedElement = (Element) clonedNode;
    }
    if (clonedElement == null) {
        // couldn't find an element to set prefixes on, so bail out
        return;
    }

    String text = ((Text) clonedChild).getNodeValue();
    if (text != null && text.indexOf(":") > 0) {
        Name11Checker nameChecker = Name11Checker.getInstance();
        for (int colonIndex = text.indexOf(":"); colonIndex != -1
                && colonIndex < text.length(); colonIndex = text.indexOf(":", colonIndex + 1)) {
            StringBuffer prefixString = new StringBuffer();
            for (int prefixIndex = colonIndex - 1; prefixIndex >= 0
                    && nameChecker.isNCNameChar(text.charAt(prefixIndex)); prefixIndex--) {
                prefixString.append(text.charAt(prefixIndex));
            }
            prefixString.reverse();
            if (prefixString.length() > 0) {
                String uri = sourceNode.lookupNamespaceURI(prefixString.toString());
                if (uri != null) {
                    clonedElement.setAttributeNS(NS_URI_XMLNS, "xmlns:" + prefixString, uri);
                }
            }
        }
    }
}