Example usage for org.w3c.dom Node getNamespaceURI

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

Introduction

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

Prototype

public String getNamespaceURI();

Source Link

Document

The namespace URI of this node, or null if it is unspecified (see ).

Usage

From source file:edu.cornell.mannlib.vitro.webapp.controller.harvester.FileHarvestController.java

/**
 * Parse an XML node for all subnodes with qualified name "rdf:type", and return each's "rdf:resource" value in a list.
 * @param descriptionNode the RDF description node
 * @return a list of rdf:types of the given description node
 *///from w w  w.j  a va 2s  . c  o m
private ArrayList<String> getRdfTypes(Node descriptionNode) {
    ArrayList<String> rdfTypesList = new ArrayList<String>();

    NodeList children = descriptionNode.getChildNodes();
    int numChildren = children.getLength();
    for (int i = 0; i < numChildren; i++) {
        Node child = children.item(i);

        String namespace = child.getNamespaceURI();
        String name = child.getLocalName();
        String fullName = namespace + name;
        if (fullName.equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")) {
            NamedNodeMap attributes = child.getAttributes();
            Node resourceAttribute = attributes.getNamedItemNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#",
                    "resource");
            if (resourceAttribute != null) {
                //String attributeNamespace = resourceAttribute.getNamespaceURI();
                String value = resourceAttribute.getNodeValue();
                //rdfTypesList.add(attributeNamespace + value);
                rdfTypesList.add(value);
            }
        }
    }

    return rdfTypesList;
}

From source file:com.android.sdklib.internal.repository.packages.Package.java

/**
 * Parses an XML node to process the <archives> element.
 * Always return a non-null array. The array may be empty.
 *///from w  ww. j  av  a 2s  .  c o  m
@NonNull
private Archive[] parseArchives(@NonNull Node archivesNode) {
    ArrayList<Archive> archives = new ArrayList<Archive>();

    if (archivesNode != null) {
        String nsUri = archivesNode.getNamespaceURI();
        for (Node child = archivesNode.getFirstChild(); child != null; child = child.getNextSibling()) {

            if (child.getNodeType() == Node.ELEMENT_NODE && nsUri.equals(child.getNamespaceURI())
                    && SdkRepoConstants.NODE_ARCHIVE.equals(child.getLocalName())) {
                archives.add(parseArchive(child));
            }
        }
    }

    return archives.toArray(new Archive[archives.size()]);
}

From source file:com.marklogic.dom.NodeImpl.java

/** {@inheritDoc} */
public boolean isEqualNode(Node other) {

    // Note that normalization can affect equality; to avoid this,
    // nodes should be normalized before being compared.
    // For the moment, normalization cannot be done.
    if (other == null)
        return false;
    if (getNodeType() != other.getNodeType())
        return false;
    if (!getLocalName().equals(other.getLocalName()))
        return false;
    if (notequals(getNamespaceURI(), other.getNamespaceURI()))
        return false;
    if (notequals(getPrefix(), other.getPrefix()))
        return false;
    if (notequals(getNodeValue(), other.getNodeValue()))
        return false;
    if (hasChildNodes() != other.hasChildNodes())
        return false;
    if (hasAttributes() != other.hasAttributes())
        return false;
    if (hasChildNodes()) {
        NamedNodeMap thisAttr = getAttributes();
        NamedNodeMap otherAttr = other.getAttributes();
        if (thisAttr.getLength() != otherAttr.getLength())
            return false;
        for (int i = 0; i < thisAttr.getLength(); i++)
            if (thisAttr.item(i).isEqualNode(otherAttr.item(i)))
                return false;
    }//from   w  w w.  j  ava  2 s .co  m
    if (hasAttributes()) {
        NodeList thisChild = getChildNodes();
        NodeList otherChild = other.getChildNodes();
        if (thisChild.getLength() != otherChild.getLength())
            return false;
        for (int i = 0; i < thisChild.getLength(); i++)
            if (thisChild.item(i).isEqualNode(otherChild.item(i)))
                return false;
    }
    return true;
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

private SOAPElement addSoapElement(Context context, SOAPEnvelope se, SOAPElement soapParent, Node node)
        throws Exception {
    String prefix = node.getPrefix();
    String namespace = node.getNamespaceURI();
    String nodeName = node.getNodeName();
    String localName = node.getLocalName();
    String value = node.getNodeValue();

    boolean includeResponseElement = true;
    if (context.sequenceName != null) {
        includeResponseElement = ((Sequence) context.requestedObject).isIncludeResponseElement();
    }//from  w  ww .j  av a2 s  .  co m

    SOAPElement soapElement = null;
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) node;

        boolean toAdd = true;
        if (!includeResponseElement && "response".equalsIgnoreCase(localName)) {
            toAdd = false;
        }
        if ("http://schemas.xmlsoap.org/soap/envelope/".equals(element.getParentNode().getNamespaceURI())
                || "http://schemas.xmlsoap.org/soap/envelope/".equals(namespace)
                || nodeName.toLowerCase().endsWith(":envelope") || nodeName.toLowerCase().endsWith(":body")
        //element.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1 ||
        //nodeName.toUpperCase().indexOf("NS0:") != -1
        ) {
            toAdd = false;
        }

        if (toAdd) {
            if (prefix == null || prefix.equals("")) {
                soapElement = soapParent.addChildElement(nodeName);
            } else {
                soapElement = soapParent.addChildElement(se.createName(localName, prefix, namespace));
            }
        } else {
            soapElement = soapParent;
        }

        if (soapElement != null) {
            if (soapParent.equals(se.getBody()) && !soapParent.equals(soapElement)) {
                if (XsdForm.qualified == context.project.getSchemaElementForm()) {
                    if (soapElement.getAttribute("xmlns") == null) {
                        soapElement.addAttribute(se.createName("xmlns"), context.project.getTargetNamespace());
                    }
                }
            }

            if (element.hasAttributes()) {
                String attrType = element.getAttribute("type");
                if (("attachment").equals(attrType)) {
                    if (context.requestedObject instanceof AbstractHttpTransaction) {
                        AttachmentDetails attachment = AttachmentManager.getAttachment(element);
                        if (attachment != null) {
                            byte[] raw = attachment.getData();
                            if (raw != null)
                                soapElement.addTextNode(Base64.encodeBase64String(raw));
                        }

                        /* DON'T WORK YET *\
                        AttachmentPart ap = responseMessage.createAttachmentPart(new ByteArrayInputStream(raw), element.getAttribute("content-type"));
                        ap.setContentId(key);
                        ap.setContentLocation(element.getAttribute("url"));
                        responseMessage.addAttachmentPart(ap);
                        \* DON'T WORK YET */
                    }
                }

                if (!includeResponseElement && "response".equalsIgnoreCase(localName)) {
                    // do not add attributes
                } else {
                    NamedNodeMap attributes = element.getAttributes();
                    int len = attributes.getLength();
                    for (int i = 0; i < len; i++) {
                        Node item = attributes.item(i);
                        addSoapElement(context, se, soapElement, item);
                    }
                }
            }

            if (element.hasChildNodes()) {
                NodeList childNodes = element.getChildNodes();
                int len = childNodes.getLength();
                for (int i = 0; i < len; i++) {
                    Node item = childNodes.item(i);
                    switch (item.getNodeType()) {
                    case Node.ELEMENT_NODE:
                        addSoapElement(context, se, soapElement, item);
                        break;
                    case Node.CDATA_SECTION_NODE:
                    case Node.TEXT_NODE:
                        String text = item.getNodeValue();
                        text = (text == null) ? "" : text;
                        soapElement.addTextNode(text);
                        break;
                    default:
                        break;
                    }
                }
            }
        }
    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        if (prefix == null || prefix.equals("")) {
            soapElement = soapParent.addAttribute(se.createName(nodeName), value);
        } else {
            soapElement = soapParent.addAttribute(se.createName(localName, prefix, namespace), value);
        }
    }
    return soapElement;
}

From source file:com.amalto.core.util.Util.java

private static String[] getTextNodes(Node contextNode, String xPath, final Node namespaceNode)
        throws TransformerException {
    String[] results;/*  w  ww .j  a v  a 2s.co m*/
    // test for hard-coded values
    if (xPath.startsWith("\"") && xPath.endsWith("\"")) { //$NON-NLS-1$ //$NON-NLS-2$
        return new String[] { xPath.substring(1, xPath.length() - 1) };
    }
    // test for incomplete path (elements missing /text())
    if (!xPath.matches(".*@[^/\\]]+")) { // attribute
        if (!xPath.endsWith(")")) { // function
            xPath += "/text()";
        }
    }
    try {
        XPath path = XPathFactory.newInstance().newXPath();
        path.setNamespaceContext(new NamespaceContext() {

            @Override
            public String getNamespaceURI(String s) {
                return namespaceNode.getNamespaceURI();
            }

            @Override
            public String getPrefix(String s) {
                return namespaceNode.getPrefix();
            }

            @Override
            public Iterator getPrefixes(String s) {
                return Collections.singleton(namespaceNode.getPrefix()).iterator();
            }
        });
        NodeList xo = (NodeList) path.evaluate(xPath, contextNode, XPathConstants.NODESET);
        results = new String[xo.getLength()];
        for (int i = 0; i < xo.getLength(); i++) {
            results[i] = xo.item(i).getTextContent();
        }
    } catch (Exception e) {
        String err = "Unable to get the text node(s) of " + xPath + ": " + e.getClass().getName() + ": "
                + e.getLocalizedMessage();
        throw new TransformerException(err);
    }
    return results;

}

From source file:dk.statsbiblioteket.doms.central.connectors.fedora.FedoraRest.java

@Override
public List<FedoraRelation> getNamedRelations(String pid, String predicate, Long asOfTime)
        throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException {
    ArrayList<FedoraRelation> result = new ArrayList<FedoraRelation>();
    try {// w  w  w. j ava  2s .c o m
        //TODO handle RELS-INT
        pid = cleanInfo(pid);
        XPathSelector xpath = DOM.createXPathSelector("rdf", Constants.NAMESPACE_RDF);

        Document relsDoc = DOM.stringToDOM(getXMLDatastreamContents(pid, "RELS-EXT", asOfTime), true);

        NodeList relationNodes = xpath.selectNodeList(relsDoc, "/rdf:RDF/rdf:Description/*");
        if (predicate != null) {
            predicate = getAbsoluteURIAsString(predicate);
        }
        for (int i = 0; i < relationNodes.getLength(); i++) {
            Node relationNode = relationNodes.item(i);
            final String nodeName = relationNode.getNamespaceURI() + relationNode.getLocalName();
            if (predicate == null || nodeName.equals(predicate)) {

                final Node resource = relationNode.getAttributes().getNamedItemNS(Constants.NAMESPACE_RDF,
                        "resource");
                //The resource will have the info:fedora/ prefix if not literal
                if (resource != null) {
                    result.add(new FedoraRelation(toUri(pid), nodeName, resource.getNodeValue()));
                } else {
                    final FedoraRelation fedoraRelation = new FedoraRelation(toUri(pid), nodeName,
                            relationNode.getTextContent());
                    fedoraRelation.setLiteral(true);
                    result.add(fedoraRelation);
                }

            }
        }
    } catch (BackendInvalidResourceException e) {
        if (exists(pid, asOfTime)) {
            //does not have a RELS-EXT datastream. This is not really an error
            return result;
        } else {
            throw new BackendInvalidResourceException("Object '" + pid + "' does not exist", e);
        }
    }
    return result;

}

From source file:it.cnr.icar.eric.server.common.Utility.java

public org.w3c.dom.Element getSignatureElement(SOAPMessage msg)
        throws javax.xml.soap.SOAPException, javax.xml.transform.TransformerException {
    org.w3c.dom.Element sigElement = null;

    javax.xml.transform.Transformer xFormer = javax.xml.transform.TransformerFactory.newInstance()
            .newTransformer();/*from   w  w w . j  ava 2s  .c o m*/

    // grab info out of msg
    javax.xml.soap.SOAPPart msgPart = msg.getSOAPPart();
    javax.xml.transform.Source msgSource = msgPart.getContent();

    // transform
    javax.xml.transform.dom.DOMResult domResult = new javax.xml.transform.dom.DOMResult();
    xFormer.transform(msgSource, domResult);

    //root node is the soap:Envelope
    Node envelopeNode = domResult.getNode();

    //now you have the node. the following code strips off the envelope of
    //the soap message to get to the actual content
    // Advance to envelope node in case of text nodes preceding it
    while ((envelopeNode.getLocalName() == null)
            || (!envelopeNode.getLocalName().equalsIgnoreCase("envelope"))) {
        envelopeNode = envelopeNode.getFirstChild();
    }

    // Advance to header within envelope node
    Node headerNode = envelopeNode.getFirstChild();

    while ((headerNode.getLocalName() == null) || (!headerNode.getLocalName().equalsIgnoreCase("header"))) {
        headerNode = headerNode.getNextSibling();
    }

    //System.err.println("headerNode name is: " + headerNode.getLocalName());
    // Advance to signature node within header
    Node sigNode = headerNode.getFirstChild();

    if (sigNode == null) {
        return null;
    }

    //System.err.println("sigNode: " + sigNode);
    while ((sigNode.getLocalName() == null) || (!sigNode.getLocalName().equalsIgnoreCase("signature"))) {
        sigNode = sigNode.getNextSibling();

        if (sigNode == null) {
            return null;
        }
    }

    //Desired Signature element may be inside a SOAP-SEC signature element
    if (!sigNode.getNamespaceURI().equals("http://www.w3.org/2000/09/xmldsig#")) {
        sigNode = sigNode.getFirstChild();

        while ((sigNode.getLocalName() == null) || (!sigNode.getLocalName().equalsIgnoreCase("signature"))) {
            sigNode = sigNode.getNextSibling();
        }
    }

    if (sigNode.getNamespaceURI().equals("http://www.w3.org/2000/09/xmldsig#")) {
        if (sigNode instanceof org.w3c.dom.Element) {
            sigElement = (org.w3c.dom.Element) sigNode;
        }
    }

    return sigElement;
}

From source file:com.connexta.arbitro.ctx.xacml3.XACML3EvaluationCtx.java

private Set<String> getChildXPaths(Node root, String xPath) {

    Set<String> xPaths = new HashSet<String>();
    NamespaceContext namespaceContext = null;

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    if (namespaceContext == null) {

        //see if the request root is in a namespace
        String namespace = null;//from  w ww. ja va2  s .com
        if (root != null) {
            namespace = root.getNamespaceURI();
        }
        // name spaces are used, so we need to lookup the correct
        // prefix to use in the search string
        NamedNodeMap namedNodeMap = root.getAttributes();

        Map<String, String> nsMap = new HashMap<String, String>();
        if (namedNodeMap != null) {
            for (int i = 0; i < namedNodeMap.getLength(); i++) {
                Node n = namedNodeMap.item(i);
                // we found the matching namespace, so get the prefix
                // and then break out
                String prefix = DOMHelper.getLocalName(n);
                String nodeValue = n.getNodeValue();
                nsMap.put(prefix, nodeValue);
            }
        }

        // if there is not any namespace is defined for content element, default XACML request
        //  name space would be there.
        if (XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(namespace)
                || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(namespace)
                || XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(namespace)) {
            nsMap.put("xacml", namespace);
        }

        namespaceContext = new DefaultNamespaceContext(nsMap);
    }

    xpath.setNamespaceContext(namespaceContext);

    try {
        XPathExpression expression = xpath.compile(xPath);
        NodeList matches = (NodeList) expression.evaluate(root, XPathConstants.NODESET);
        if (matches != null && matches.getLength() > 0) {

            for (int i = 0; i < matches.getLength(); i++) {
                String text = null;
                Node node = matches.item(i);
                short nodeType = node.getNodeType();

                // see if this is straight text, or a node with data under
                // it and then get the values accordingly
                if ((nodeType == Node.CDATA_SECTION_NODE) || (nodeType == Node.COMMENT_NODE)
                        || (nodeType == Node.TEXT_NODE) || (nodeType == Node.ATTRIBUTE_NODE)) {
                    // there is no child to this node
                    text = node.getNodeValue();
                } else {

                    // the data is in a child node
                    text = "/" + DOMHelper.getLocalName(node);
                }
                String newXPath = '(' + xPath + ")[" + (i + 1) + ']';
                xPaths.add(newXPath);
            }
        }
    } catch (Exception e) {
        // TODO
    }

    return xPaths;
}

From source file:com.silverwrist.venice.std.TrackbackManager.java

/**
 * Loads the HTTP content at the specified URL, scans it for RDF description blocks, and adds those blocks
 * as {@link com.silverwrist.venice.std.TrackbackItem TrackbackItem}s to our internal cache.  Uses modification
 * detection to keep from reloading a page unless necessary.
 *
 * @param url The URL of the resource to be loaded.
 * @param attrs The attributes of the specified page; if this is <code>null</code>, we'll check the page
 *              cache for the right attributes.
 * @return <code>true</code> if the page data was loaded and scanned for trackback items; <code>false</code>
 *         if no data was loaded (because it was not modified since the last time we loaded it, for instance).
 * @exception com.silverwrist.venice.except.TrackbackException If there was an error loading or interpreting
 *            the page data.//  ww w .j av  a2  s.  c  o m
 */
private synchronized boolean load(URL url, PageAttributes attrs) throws TrackbackException {
    if (attrs == null)
        attrs = (PageAttributes) (m_page_cache.get(url));

    // Create the GET method and set its headers.
    String s = url.toString();
    int x = s.lastIndexOf('#');
    if (x >= 0)
        s = s.substring(0, x);
    GetMethod getter = new GetMethod(s);
    HttpMethodParams params = getter.getParams();
    getter.setDoAuthentication(false);
    getter.setFollowRedirects(true);
    getter.setRequestHeader("User-Agent", USER_AGENT);
    getter.setRequestHeader("Accept", "text/*");
    getter.setRequestHeader("Accept-Encoding", "identity");
    params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    getter.setParams(params);

    boolean get_resp = false;
    PageAttributes newattrs = null;
    ContentType ctype = null;
    byte[] rawdata = null;
    try { // set the Last-Modified date as an If-Modified-Since header on the request
        java.util.Date lmod = null;
        if (attrs != null)
            lmod = attrs.getLastModified();
        if (lmod != null)
            getter.setRequestHeader("If-Modified-Since", s_httpdate_format.format(lmod));

        // execute the Get method!
        int rc = m_http_client.executeMethod(getter);
        get_resp = true;
        if ((lmod != null) && (rc == HttpStatus.SC_NOT_MODIFIED))
            return false; // we were not modified
        if (rc == HttpStatus.SC_NO_CONTENT)
            return false; // there's no content there
        if (rc != HttpStatus.SC_OK) // this is farked!
            throw new TrackbackException("GET of " + url + " returned " + rc);

        // Get the new page attributes and save them off.
        newattrs = new PageAttributes(getter);
        m_page_cache.put(url, newattrs);

        // Get the Content-Type header and see if it's valid.
        Header hdr = getter.getResponseHeader("Content-Type");
        if (hdr != null)
            s = hdr.getValue();
        else
            s = "text/plain"; // necessary assumption
        ctype = new ContentType(s);
        if (!(ctype.getPrimaryType().equals("text")))
            throw new TrackbackException("URL " + url + " does not point to a text-based resource");

        // Load the resource in as byte data; we will determine the right character set for it later.
        rawdata = getter.getResponseBody();
        get_resp = false;

    } // end try
    catch (IOException e) { // IO error getting the page
        throw new TrackbackException("I/O error retrieving " + url + ": " + e.getMessage(), e);

    } // end catch
    catch (javax.mail.internet.ParseException e) { // translate into TrackbackException
        throw new TrackbackException("invalid Content-Type received for URL " + url, e);

    } // end catch
    finally { // release the connection if possible
        try { // need to get the message body
            if (get_resp)
                getter.getResponseBody();

        } // end try
        catch (IOException e) { // ignore these
        } // end catch

        getter.releaseConnection();

    } // end finally

    // make a first guess at the charset from the HTTP header Content-Type
    String cset = ctype.getParameter("charset");
    if (cset == null)
        cset = "US-ASCII";
    String content = null;
    try { // interpret the content
        content = new String(rawdata, cset);

    } // end try
    catch (UnsupportedEncodingException e) { // fall back and try just using US-ASCII
        cset = null;
        try { // interpret the content
            content = new String(rawdata, "US-ASCII");

        } // end try
        catch (UnsupportedEncodingException e2) { // can't happen
            logger.debug("WTF? US-ASCII should damn well be a supported character set!", e2);

        } // end catch

    } // end catch

    // Look for <META HTTP-EQUIV=...> tags in the content.
    Map http_attrs = extractHttpEquivTags(content);

    // Try to get a Content-Type attribute from there.
    s = (String) (http_attrs.get("CONTENT-TYPE"));
    String cset2 = null;
    if (s != null) { // look for the content type
        try { // parse into Content-Type
            ContentType c = new ContentType(s);
            if (c.getPrimaryType().equals("text"))
                cset2 = c.getParameter("charset");

        } // end try
        catch (javax.mail.internet.ParseException e) { // can't get a second Content-Type
            logger.debug("parse of Content-Type from META tags failed", e);
            cset2 = null;

        } // end catch

    } // end if

    if ((cset == null) && (cset2 == null))
        throw new TrackbackException("unable to determine character set for " + url);
    if ((cset2 != null) && ((cset == null) || !(cset.equalsIgnoreCase(cset2)))) { // reinterpret content in new character set
        try { // reinterpret content in new character set
            s = new String(rawdata, cset2);
            content = s;

            // the contents of the HTTP-EQUIV tags may have changed as a result
            http_attrs = extractHttpEquivTags(content);

        } // end try
        catch (UnsupportedEncodingException e) { // just use original character set
            if (cset == null)
                throw new TrackbackException("unable to determine character set for " + url);

        } // end catch

    } // end if

    newattrs.updateFromPage(http_attrs); // update the page attributes from the META tag data

    // Search the page content for RDF blocks.
    RE m = new RE(s_rdf_start, RE.MATCH_NORMAL);
    int pos = 0;
    while (m.match(content, pos)) { // look for the end of this RDF block
        RE m2 = new RE(getEndRecognizer(m.getParen(1)), RE.MATCH_NORMAL);
        if (m2.match(content, m.getParenEnd(0))) { // we now have a block to feed to the XML parser
            try { // run the block through the XML parser
                InputSource isrc = new InputSource(
                        new StringReader(content.substring(m.getParenStart(0), m2.getParenEnd(0))));
                Document doc = m_rdf_parser.parse(isrc);

                // examine topmost element, which should be rdf:RDF
                Element root = doc.getDocumentElement();
                if (NS_RDF.equals(root.getNamespaceURI()) && (root.getLocalName() != null)
                        && root.getLocalName().equals("RDF")) { // this is most definitely an rdf:RDF node...look for rdf:Description nodes under it
                    NodeList nl = root.getChildNodes();
                    for (int i = 0; i < nl.getLength(); i++) { // check each node in the list
                        Node n = nl.item(i);
                        if ((n.getNodeType() == Node.ELEMENT_NODE) && NS_RDF.equals(n.getNamespaceURI())
                                && (n.getLocalName() != null) && n.getLocalName().equals("Description")) { // we've got an rdf:Description node...extract the attributes from it
                            Element elt = (Element) n;
                            try { // look for the item and trackback URLs
                                URL item = null, trackback = null;
                                s = elt.getAttributeNS(NS_DC, "identifier");
                                if ((s != null) && (s.length() > 0))
                                    item = new URL(s);
                                s = elt.getAttributeNS(NS_TRACKBACK, "ping");
                                if ((s != null) && (s.length() > 0))
                                    trackback = new URL(s);
                                if ((item != null) && (trackback != null)) { // create the item
                                    s = elt.getAttributeNS(NS_DC, "title");
                                    m_item_cache.put(item, new MyTrackbackItem(item, trackback, s, newattrs));

                                } // end if

                            } // end try
                            catch (MalformedURLException e) { // this means skip this item
                                logger.warn("URL parse failure", e);

                            } // end catch

                        } // end if

                    } // end for

                } // end if

            } // end try
            catch (IOException e) { // disregard this block
                logger.warn("RDF block parse failure", e);

            } // end catch
            catch (SAXException e) { // disregard this block
                logger.warn("RDF block parse failure", e);

            } // end catch

        } // end if
          // else ignore this possible block

        pos = m.getParenEnd(0);

    } // end while

    return true;

}

From source file:DOM2SAX.java

/**
 * Writes a node using the given writer.
 * @param node node to serialize/*w w  w .j  a  v  a2  s .  com*/
 * @throws SAXException In case of a problem while writing XML
 */
private void writeNode(Node node) throws SAXException {
    if (node == null) {
        return;
    }

    switch (node.getNodeType()) {
    case Node.ATTRIBUTE_NODE: // handled by ELEMENT_NODE
    case Node.DOCUMENT_FRAGMENT_NODE:
    case Node.DOCUMENT_TYPE_NODE:
    case Node.ENTITY_NODE:
    case Node.ENTITY_REFERENCE_NODE:
    case Node.NOTATION_NODE:
        // These node types are ignored!!!
        break;
    case Node.CDATA_SECTION_NODE:
        final String cdata = node.getNodeValue();
        if (lexicalHandler != null) {
            lexicalHandler.startCDATA();
            contentHandler.characters(cdata.toCharArray(), 0, cdata.length());
            lexicalHandler.endCDATA();
        } else {
            // in the case where there is no lex handler, we still
            // want the text of the cdate to make its way through.
            contentHandler.characters(cdata.toCharArray(), 0, cdata.length());
        }
        break;

    case Node.COMMENT_NODE: // should be handled!!!
        if (lexicalHandler != null) {
            final String value = node.getNodeValue();
            lexicalHandler.comment(value.toCharArray(), 0, value.length());
        }
        break;
    case Node.DOCUMENT_NODE:
        contentHandler.startDocument();
        Node next = node.getFirstChild();
        while (next != null) {
            writeNode(next);
            next = next.getNextSibling();
        }
        contentHandler.endDocument();
        break;

    case Node.ELEMENT_NODE:
        String prefix;
        List pushedPrefixes = new java.util.ArrayList();
        final AttributesImpl attrs = new AttributesImpl();
        final NamedNodeMap map = node.getAttributes();
        final int length = map.getLength();

        // Process all namespace declarations
        for (int i = 0; i < length; i++) {
            final Node attr = map.item(i);
            final String qnameAttr = attr.getNodeName();

            // Ignore everything but NS declarations here
            if (qnameAttr.startsWith(XMLNS_PREFIX)) {
                final String uriAttr = attr.getNodeValue();
                final int colon = qnameAttr.lastIndexOf(':');
                prefix = (colon > 0) ? qnameAttr.substring(colon + 1) : EMPTYSTRING;
                if (startPrefixMapping(prefix, uriAttr)) {
                    pushedPrefixes.add(prefix);
                }
            }
        }

        // Process all other attributes
        for (int i = 0; i < length; i++) {
            final Node attr = map.item(i);
            final String qnameAttr = attr.getNodeName();

            // Ignore NS declarations here
            if (!qnameAttr.startsWith(XMLNS_PREFIX)) {
                final String uriAttr = attr.getNamespaceURI();

                // Uri may be implicitly declared
                if (uriAttr != null) {
                    final int colon = qnameAttr.lastIndexOf(':');
                    prefix = (colon > 0) ? qnameAttr.substring(0, colon) : EMPTYSTRING;
                    if (startPrefixMapping(prefix, uriAttr)) {
                        pushedPrefixes.add(prefix);
                    }
                }

                // Add attribute to list
                attrs.addAttribute(attr.getNamespaceURI(), getLocalName(attr), qnameAttr, "CDATA",
                        attr.getNodeValue());
            }
        }

        // Now process the element itself
        final String qname = node.getNodeName();
        final String uri = node.getNamespaceURI();
        final String localName = getLocalName(node);

        // Uri may be implicitly declared
        if (uri != null) {
            final int colon = qname.lastIndexOf(':');
            prefix = (colon > 0) ? qname.substring(0, colon) : EMPTYSTRING;
            if (startPrefixMapping(prefix, uri)) {
                pushedPrefixes.add(prefix);
            }
        }

        // Generate SAX event to start element
        contentHandler.startElement(uri, localName, qname, attrs);

        // Traverse all child nodes of the element (if any)
        next = node.getFirstChild();
        while (next != null) {
            writeNode(next);
            next = next.getNextSibling();
        }

        // Generate SAX event to close element
        contentHandler.endElement(uri, localName, qname);

        // Generate endPrefixMapping() for all pushed prefixes
        final int nPushedPrefixes = pushedPrefixes.size();
        for (int i = 0; i < nPushedPrefixes; i++) {
            endPrefixMapping((String) pushedPrefixes.get(i));
        }
        break;

    case Node.PROCESSING_INSTRUCTION_NODE:
        contentHandler.processingInstruction(node.getNodeName(), node.getNodeValue());
        break;

    case Node.TEXT_NODE:
        final String data = node.getNodeValue();
        contentHandler.characters(data.toCharArray(), 0, data.length());
        break;
    default:
        //nop
    }
}