Example usage for org.w3c.dom Node getParentNode

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

Introduction

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

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:de.betterform.xml.xforms.model.Instance.java

/**
 * returns true if current Node's modelitem is readonly or any of it's ancestors is readonly
 * @param n// www  . ja  v  a 2 s  . c  om
 * @return true if any of the ancestors or the node itself is readonly false otherwise
 */
private boolean isReadonly(Node n) {
    if (n.getNodeType() == Node.DOCUMENT_NODE)
        return false;
    if (getModelItem(n).isReadonly()) {
        return true;
    } else if (n.getNodeType() == Node.ATTRIBUTE_NODE) {
        return isReadonly(((Attr) n).getOwnerElement());
    } else {
        return isReadonly(n.getParentNode());
    }
}

From source file:io.fabric8.devops.connector.DevOpsConnector.java

public static String removeBuildParameter(Logger log, String template, String parameterName) {
    try {//w  w  w.j av a 2s  .  c  om
        Document doc = parseXmlText(template);
        Element rootElement = doc.getDocumentElement();
        NodeList stringDefs = rootElement.getElementsByTagName("hudson.model.StringParameterDefinition");
        if (stringDefs != null) {
            for (int i = 0, size = stringDefs.getLength(); i < size; i++) {
                Node item = stringDefs.item(i);
                if (item instanceof Element) {
                    Element element = (Element) item;
                    Element name = DomHelper.firstChild(element, "name");
                    if (name != null) {
                        String textContent = name.getTextContent();
                        if (textContent != null) {
                            if (parameterName.equals(textContent.trim())) {
                                Node parameterDefinitions = item.getParentNode();
                                Node parametersDefinitionProperty = parameterDefinitions != null
                                        ? parameterDefinitions.getParentNode()
                                        : null;
                                DomHelper.detach(item);
                                if (DomHelper.firstChildElement(parameterDefinitions) == null) {
                                    DomHelper.detach(parameterDefinitions);
                                }
                                if (DomHelper.firstChildElement(parametersDefinitionProperty) == null) {
                                    DomHelper.detach(parametersDefinitionProperty);
                                }
                                return DomHelper.toXml(doc);
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("Failed to remove the build parameter from the Jenkins XML. " + e, e);
    }
    return template;
}

From source file:org.gege.caldavsyncadapter.caldav.CaldavFacade.java

public ArrayList<CalendarEvent> getCalendarEvents(DavCalendar calendar) throws URISyntaxException,
        ClientProtocolException, IOException, ParserConfigurationException, SAXException {

    ArrayList<CalendarEvent> calendarEventList = new ArrayList<CalendarEvent>();

    String requestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<D:propfind xmlns:D=\"DAV:\">"
            + "<D:prop>" + "<D:getetag/>" + "</D:prop>" + "</D:propfind>";

    HttpPropFind request = null;/*from  ww  w .ja  va2  s  .  c o m*/

    /*request = new HttpPropFind();
    request.setURI(calendar.getURI());
    request.setHeader("Host", targetHost.getHostName());
    request.setHeader("Depth", "1");
    request.setHeader("Content-Type", "application/xml;charset=\"UTF-8\"");
            
    try {
       request.setEntity(new StringEntity(requestBody, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
       throw new AssertionError("UTF-8 is unknown");
    }*/
    request = this.createPropFindRequest(calendar.getURI(), requestBody, 1);

    Log.d(TAG, "Getting eTag by PROPFIND at " + request.getURI());

    HttpResponse response = httpClient.execute(targetHost, request, mContext);

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

    String line;
    String body = "";
    do {
        line = reader.readLine();
        if (line != null)
            body += line;
    } while (line != null);

    Log.d(TAG, "HttpResponse status=" + response.getStatusLine() + " body= " + body);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document dom = builder.parse(new InputSource(new ByteArrayInputStream(body.getBytes("utf-8"))));
    Element root = dom.getDocumentElement();
    NodeList items = root.getElementsByTagNameNS("*", "getetag");

    for (int i = 0; i < items.getLength(); i++) {
        CalendarEvent calendarEvent = new CalendarEvent(this.mAccount, this.mProvider);

        Node node = items.item(i);

        if (node.getTextContent().trim().length() == 0)
            continue; // not an event

        calendarEvent.setETag(node.getTextContent().trim());
        //calendarEvent.calendarURL = this.url;
        calendarEvent.calendarURL = calendar.getURI().toURL();

        node = node.getParentNode(); // prop
        node = node.getParentNode(); // propstat
        node = node.getParentNode(); // response

        NodeList children = node.getChildNodes();
        for (int j = 0; j < children.getLength(); j++) {
            Node childNode = children.item(j);
            if ((childNode.getLocalName() != null) && (childNode.getLocalName().equalsIgnoreCase("href"))) {
                calendarEvent.setUri(new URI(childNode.getTextContent().trim()));
            }
        }

        calendarEventList.add(calendarEvent);

    }

    return calendarEventList;
}

From source file:com.connexta.arbitro.attr.AttributeSelector.java

/**
 * Creates a new <code>AttributeSelector</code> based on the DOM root of the XML type. Note that
 * as of XACML 1.1 the XPathVersion element is required in any policy that uses a selector, so
 * if the <code>xpathVersion</code> string is null, then this will throw an exception.
 * /*from ww  w  .j  a v a  2s  .  c  om*/
 * @param root the root of the DOM tree for the XML AttributeSelectorType XML type
 * @param metaData the meta-data associated with the containing policy
 * 
 * @return an <code>AttributeSelector</code>
 * 
 * @throws ParsingException if the AttributeSelectorType was invalid
 */
public static AttributeSelector getInstance(Node root, PolicyMetaData metaData) throws ParsingException {
    URI type = null;
    String contextPath = null;
    boolean mustBePresent = false;
    String xpathVersion = metaData.getXPathIdentifier();

    // make sure we were given an xpath version
    if (xpathVersion == null)
        throw new ParsingException("An XPathVersion is required for " + "any policies that use selectors");

    NamedNodeMap attrs = root.getAttributes();

    try {
        // there's always a DataType attribute
        type = new URI(attrs.getNamedItem("DataType").getNodeValue());
    } catch (Exception e) {
        throw new ParsingException("Error parsing required DataType " + "attribute in AttributeSelector", e);
    }

    try {
        // there's always a RequestPath
        contextPath = attrs.getNamedItem("RequestContextPath").getNodeValue();
    } catch (Exception e) {
        throw new ParsingException(
                "Error parsing required " + "RequestContextPath attribute in " + "AttributeSelector", e);
    }

    try {
        // there may optionally be a MustBePresent
        Node node = attrs.getNamedItem("MustBePresent");
        if (node != null)
            if (node.getNodeValue().equals("true"))
                mustBePresent = true;
    } catch (Exception e) {
        // this shouldn't happen, since we check the cases, but still...
        throw new ParsingException("Error parsing optional attributes " + "in AttributeSelector", e);
    }

    // as of 1.2 we need the root element of the policy so we can get
    // the namespace mapping, but in order to leave the APIs unchanged,
    // we'll walk up the tree to find the root rather than pass this
    // element around through all the code
    Node policyRoot = null;
    Node node = root.getParentNode();

    while ((node != null) && (node.getNodeType() == Node.ELEMENT_NODE)) {
        policyRoot = node;
        node = node.getParentNode();
    }

    // create the new selector
    return new AttributeSelector(type, contextPath, policyRoot, mustBePresent, xpathVersion);
}

From source file:com.edgenius.wiki.rss.RSSServiceImpl.java

/**
 * @param spaceUid//from  ww w. j  a  v  a  2s. c  o  m
 * @param spaceUname
 * @param viewer
 * @param skipSecurityCheck 
 * @return
 * @throws FeedException
 */
private Document getFeedDom(Integer spaceUid, String spaceUname, User viewer, boolean skipSecurityCheck)
        throws FeedException {
    ReentrantReadWriteLock lock = null;
    Document dom;
    try {

        File feedFile = new File(FileUtil.getFullPath(rssRoot.getFile().getAbsolutePath(), spaceUid + ".xml"));
        if (!feedFile.exists()) {
            createFeed(spaceUname);
        }

        //do read lock! must after createFeed possibility, otherwise, deadlock 
        lock = lockMap.get(spaceUid.toString());
        if (lock == null) {
            lock = new ReentrantReadWriteLock();
            lockMap.put(spaceUid.toString(), lock);
        }
        lock.readLock().lock();
        //!!! DON'T USE JDOM - although I test DOM, JDOM, DOM4J: JDOM is fastest. And DOM and DOM4J almost 2 time slow. But
        //!!! JDOM is not thread safe, an infinite looping can happen while this method reading different XML source, 
        //in different thread, and SAXBuild are different instance! The problem is mostly caused by NameSpace.getNamespace(), 
        //which using static HashMap and cause HashMap dead lock!!!
        DocumentBuilder builder = xmlBuilderPool.poll();
        if (builder == null) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setCoalescing(true);
            factory.setIgnoringComments(true);
            builder = factory.newDocumentBuilder();
        }
        dom = builder.parse(feedFile);
        xmlBuilderPool.add(builder);

    } catch (Exception e) {
        log.error("Unable get feed " + spaceUname + " with excpetion ", e);
        throw new FeedException("Unable get feed " + spaceUname + " with excpetion " + e);
    } finally {
        if (lock != null)
            lock.readLock().unlock();
    }
    if (dom == null) {
        log.error("Unable get feed " + spaceUname);
        throw new FeedException("Unable get feed " + spaceUname);
    }

    //~~~~~~~~~~~~ Security filter
    if (!skipSecurityCheck) {
        //need filter out the page that viewer has not permission to read.  
        List<Node> forbidPageUuidList = new ArrayList<Node>();
        String pageUuid;
        Node ele;
        NodeList list = dom.getElementsByTagName(PageRSSModule.NS_PREFIX + ":" + PageRSSModule.PAGE_UUID);
        int len = list.getLength();
        for (int idx = 0; idx < len; idx++) {
            ele = list.item(idx);
            pageUuid = ele.getTextContent();
            if (!securityService.isAllowPageReading(spaceUname, pageUuid, viewer)) {
                log.info("User " + (viewer == null ? "anonymous" : viewer.getUsername())
                        + "  has not reading permission for pageUuid " + pageUuid + " on space " + spaceUname
                        + ". Feed item of this page is removed from RSS output.");
                forbidPageUuidList.add(ele.getParentNode());
            }

        }
        if (forbidPageUuidList.size() > 0) {
            NodeList cl = dom.getElementsByTagName(PageRSSModule.CHANNEL);
            if (cl.getLength() > 0) {
                //only one channel tag!
                Node channel = cl.item(0);
                for (Node element : forbidPageUuidList) {
                    channel.removeChild(element);
                }
            }
        }
    }
    return dom;
}

From source file:erwins.util.repack.xml.XMLBuilder.java

/**
 * Find and delete from the underlying Document any text nodes that
 * contain nothing but whitespace, such as newlines and tab or space
 * characters used to indent or pretty-print an XML document.
 *
 * Uses approach I documented on StackOverflow:
 * http://stackoverflow.com/a/979606/4970
 *
 * @return//from www.  j  av  a  2s . c  o  m
 * a builder node at the same location as before the operation.
 * @throws XPathExpressionException
 */
public XMLBuilder stripWhitespaceOnlyTextNodes() throws XPathExpressionException {
    XPathFactory xpathFactory = XPathFactory.newInstance();
    // XPath to find empty text nodes.
    XPathExpression xpathExp = xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']");
    NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(this.getDocument(), XPathConstants.NODESET);

    // Remove each empty text node from document.
    for (int i = 0; i < emptyTextNodes.getLength(); i++) {
        Node emptyTextNode = emptyTextNodes.item(i);
        emptyTextNode.getParentNode().removeChild(emptyTextNode);
    }
    return this;
}

From source file:erwins.util.repack.xml.XMLBuilder.java

/**
 * Return the builder node representing the n<em>th</em> ancestor element
 * of this node, or the root node if n exceeds the document's depth.
 *
 * @param steps/*from   ww  w.j av a 2  s  .  c  o m*/
 * the number of parent elements to step over while navigating up the chain
 * of node ancestors. A steps value of 1 will find a node's parent, 2 will
 * find its grandparent etc.
 *
 * @return
 * the n<em>th</em> ancestor of this node, or the root node if this is
 * reached before the n<em>th</em> parent is found.
 */
public XMLBuilder up(int steps) {
    Node currNode = this.xmlNode;
    int stepCount = 0;
    while (currNode.getParentNode() != null && stepCount < steps) {
        currNode = currNode.getParentNode();
        stepCount++;
    }
    if (currNode instanceof Document) {
        return new XMLBuilder((Document) currNode);
    } else {
        return new XMLBuilder(currNode, null);
    }
}

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

@Override
public String newEmptyObject(String pid, List<String> oldIDs, List<String> collections, String logMessage)
        throws BackendMethodFailedException, BackendInvalidCredsException {
    InputStream emptyObjectStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("EmptyObject.xml");
    Document emptyObject = DOM.streamToDOM(emptyObjectStream, true);

    XPathSelector xpath = DOM.createXPathSelector("foxml", Constants.NAMESPACE_FOXML, "rdf",
            Constants.NAMESPACE_RDF, "d", Constants.NAMESPACE_RELATIONS, "dc", Constants.NAMESPACE_DC, "oai_dc",
            Constants.NAMESPACE_OAIDC);//from www  .  j a v a2  s. c o  m
    //Set pid
    Node pidNode = xpath.selectNode(emptyObject, "/foxml:digitalObject/@PID");
    pidNode.setNodeValue(pid);

    Node rdfNode = xpath.selectNode(emptyObject,
            "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/rdf:RDF/rdf:Description/@rdf:about");
    rdfNode.setNodeValue("info:fedora/" + pid);

    //add Old Identifiers to DC
    Node dcIdentifierNode = xpath.selectNode(emptyObject,
            "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/oai_dc:dc/dc:identifier");
    dcIdentifierNode.setTextContent(pid);
    Node parent = dcIdentifierNode.getParentNode();
    for (String oldID : oldIDs) {
        Node clone = dcIdentifierNode.cloneNode(true);
        clone.setTextContent(oldID);
        parent.appendChild(clone);
    }

    Node collectionRelationNode = xpath.selectNode(emptyObject,
            "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/rdf:RDF/rdf:Description/d:isPartOfCollection");

    parent = collectionRelationNode.getParentNode();
    //remove the placeholder relationNode
    parent.removeChild(collectionRelationNode);

    for (String collection : collections) {
        Node clone = collectionRelationNode.cloneNode(true);
        clone.getAttributes().getNamedItem("rdf:resource").setNodeValue("info:fedora/" + collection);
        parent.appendChild(clone);
    }

    String emptyObjectAsString;
    try {
        emptyObjectAsString = DOM.domToString(emptyObject);
    } catch (TransformerException e) {
        //TODO This is not really a backend exception
        throw new BackendMethodFailedException("Failed to convert DC back to string", e);
    }
    WebResource.Builder request = restApi.path("/").path(urlEncode(pid)).queryParam("state", "I")
            .type(MediaType.TEXT_XML_TYPE);
    int tries = 0;
    while (true) {
        tries++;
        try {
            return request.post(String.class, emptyObjectAsString);
        } catch (UniformInterfaceException e) {
            try {
                handleResponseException(pid, tries, maxTriesPost, e);
            } catch (BackendInvalidResourceException e1) {
                //Ignore, never happens
                throw new RuntimeException(e1);
            }
        }
    }
}

From source file:de.betterform.xml.dom.DOMUtil.java

/**
 * returns a canonical XPath locationpath for a given Node. Each step in the path will contain the positional
 * predicate of the Element. Example '/root[1]/a[1]/b[2]/c[5]/@d'. This would point to<br/>
 * to Attribute named 'd'<br/>//from w  ww. j  a v a2s.c  om
 * on 5th Element 'c"<br/>
 * on 2nd Element 'b'<br/>
 * on first Element a<br/>
 * which is a child of the Document Element.
 *
 * @param node the Node where to start
 * @return canonical XPath locationPath for given Node or the empty string if node is null
 */
public static String getCanonicalPath(Node node) {

    if (node == null) {
        return "";
    }

    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        return "/";
    }

    //add ourselves
    String canonPath;
    String ns = node.getNamespaceURI();
    String nodeName1 = node.getNodeName();
    String nodeName2 = node.getLocalName();
    if (ns != null && ns.equals("http://www.w3.org/1999/xhtml")
            && node.getNodeName().equals(node.getLocalName())) {
        canonPath = "html:" + node.getNodeName();
    } else {
        canonPath = node.getNodeName();
    }
    if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        canonPath = "@" + canonPath;
    } else if (node.getNodeType() == Node.ELEMENT_NODE) {
        int position = DOMUtil.getCurrentNodesetPosition(node);
        //append position if we are an Element
        canonPath += "[" + position + "]";
    }

    //check for parent - if there's none we're root
    Node parent = null;
    if (node.getNodeType() == Node.ELEMENT_NODE || node.getNodeType() == Node.TEXT_NODE) {
        parent = node.getParentNode();
    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        parent = ((Attr) node).getOwnerElement();
    }
    if (parent == null) {
        parent = node.getOwnerDocument().getDocumentElement();
    }
    if (parent.getNodeType() == Node.DOCUMENT_NODE || parent.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE) {
        canonPath = "/" + canonPath;
    } else {
        canonPath = DOMUtil.getCanonicalPath(parent) + "/" + canonPath;
    }

    return canonPath;
}

From source file:be.fedict.eid.tsl.TrustServiceList.java

public void sign(PrivateKey privateKey, X509Certificate certificate) throws IOException {
    LOG.debug("sign with: " + certificate.getSubjectX500Principal());
    if (null == this.tslDocument) {
        /*//from  w w  w  . j av a2s .com
         * Marshall to DOM.
         */
        try {
            marshall();
        } catch (Exception e) {
            throw new IOException("marshaller error: " + e.getMessage(), e);
        }
    }

    /*
     * Remove existing XML signature from DOM.
     */
    Node signatureNode = getSignatureNode();
    if (null != signatureNode) {
        signatureNode.getParentNode().removeChild(signatureNode);
    }

    String tslId = this.trustStatusList.getId();

    /*
     * Create new XML signature.
     */
    try {
        xmlSign(privateKey, certificate, tslId);
    } catch (Exception e) {
        throw new IOException("XML sign error: " + e.getMessage(), e);
    }
    setChanged();
}