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:org.eclipse.lyo.testsuite.oslcv2.asset.GetAndUpdateXmlTests.java

@Test
public void removeArtifactFromAsset() throws IOException, TransformerException, ParseException,
        ParserConfigurationException, SAXException, XPathExpressionException {
    String artifactFactory = getArtifactFactory();

    Header[] header = addHeader(new BasicHeader("oslc_asset.name", "/helpFolder/help"));

    String fileName = setupProps.getProperty("createTemplateArtifactXmlFile");
    assertTrue("There needs to be an artifact template file", fileName != null);
    String artifact = OSLCUtils.readFileByNameAsString(fileName);

    // Adds the artifact to the asset
    HttpResponse response = OSLCUtils.postDataToUrl(artifactFactory, creds, OSLCConstants.CT_XML,
            OSLCConstants.CT_XML, artifact, header);
    EntityUtils.consume(response.getEntity());

    // Gets the asset with the artifact added to it
    String resp = getAssetAsString();
    Document document = OSLCUtils.createXMLDocFromResponseBody(resp);

    // Removes the artifact from the asset
    NodeList nodes = getAssetNodeChildren(document);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeName().equals("oslc_asset:artifact")) {
            node.getParentNode().removeChild(node);
        }/*  w  w w . ja  v a  2  s  .  c o  m*/
    }

    String content = OSLCUtils.createStringFromXMLDoc(document);
    putAsset(content);
    resp = getAssetAsString();
    document = OSLCUtils.createXMLDocFromResponseBody(resp);

    // Tests to verify that the artifact was removed
    nodes = getAssetNodeChildren(document);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeName().equals("oslc_asset:artifact")) {
            fail("The artifact was not removed");
        }
    }
}

From source file:org.eclipse.recommenders.jayes.io.XDSLReader.java

private void initializeNodeOutcomes(Document doc, BayesNet net) {

    NodeList nodelist = doc.getElementsByTagName(STATE);
    for (int i = 0; i < nodelist.getLength(); i++) {
        Node node = nodelist.item(i);

        BayesNode bNode = net.getNode(getId(node.getParentNode()));

        bNode.addOutcome(StringEscapeUtils.unescapeXml(getId(node)));

    }/*  w  w  w .  j a v  a  2  s  .  co m*/
}

From source file:org.eclipse.recommenders.jayes.io.XDSLReader.java

private void setParents(Document doc, BayesNet net) {

    NodeList nodelist = doc.getElementsByTagName(PARENTS);
    for (int i = 0; i < nodelist.getLength(); i++) {
        Node node = nodelist.item(i);

        BayesNode bNode = net.getNode(getId(node.getParentNode()));

        List<String> parentNames = newArrayList();
        Iterables.addAll(parentNames,//  w  ww  .  jav  a 2s  . c om
                Splitter.on(CharMatcher.WHITESPACE).omitEmptyStrings().split(node.getTextContent()));

        List<BayesNode> parents = newArrayList();
        for (String parentname : parentNames) {
            parents.add(net.getNode(parentname));
        }
        bNode.setParents(parents);
    }

}

From source file:org.eclipse.recommenders.jayes.io.XDSLReader.java

private void parseProbabilities(Document doc, BayesNet net) {
    NodeList nodelist = doc.getElementsByTagName(PROBABILITIES);
    for (int i = 0; i < nodelist.getLength(); i++) {
        Node node = nodelist.item(i);

        BayesNode bNode = net.getNode(getId(node.getParentNode()));

        String table = node.getTextContent();
        List<Double> probabilities = newArrayList();

        StringTokenizer tok = new StringTokenizer(table);
        while (tok.hasMoreTokens()) {
            probabilities.add(Double.valueOf(tok.nextToken()));
        }//from ww w  .j  a v  a  2 s.c  o  m

        bNode.setProbabilities(Doubles.toArray(probabilities));
    }

}

From source file:org.eclipse.skalli.core.extension.DataMigration11.java

/**
 * Changes from model version 11 -> 12:
 * <ol>/*from   ww w  . ja v a2 s  .  c om*/
 *   <li>Project members now in separate collections</li>
 * </ol>
 */
@Override
public void migrate(Document doc) {
    Map<String, String> roleCache = new HashMap<String, String>();

    List<String> members = new LinkedList<String>();
    List<String> leads = new LinkedList<String>();
    List<String> productOwners = new LinkedList<String>();
    List<String> scrumMasters = new LinkedList<String>();

    // reading old project members and their roles
    NodeList nodes = doc.getElementsByTagName("org.eclipse.skalli.model.core.ProjectMember");
    for (int i = 0; i < nodes.getLength(); i++) {
        Element member = (Element) nodes.item(i);
        String userId = member.getElementsByTagName("userID").item(0).getTextContent();
        LOG.debug("Reading User '" + userId + "' for Migration.");

        NodeList roles = member.getElementsByTagName("roles").item(0).getChildNodes();
        for (int j = 0; j < roles.getLength(); j++) {
            Node roleNode = (Node) roles.item(j);
            if (roleNode instanceof Element && !roleNode.getNodeName().equals("no-comparator")) {
                Element roleElement = (Element) roleNode;
                String role = null;
                if (StringUtils.isBlank(roleElement.getAttribute("reference"))) {
                    role = roleElement.getElementsByTagName("technicalName").item(0).getTextContent();
                    roleCache.put(roleElement.getNodeName(), role);
                } else {
                    role = roleCache.get(roleElement.getNodeName());
                }
                LOG.debug("User '" + userId + "' has role '" + role + "'.");
                if (role.equals("projectmember")) {
                    members.add(userId);
                } else if (role.equals("projectlead")) {
                    leads.add(userId);
                } else if (role.equals("scrummaster")) {
                    scrumMasters.add(userId);
                } else if (role.equals("productowner")) {
                    productOwners.add(userId);
                } else {
                    throw new RuntimeException("unknown role: " + role);
                }
            }
        }
    }

    // remove current "members" section
    Node membersNode = doc.getElementsByTagName("members").item(0);
    if (membersNode == null) {
        throw new RuntimeException(doc.toString());
    }
    Node projectNode = membersNode.getParentNode();
    projectNode.removeChild(membersNode);

    // add (new) members
    addPeopleSection(doc, projectNode, "members", members);

    // add leads
    addPeopleSection(doc, projectNode, "leads", leads);

    // add scrum people
    if (scrumMasters.size() > 0 || productOwners.size() > 0) {
        Node scrumExt = doc.getElementsByTagName("org.eclipse.skalli.model.ext.scrum.ScrumProjectExt").item(0);

        if (scrumExt == null) {
            LOG.warn("there were scrum people, but no scrum extension.");
        } else {
            // add scrum masters
            addPeopleSection(doc, scrumExt, "scrumMasters", scrumMasters);

            // add product owners
            addPeopleSection(doc, scrumExt, "productOwners", productOwners);
        }
    }
}

From source file:org.eclipse.skalli.model.ext.maven.internal.DataMigration1.java

private void remove(NodeList elements) {
    for (int i = 0; i < elements.getLength(); i++) {
        Node item = elements.item(i);
        item.getParentNode().removeChild(item);
    }//w ww .j  a va  2  s.  c  o  m
}

From source file:org.eclipse.skalli.view.internal.servlet.StaticContentServlet.java

/**
 * Resolves all &lt;include&gt; in a given schema and writes the
 * result to the given output stream. Includes that can't be resolved
 * are removed from the schema./* w w  w. j a v  a  2s .com*/
 * @param in  the input stream providing the schema to resolve.
 * @param out  the output stream to write the result to.
 * @throws IOException  if an i/o error occured.
 * @throws SAXException  if parsing of the schema failed.
 * @throws ParserConfigurationException  indicates a serious parser configuration error.
 * @throws TransformerException  if transforming the schema DOM to a character stream failed.
 * @throws TransformerConfigurationException  indicates a serious transformer configuration error.
 */
private void resolveIncludes(InputStream in, OutputStream out) throws IOException, SAXException,
        ParserConfigurationException, TransformerConfigurationException, TransformerException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document schemaDOM = dbf.newDocumentBuilder().parse(new InputSource(in));
    Element schemaRoot = schemaDOM.getDocumentElement();

    // iterate all <include> tags and resolve them if possible
    NodeList includes = schemaDOM.getElementsByTagName("xsd:include");
    while (includes.getLength() > 0) {
        for (int i = 0; i < includes.getLength(); ++i) {
            Node includeNode = includes.item(i);
            Node includeParent = includeNode.getParentNode();
            Node schemaLocation = includeNode.getAttributes().getNamedItem("schemaLocation");
            if (schemaLocation != null) {
                // extract the pure file name from the schemaLocation and
                // try to find an XSD resource in all model extensions matching
                // the given schemaLocation attribute -> if found, replace the include tag
                // with the DOM of the include (without the root tag, of course!)
                URL includeFile = RestUtils.findSchemaResource(schemaLocation.getTextContent());
                if (includeFile != null) {
                    Document includeDOM = dbf.newDocumentBuilder()
                            .parse(new InputSource(includeFile.openStream()));
                    NodeList includeNodes = includeDOM.getDocumentElement().getChildNodes();
                    for (int j = 0; j < includeNodes.getLength(); ++j) {
                        // import and insert the tag before <include>
                        schemaRoot.insertBefore(schemaDOM.importNode(includeNodes.item(j), true), includeNode);
                    }
                }

                // in any case: remove the <include> tag
                includeParent.removeChild(includeNode);
            }
        }
        // resolve includes of includes (if any)
        includes = schemaDOM.getElementsByTagName("xsd:include");
    }

    // serialize the schema DOM to the given output stream
    Transformer xform = TransformerFactory.newInstance().newTransformer();
    xform.setOutputProperty(OutputKeys.INDENT, "yes");
    xform.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    xform.transform(new DOMSource(schemaDOM), new StreamResult(out));
}

From source file:org.etudes.component.app.melete.SubSectionUtilImpl.java

public String bringOneLevelUp(String sectionsSeqXML, String section_id) throws MeleteException {
    try {/*  w  w w  .j ava 2  s. com*/
        org.w3c.dom.Document subSectionW3CDOM = Xml.readDocumentFromString(sectionsSeqXML);
        org.w3c.dom.Element root = subSectionW3CDOM.getDocumentElement();
        org.w3c.dom.Element bringUpThisElement = subSectionW3CDOM.getElementById(section_id);

        if (bringUpThisElement == null) {
            throw new MeleteException("indent_left_fail");
        }
        org.w3c.dom.Node makeSiblingOf = bringUpThisElement.getParentNode();
        org.w3c.dom.Node bringUpBeforeThisElement = makeSiblingOf.getNextSibling();

        //Clone the node that needs to be moved
        org.w3c.dom.Node newNode = bringUpThisElement.cloneNode(true);
        org.w3c.dom.Node nextNode = bringUpThisElement.getNextSibling();
        org.w3c.dom.Node prevNode = null;
        //Iterate through each of the node's siblings and make them its children
        //In the process, also delete the siblings
        while (nextNode != null) {
            org.w3c.dom.Node cNode = nextNode.cloneNode(true);
            prevNode = nextNode;
            newNode.appendChild(cNode);
            nextNode = nextNode.getNextSibling();
            prevNode.getParentNode().removeChild(prevNode);
        }
        //Insert the new node, inbetween or end of list, takes null or bringUpBeforeThisElement
        makeSiblingOf.getParentNode().insertBefore(newNode, bringUpBeforeThisElement);
        //Delete node from original position
        bringUpThisElement.getParentNode().removeChild(bringUpThisElement);

        return writeDocumentToString(subSectionW3CDOM);
    } catch (MeleteException mex) {
        throw mex;
    } catch (Exception ex) {
        if (logger.isDebugEnabled()) {
            logger.error("some other error on indenting right" + ex.toString());
            ex.printStackTrace();
        }
        throw new MeleteException("indent_right_fail");
    }
}

From source file:org.geoserver.rest.catalog.DataStoreFileUploadTest.java

private byte[] appSchemaAlternativeMappingAsBytes() throws Exception {
    byte[] mapping = appSchemaMappingAsBytes();
    if (mapping != null) {
        Document mappingDom = dom(new ByteArrayInputStream(mapping));

        // remove mapping for MappedFeature/gml:name[2] attribute
        NodeList attrMappingNodes = mappingDom.getDocumentElement().getElementsByTagName("AttributeMapping");
        for (int i = 0; i < attrMappingNodes.getLength(); i++) {
            Node attrMapping = attrMappingNodes.item(i);
            NodeList children = attrMapping.getChildNodes();
            for (int j = 0; j < children.getLength(); j++) {
                if ("MappedFeature/gml:name[2]".equals(children.item(j).getTextContent())) {
                    attrMapping.getParentNode().removeChild(attrMapping);
                    break;
                }/*from   w w  w  . ja  va2 s.  co m*/
            }
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        print(mappingDom, output);

        return output.toByteArray();
    } else {
        return null;
    }
}

From source file:org.glom.app.libglom.Document.java

/**
 * getElementsByTagName() is recursive, but we do not want that.
 *
 * @param parentNode/*from w  w  w  .j a va 2  s . c  o m*/
 * @param tagName
 * @return
 */
private List<Node> getChildrenByTagName(final Element parentNode, final String tagName) {
    final List<Node> result = new ArrayList<>();

    final NodeList list = parentNode.getElementsByTagName(tagName);
    final int num = list.getLength();
    for (int i = 0; i < num; i++) {
        final Node node = list.item(i);
        if (node == null) {
            continue;
        }

        final Node itemParentNode = node.getParentNode();
        if (itemParentNode.equals(parentNode)) {
            result.add(node);
        }
    }

    return result;
}