Example usage for org.w3c.dom Node getNextSibling

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

Introduction

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

Prototype

public Node getNextSibling();

Source Link

Document

The node immediately following this node.

Usage

From source file:com.crawljax.plugins.errorreport.ErrorReport.java

private Document addMarker(String id, Document doc, String xpath) {
    try {/*from  ww  w . j  av a2  s.  co m*/

        String prefixMarker = "###BEGINMARKER" + id + "###";
        String suffixMarker = "###ENDMARKER###";

        NodeList nodeList = XPathHelper.evaluateXpathExpression(doc, xpath);

        if (nodeList.getLength() == 0 || nodeList.item(0) == null) {
            return doc;
        }
        Node element = nodeList.item(0);

        if (element.getNodeType() == Node.ELEMENT_NODE) {
            Node beginNode = doc.createTextNode(prefixMarker);
            Node endNode = doc.createTextNode(suffixMarker);

            element.getParentNode().insertBefore(beginNode, element);
            if (element.getNextSibling() == null) {
                element.getParentNode().appendChild(endNode);
            } else {
                element.getParentNode().insertBefore(endNode, element.getNextSibling());
            }
        } else if (element.getNodeType() == Node.TEXT_NODE && element.getTextContent() != null) {
            element.setTextContent(prefixMarker + element.getTextContent() + suffixMarker);
        } else if (element.getNodeType() == Node.ATTRIBUTE_NODE) {
            element.setNodeValue(prefixMarker + element.getTextContent() + suffixMarker);
        }

        return doc;
    } catch (Exception e) {
        return doc;
    }
}

From source file:it.cnr.icar.eric.common.security.wss4j.WSS4JSignatureBST.java

/**
 * Compute the Signature over the references.
 * /*  ww  w  .  j a  v a  2  s .c o  m*/
 * This method can be called any time after the references were set. See
 * <code>addReferencesToSign()</code>.
 * 
 * @param referenceList The list of references to sign
 * @param prepend Whether to prepend the signature element to the security header
 * @param siblingElement If prepending, then prepend before this sibling Element
 * 
 * @throws WSSecurityException
 */
public void computeSignature(List<javax.xml.crypto.dsig.Reference> referenceList, boolean prepend,
        Element siblingElement) throws WSSecurityException {
    try {
        java.security.Key key;

        if (privateKey == null)
            key = crypto.getPrivateKey(user, password);
        else
            key = privateKey;

        //            if (secretKey == null) {
        //                  key = crypto.getPrivateKey(user, password);
        //            } else {
        //                key = WSSecurityUtil.prepareSecretKey(sigAlgo, secretKey);
        //            }

        SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(sigAlgo, null);
        SignedInfo signedInfo = signatureFactory.newSignedInfo(c14nMethod, signatureMethod, referenceList);

        sig = signatureFactory.newXMLSignature(signedInfo, keyInfo, null,
                getWsConfig().getIdAllocator().createId("SIG-", null), null);

        //
        // Figure out where to insert the signature element
        //
        XMLSignContext signContext = null;
        if (prepend) {
            if (siblingElement == null) {
                Node child = securityHeader.getFirstChild();
                while (child != null && child.getNodeType() != Node.ELEMENT_NODE) {
                    child = child.getNextSibling();
                }
                siblingElement = (Element) child;
            }
            if (siblingElement == null) {
                signContext = new DOMSignContext(key, securityHeader);
            } else {
                signContext = new DOMSignContext(key, securityHeader, siblingElement);
            }
        } else {
            signContext = new DOMSignContext(key, securityHeader);
        }

        signContext.putNamespacePrefix(WSConstants.SIG_NS, WSConstants.SIG_PREFIX);
        if (WSConstants.C14N_EXCL_OMIT_COMMENTS.equals(canonAlgo)) {
            signContext.putNamespacePrefix(WSConstants.C14N_EXCL_OMIT_COMMENTS,
                    WSConstants.C14N_EXCL_OMIT_COMMENTS_PREFIX);
        }
        signContext.setProperty(STRTransform.TRANSFORM_WS_DOC_INFO, wsDocInfo);
        wsDocInfo.setCallbackLookup(callbackLookup);

        // Add the elements to sign to the Signature Context
        wsDocInfo.setTokensOnContext((DOMSignContext) signContext);
        if (secRef != null && secRef.getElement() != null) {
            WSSecurityUtil.storeElementInContext((DOMSignContext) signContext, secRef.getElement());
        }
        sig.sign(signContext);

        signatureValue = sig.getSignatureValue().getValue();
    } catch (Exception ex) {
        log.error(ex);
        throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, null, null, ex);
    }
}

From source file:org.structr.web.entity.dom.DOMNode.java

private static void getAllChildNodes(final DOMNode node, final Set<DOMNode> allChildNodes) {

    Node n = node.getFirstChild();

    while (n != null) {

        if (n instanceof DOMNode) {

            DOMNode domNode = (DOMNode) n;

            if (!allChildNodes.contains(domNode)) {

                allChildNodes.add(domNode);
                allChildNodes.addAll(getAllChildNodes(domNode));

            } else {

                // break loop!
                break;
            }/*from www .  ja v  a  2  s  . c  o m*/
        }

        n = n.getNextSibling();
    }
}

From source file:importer.handler.post.stages.Splitter.java

/**
 * Rule 1 states that the versions of every element are also 
 * present in its parents, up to the root.
 * @param elem the element to start from
 *///from ww  w.  java2s  . c o  m
void verifyRule1(Element elem) {
    String pVers = elem.getAttribute(VERSIONS);
    Node child = elem.getFirstChild();
    // descend depth-first
    while (child != null) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            String cVers = ((Element) child).getAttribute(VERSIONS);
            if (cVers != null && pVers != null) {
                if (!verifyMembership(pVers, cVers))
                    System.out.println("Rule 1 broken for element " + elem.getNodeName() + " with child "
                            + child.getNodeName() + ": \"" + cVers + "\" not contained in \"" + pVers + "\"");
                // recurse
                verifyRule1((Element) child);
            } else
                System.out.println("Missing parent (" + pVers + ") or child versions (" + cVers + ")");
        }
        child = child.getNextSibling();
    }
}

From source file:com.l2jfree.gameserver.model.entity.Instance.java

private void parseInstance(Node n) throws Exception {
    L2Spawn spawnDat;/*from   w  w w .j  a v a2s.  c om*/
    L2NpcTemplate npcTemplate;
    String name;
    name = n.getAttributes().getNamedItem("name").getNodeValue();
    setName(name);
    Node template = n.getAttributes().getNamedItem("template");
    if (template != null)
        _template = Integer.parseInt(template.getNodeValue());

    Node a;
    Node first = n.getFirstChild();
    for (n = first; n != null; n = n.getNextSibling()) {
        if ("activityTime".equalsIgnoreCase(n.getNodeName())) {
            a = n.getAttributes().getNamedItem("val");
            if (a != null) {
                _checkTimeUpTask = ThreadPoolManager.getInstance()
                        .scheduleGeneral(new CheckTimeUp(Integer.parseInt(a.getNodeValue()) * 60000), 15000);
                _instanceEndTime = System.currentTimeMillis()
                        + _checkTimeUpTask.getDelay(TimeUnit.MILLISECONDS);
            }
        }
        /*else if ("timeDelay".equalsIgnoreCase(n.getNodeName()))
        {
           a = n.getAttributes().getNamedItem("val");
           if (a != null)
              setTimeDelay(Integer.parseInt(a.getNodeValue()));
        }*/
        else if ("allowSummon".equalsIgnoreCase(n.getNodeName())) {
            a = n.getAttributes().getNamedItem("val");
            if (a != null)
                setAllowSummon(Boolean.parseBoolean(a.getNodeValue()));
        } else if ("emptyDestroyTime".equalsIgnoreCase(n.getNodeName())) {
            a = n.getAttributes().getNamedItem("val");
            if (a != null)
                _emptyDestroyTime = Long.parseLong(a.getNodeValue()) * 1000;
        } else if ("PvPInstance".equalsIgnoreCase(n.getNodeName())) {
            a = n.getAttributes().getNamedItem("val");
            if (a != null)
                setPvPInstance(Boolean.parseBoolean(a.getNodeValue()));
        } else if ("returnTeleport".equalsIgnoreCase(n.getNodeName())) {
            int tpx = 0, tpy = 0, tpz = 0;

            tpx = Integer.parseInt(n.getAttributes().getNamedItem("x").getNodeValue());
            tpy = Integer.parseInt(n.getAttributes().getNamedItem("y").getNodeValue());
            tpz = Integer.parseInt(n.getAttributes().getNamedItem("z").getNodeValue());

            setReturnTeleport(tpx, tpy, tpz);
        } else if ("doorList".equalsIgnoreCase(n.getNodeName())) {
            for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                int doorId = 0;
                boolean doorState = false;
                if ("door".equalsIgnoreCase(d.getNodeName())) {
                    doorId = Integer.parseInt(d.getAttributes().getNamedItem("doorId").getNodeValue());
                    if (d.getAttributes().getNamedItem("open") != null)
                        doorState = Boolean.parseBoolean(d.getAttributes().getNamedItem("open").getNodeValue());
                    addDoor(doorId, doorState);
                }
            }
        } else if ("spawnList".equalsIgnoreCase(n.getNodeName())) {
            for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                int npcId = 0, x = 0, y = 0, z = 0, respawn = 0, heading = 0, amount = 1;

                if ("spawn".equalsIgnoreCase(d.getNodeName())) {
                    npcId = Integer.parseInt(d.getAttributes().getNamedItem("npcId").getNodeValue());
                    x = Integer.parseInt(d.getAttributes().getNamedItem("x").getNodeValue());
                    y = Integer.parseInt(d.getAttributes().getNamedItem("y").getNodeValue());
                    z = Integer.parseInt(d.getAttributes().getNamedItem("z").getNodeValue());
                    heading = Integer.parseInt(d.getAttributes().getNamedItem("heading").getNodeValue());
                    // these have default values in schema, but DF doesn't seem to care
                    Node opt = d.getAttributes().getNamedItem("respawnDelay");
                    if (opt != null)
                        respawn = Integer.parseInt(opt.getNodeValue());
                    opt = d.getAttributes().getNamedItem("amount");
                    if (opt != null)
                        amount = Integer.parseInt(opt.getNodeValue());

                    npcTemplate = NpcTable.getInstance().getTemplate(npcId);
                    if (npcTemplate != null) {
                        spawnDat = new L2Spawn(npcTemplate);
                        spawnDat.setLocx(x);
                        spawnDat.setLocy(y);
                        spawnDat.setLocz(z);
                        spawnDat.setAmount(amount);
                        spawnDat.setHeading(heading);
                        spawnDat.setRespawnDelay(respawn);
                        if (respawn == 0)
                            spawnDat.stopRespawn();
                        else
                            spawnDat.startRespawn();
                        spawnDat.setInstanceId(getId());
                        spawnDat.doSpawn();
                    } else {
                        _log.warn("Instance: Data missing in NPC table for ID: " + npcTemplate + " in Instance "
                                + getId());
                    }
                }
            }
        } else if ("spawnPoint".equalsIgnoreCase(n.getNodeName())) {
            try {
                int x = Integer.parseInt(n.getAttributes().getNamedItem("x").getNodeValue());
                int y = Integer.parseInt(n.getAttributes().getNamedItem("y").getNodeValue());
                int z = Integer.parseInt(n.getAttributes().getNamedItem("z").getNodeValue());

                _spawnLoc = new Location(x, y, z);
            } catch (Exception e) {
                _log.warn("Error parsing instance xml: ", e);
            }
        }
    }
    if (_log.isDebugEnabled())
        _log.info(name + " Instance Template for Instance " + getId() + " loaded");
}

From source file:XMLConfig.java

/** Create the node specified by the DOM path.
 * @param path DOM path/* w w w  .  j a  v  a2 s.  c om*/
 * @param n node where the search should start, or null for the root
 * @param overwrite whether to overwrite (true) or add (false) -- only applies for last node!
 * @return the node that was created, or the parent node of the attribute if it was an attribute
 */
public Node createNode(String path, Node n, boolean overwrite) {
    if (isDelegated()) {
        return _parent.createNode(path, n, overwrite);
    }

    if (n == null) {
        n = _document;
    }
    while (path.indexOf('/') > -1) {
        Node child = null;
        String nodeName = path.substring(0, path.indexOf('/'));
        path = path.substring(path.indexOf('/') + 1);
        child = n.getFirstChild();
        while (child != null) {
            if (child.getNodeName().equals(nodeName)) {
                // found
                n = child;
                break;
            }
            child = child.getNextSibling();
        }
        if (child == null) {
            // not found
            child = _document.createElement(nodeName);
            n.appendChild(child);
            n = child;
        }
    }

    String nodeName;
    if (path.indexOf('.') > -1) {
        nodeName = path.substring(0, path.indexOf('.'));
    } else {
        if (path.length() == 0) {
            throw new XMLConfigException("Cannot set node with empty name");
        }
        nodeName = path;
    }
    Node child = null;
    if (nodeName.length() > 0) {
        if (overwrite) {
            child = n.getFirstChild();
            while (child != null) {
                if (child.getNodeName().equals(nodeName)) {
                    // found
                    n = child;
                    break;
                }
                child = child.getNextSibling();
            }
            if (child == null) {
                child = _document.createElement(nodeName);
                n.appendChild(child);
                n = child;
            }
        } else {
            child = _document.createElement(nodeName);
            n.appendChild(child);
            n = child;
        }
    }

    if (path.indexOf('.') > -1) {
        if (!(n instanceof Element)) {
            throw new XMLConfigException(
                    "Node " + n.getNodeName() + " should be an element so it can contain attributes");
        }
        return n;
    } else {
        if (overwrite) {
            child = n.getFirstChild();
            // remove all children
            while (child != null) {
                Node temp = child.getNextSibling();
                n.removeChild(child);
                child = temp;
            }
            return n;
        } else {
            return child;
        }
    }
}

From source file:edu.wpi.margrave.MCommunicator.java

/**
 * Takes a MARGRAVE-COMMAND node and performs the appropriate action.
 *
 * @param margraveCommandNode/*ww  w . jav a  2  s.c  o m*/
 * @param originalXMLText
 * @return
 * @throws MBaseException
 */
private static Document xmlHelper(Node margraveCommandNode, String originalXMLText) throws MBaseException {
    //List<Node> childNodes = getElementChildren(node);

    writeToLog("\n  In XML Helper...");

    Document theResponse = null;

    if (margraveCommandNode.getNodeType() == Node.ELEMENT_NODE) {
        String type = getNodeAttribute(margraveCommandNode, "type");
        writeToLog("  At command node. Type attribute was: " + type + "\n");
        if (type == null)
            return MEnvironment.errorResponse(MEnvironment.sUnknown, MEnvironment.sCommand,
                    "<null command type>");

        if (type.equalsIgnoreCase("SET")) {
            Node setNode = getChildNode(margraveCommandNode, "SET");

            String setParameter = getNodeAttribute(setNode, "parameter");
            String setSubParameter = getNodeAttribute(setNode, "subparameter");
            String setValue = getNodeAttribute(setNode, "value");

            if ("CEILING".equalsIgnoreCase(setParameter)) {
                try {
                    int intValue = Integer.parseInt(setValue);
                    // Global parameters for size ceilings per sort
                    theResponse = MEnvironment.setSortCeiling(setSubParameter, intValue);

                } catch (NumberFormatException e) {
                    theResponse = MEnvironment.errorResponse(MEnvironment.sNotDocument, "Not an integer",
                            setValue);
                }
            } else {
                theResponse = MEnvironment.errorResponse(MEnvironment.sCommand, MEnvironment.sUnknown,
                        setParameter);
            }

        } else if (type.equalsIgnoreCase("EXPLORE")) {
            theResponse = handleExplore(originalXMLText, margraveCommandNode);
        } else if (type.equalsIgnoreCase("INFO")) {
            writeToLog("In Info");
            String idString = getInfoId(margraveCommandNode);
            writeToLog("\nPast getting id info");
            if (idString != null && idString.length() > 0) {
                theResponse = MEnvironment.printInfo(idString);
            } else {
                theResponse = MEnvironment.printSystemInfo();
            }
            writeToLog("Returning from info");
        }

        //Create Statement
        else if (type.equalsIgnoreCase("CREATE POLICY LEAF")) {
            String pname = getPolicyName(margraveCommandNode);
            String vname = getVocabName(margraveCommandNode);
            theResponse = MEnvironment.createPolicyLeaf(pname, vname);
        } else if (type.equalsIgnoreCase("CREATE POLICY SET")) {
            String pname = getPolicyName(margraveCommandNode);
            String vname = getVocabName(margraveCommandNode);
            theResponse = MEnvironment.createPolicySet(pname, vname);
        } else if (type.equalsIgnoreCase("CREATE VOCABULARY")) {
            writeToLog("In Create Vocabulary\n");
            String vname = getVocabName(margraveCommandNode);
            writeToLog("Got Vocab name. It is: " + vname + "\n");
            theResponse = MEnvironment.createVocabulary(vname);
            if (theResponse == null) {
                writeToLog("The result of create vocabulary was null!!\n");
            }
            writeToLog("Finished Create Vocabulary\n");
        } else if (type.equalsIgnoreCase("LOAD XACML POLICY")) {
            String pname = getPolicyName(margraveCommandNode);
            String fileName = getLoadFileName(margraveCommandNode);
            String schemaFileName = getLoadSchemaFileName(margraveCommandNode);
            writeToLog("\n Loading policy in file: " + fileName + "; id to use: " + pname);
            theResponse = MEnvironment.loadXACML(pname, fileName, schemaFileName);
        } else if (type.equalsIgnoreCase("LOAD SQS POLICY")) {
            String pname = getPolicyName(margraveCommandNode);
            String fileName = getLoadFileName(margraveCommandNode);
            writeToLog("\n Loading policy in file: " + fileName + "; id to use: " + pname);
            theResponse = MEnvironment.loadSQS(pname, fileName);
        }

        else if (type.equalsIgnoreCase("PREPARE")) {
            String pname = getPolicyName(margraveCommandNode);
            theResponse = MEnvironment.preparePolicy(pname);
        } else if (type.equalsIgnoreCase("DELETE VOCABULARY")) {
            String vname = getVocabName(margraveCommandNode);
            theResponse = MEnvironment.deleteVocabulary(vname);
        }

        else if (type.equalsIgnoreCase("SET TARGET FOR POLICY")) {
            String pname = getPolicyName(margraveCommandNode);

            // Target fmla
            Node targetNode = getChildNode(margraveCommandNode, "TARGET");
            assert (targetNode != null);
            MExploreCondition targetCondition = exploreHelper(targetNode.getFirstChild(), null);
            Formula target = targetCondition.fmla;

            theResponse = MEnvironment.setPolicyTarget(pname, target);
        } else if (type.equalsIgnoreCase("SET COMBINE FOR POLICY")) {
            String pname = getPolicyName(margraveCommandNode);
            Set<String> rFA = new HashSet<String>();
            Map<String, Set<String>> rO = new HashMap<String, Set<String>>();

            handleComb(margraveCommandNode, rFA, rO);
            theResponse = MEnvironment.setCombine(pname, rFA, rO);
        } else if (type.equalsIgnoreCase("QUIT")) {
            MEnvironment.quitMargrave();
        }

        else if (type.equalsIgnoreCase("RESET")) {
            // "<MARGRAVE-COMMAND type=\"RESET\"><RESET id=\"Myqry\" /></MARGRAVE-COMMAND>"
            String id = getAttributeOfChildNodeOrNode(margraveCommandNode, "RESET", "id");
            theResponse = MEnvironment.resetIterator(id);
        } else if (type.equalsIgnoreCase("IS-POSSIBLE")) {
            String id = getAttributeOfChildNodeOrNode(margraveCommandNode, "IS-POSSIBLE", "id");
            theResponse = MEnvironment.isPoss(id);
            writeToLog("Returning from IS-POSSIBLE");
        }
        /*else if (type.equalsIgnoreCase("IS-GUARANTEED")) {
         String id = getAttributeOfChildNodeOrNode(margraveCommandNode, "IS-GUARANTEED", "id");
         theResponse = MEnvironment.isGuar(id);
             }*/
        else if (type.equalsIgnoreCase("SHOW")) {
            writeToLog("In show");
            String showType = getShowType(margraveCommandNode);
            writeToLog("In show");
            String id = getAttributeOfChildNodeOrNode(margraveCommandNode, "SHOW", "id");

            Node showNode = getChildNode(margraveCommandNode, "SHOW");

            writeToLog("\nshowtype: " + showType + "\n");
            if (showType.equalsIgnoreCase("ONE")) {
                writeToLog("\nIn SHOW ONE:");

                Node includeNode = getIncludeNode(showNode);
                List<Node> idbChildNodes = getElementChildren(includeNode);
                HashMap<String, Set<List<MTerm>>> includeMap = atomicFormulasToHashmap(idbChildNodes);

                try {
                    writeToLog("\n  id was: " + id + "; includeMap was: " + includeMap
                            + "; idbChildNodes had this many elements: " + idbChildNodes.size());
                    theResponse = MEnvironment.getFirstModel(id, includeMap);
                } catch (MBaseException e) {
                    theResponse = MEnvironment.exceptionResponse(e);
                }
            } else if (showType.equalsIgnoreCase("NEXT")) {
                writeToLog("\nIn SHOW NEXT:");

                Node includeNode = getIncludeNode(showNode);
                List<Node> idbChildNodes = getElementChildren(includeNode);
                HashMap<String, Set<List<MTerm>>> includeMap = atomicFormulasToHashmap(idbChildNodes);

                try {
                    writeToLog("\n  id was: " + id + "; includeMap was: " + includeMap
                            + "; idbChildNodes had this many elements: " + idbChildNodes.size());
                    theResponse = MEnvironment.getNextModel(id, includeMap);
                } catch (MBaseException e) {
                    theResponse = MEnvironment.exceptionResponse(e);
                }
            }
            /*else if (showType.equalsIgnoreCase("CEILING")) {
            theResponse = MEnvironment.showCeiling(id);
                 }*/
            else if (showType.equalsIgnoreCase("REALIZED") || showType.equalsIgnoreCase("UNREALIZED")) {
                String popId;
                if (showType.equalsIgnoreCase("REALIZED")) {
                    popId = getPopulatedId(margraveCommandNode); // command
                } else {
                    popId = getUnpopulatedId(margraveCommandNode); // command
                }

                Node forCasesNode = getForCasesNode(showNode);
                List<Node> atomicFormulaNodes = getElementChildren(showNode);

                // not this call
                //NodeList atomicFormulaNodes = getAtomicFormulaNodesFromList(n);

                // atomicFormulasToHashmap will ignore the FOR-CASES element.
                Map<String, Set<List<MTerm>>> atomicFormulas = atomicFormulasToHashmap(atomicFormulaNodes);

                // Default map is empty. If FOR CASES, populate it.
                Map<String, Set<List<MTerm>>> forCasesAtomicFormulas = new HashMap<String, Set<List<MTerm>>>();
                if (forCasesNode != null) {
                    //NodeList forCasesAtomicFormulaNodes = getAtomicFormulaNodesFromList(forCasesNode);
                    List<Node> forCasesAtomicFormulaNodes = getElementChildren(forCasesNode);
                    forCasesAtomicFormulas = atomicFormulasToHashmap(forCasesAtomicFormulaNodes);
                }

                //writeToLog(showType+" " + popIdString + " " + atomicFormulas + " --- " + forCasesAtomicFormulas);

                // Get the result and return it
                if (showType.equalsIgnoreCase("REALIZED")) {
                    theResponse = MEnvironment.showRealized(popId, atomicFormulas, forCasesAtomicFormulas);
                } else {
                    theResponse = MEnvironment.showUnrealized(popId, atomicFormulas, forCasesAtomicFormulas);
                }

            } // end pop/unpop

        } // end show
        else if (type.equalsIgnoreCase("COUNT")) {
            String id = getCountId(margraveCommandNode);
            theResponse = MEnvironment.countModels(id);

            Node sizeNode = getSizeNode(margraveCommandNode);
            if (sizeNode != null) {
                Integer countSize = Integer.parseInt(getCountSize(sizeNode));
                theResponse = MEnvironment.countModels(id, countSize);
            } else {
                theResponse = MEnvironment.countModels(id);
            }
        }

        else if (type.equalsIgnoreCase("GET-INFO")) {
            // n is the margrave-command node.
            String getType = getGetInfoType(margraveCommandNode);
            Node getNode = getChildNode(margraveCommandNode, "GET-INFO");
            String pname = getPolicyName(getNode);
            String decname = getDecisionName(getNode);

            // decname will be null, if the user doesn't want to limit by decision

            writeToLog("\n");
            writeToLog("GET-INFO: " + getType + " " + getNode + " " + pname + " " + decname);

            String rname = "";

            if (getType.equalsIgnoreCase("HIGHER-PRIORITY-THAN")) {
                theResponse = MEnvironment.getHigherPriorityThan(pname, rname);
            } else if (getType.equalsIgnoreCase("RULES")) {
                theResponse = MEnvironment.getRulesIn(pname, false, decname);
            } else if (getType.equalsIgnoreCase("QUALIFIED-RULES")) {
                theResponse = MEnvironment.getRulesIn(pname, true, decname);
            }
        }

        //Add Statement
        else if (type.equalsIgnoreCase("ADD")) {

            Node childNode = margraveCommandNode.getFirstChild();

            if (childNode.getNodeName().equalsIgnoreCase("VOCAB-IDENTIFIER")) {
                theResponse = handleAddVocabFact(margraveCommandNode, childNode);
            } else if (childNode.getNodeName().equalsIgnoreCase("POLICY-IDENTIFIER")) {
                String pname = getPolicyName(margraveCommandNode);

                Node secondChildNode = childNode.getNextSibling(); // WORRY Shouldn't be hardcoded in!!
                if (secondChildNode.getNodeName().equalsIgnoreCase("RULE")) {
                    String rname = getRuleName(margraveCommandNode);

                    // WORRY This should be changed to be made more generic, because it assumes too much
                    Node ruleNode = childNode.getNextSibling();

                    // Decision
                    String decName = getDecisionType(ruleNode);

                    List<String> varOrdering = new ArrayList<String>();
                    varOrdering = getListElements(ruleNode, "DECISION-TYPE", "id");

                    // Target fmla
                    Node targetNode = getChildNode(ruleNode, "TARGET");
                    assert (targetNode != null);
                    MExploreCondition targetCondition = exploreHelper(targetNode.getFirstChild(),
                            new ArrayList<String>());
                    Formula target = targetCondition.fmla;

                    // condition is used exclusively for XACML, so it's ignored here.
                    Formula condition = Formula.TRUE;
                    theResponse = MEnvironment.addRule(pname, rname, decName, varOrdering, target, condition,
                            targetCondition);
                } else if (secondChildNode.getNodeName().equalsIgnoreCase("VARIABLE-DECLARATION")) {
                    String varname = getAttributeOfChildNodeOrNode(secondChildNode, "VARIABLE-DECLARATION",
                            "varname");
                    String vartype = getAttributeOfChildNodeOrNode(secondChildNode, "VARIABLE-DECLARATION",
                            "sort");

                    theResponse = MEnvironment.addVarDec(pname, varname, vartype);
                }

            } else if (childNode.getNodeName().equalsIgnoreCase("PARENT")) {
                // Declaring that <parent> is a policy set with a new child <child>
                String parent = getParentName(childNode);
                String child = getChildName(childNode);
                theResponse = MEnvironment.addChild(parent, child);
            }
        } else {
            theResponse = MEnvironment.errorResponse(MEnvironment.sUnknown, MEnvironment.sCommand, "");
        }
    } else {
        theResponse = MEnvironment.errorResponse(MEnvironment.sNotDocument, "", "");
    }

    // Finally -- did we assign a proper response? If not, none of the above cases was matched.
    // _SHOULD_ have elses everywhere. This is just in case.
    if (theResponse == null)
        theResponse = MEnvironment.errorResponse(MEnvironment.sFailure, "",
                "Fatal error: No matching case in java engine. (If you receive this error, please notify the Margrave developers.)");

    return theResponse;
}

From source file:Main.java

public static void copyInto(Node src, Node dest) throws DOMException {

    Document factory = dest.getOwnerDocument();

    //Node start = src;
    Node parent = null;/*from w w  w  .  ja v a  2s .c  o  m*/
    Node place = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr) attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException(
                    "can't copy node type, " + type + " (" + place.getNodeName() + ')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place = place.getFirstChild();
            dest = node;
        } else if (parent == null) {
            place = null;
        } else {
            // advance
            place = place.getNextSibling();
            while (place == null && parent != null) {
                place = parent.getNextSibling();
                parent = parent.getParentNode();
                dest = dest.getParentNode();
            }
        }

    }

}

From source file:XMLConfig.java

/** Returns the value as specified by the DOM path.
 * @param path DOM path/* w  w w.j a v  a 2 s .  c o m*/
 * @param n node where the search begins
 * @param accum accumulator
 * @param dotRead whether a dot has been read
 */
private void getMultipleHelper(String path, Node n, List<Node> accum, boolean dotRead) {
    int dotPos = path.indexOf('.');
    boolean initialDot = (dotPos == 0);
    if ((path.length() > 0) && (dotPos == -1) && (!path.endsWith("/"))) {
        path = path + "/";
    }
    int slashPos = path.indexOf('/');

    if (dotPos != -1 && path.indexOf('.', dotPos + 1) != -1)
        throw new XMLConfigException(
                "An attribute cannot have subparts (foo.bar.fum and foo.bar/fum not allowed)");

    if (dotPos != -1 && path.indexOf('/', dotPos + 1) != -1)
        throw new XMLConfigException(
                "An attribute cannot have subparts (foo.bar.fum and foo.bar/fum not allowed)");

    if (((slashPos > -1) || (dotPos > -1)) && !dotRead || initialDot) {
        String nodeName;
        if ((slashPos > -1) && ((dotPos == -1) || (slashPos < dotPos))) {
            nodeName = path.substring(0, slashPos);
            path = path.substring(slashPos + 1);
        } else {
            if (slashPos > -1) {
                throw new XMLConfigException(
                        "An attribute cannot have subparts (foo.bar.fum and foo.bar/fum not allowed)");
            }
            if (!initialDot) {
                nodeName = path.substring(0, dotPos);
                path = path.substring(dotPos + 1);
                dotRead = true;
            } else {
                path = path.substring(1);
                getMultipleAddAttributesHelper(path, n, accum);
                return;
            }
        }
        Node child = n.getFirstChild();
        if (nodeName.equals("*")) {
            while (child != null) {
                if (!child.getNodeName().equals("#text") && !child.getNodeName().equals("#comment")) {
                    if (dotRead) {
                        getMultipleAddAttributesHelper(path, child, accum);
                    } else {
                        getMultipleHelper(path, child, accum, false);
                    }
                }
                child = child.getNextSibling();
            }
            return;
        } else {
            while (child != null) {
                if (child.getNodeName().equals(nodeName)) {
                    // found
                    if (dotRead) {
                        getMultipleAddAttributesHelper(path, child, accum);
                    } else {
                        getMultipleHelper(path, child, accum, false);
                    }
                }
                child = child.getNextSibling();
            }
            return;
        }
    } else {
        accum.add(n);
    }
}

From source file:com.draagon.meta.loader.xml.XMLFileMetaDataLoader.java

/** 
 * Parse the MetaAttribute Value // www.j  a v a2s .c o  m
 */
protected void parseMetaAttributeValue(MetaAttribute attr, Element el) {

    ///////////////////////////////////////////////////
    // Get the Node value

    // Get the first node
    Node nv = el.getFirstChild();

    // Loop through and ignore the comments
    while (nv != null && nv.getNodeType() == Node.COMMENT_NODE) {
        nv.getNextSibling();
    }

    // If a valid node exists, then get the data
    if (nv != null) {
        switch (nv.getNodeType()) {
        // If CDATA just set the whole thing
        case Node.CDATA_SECTION_NODE:
            attr.setValueAsString(((CharacterData) nv).getData());
            break;

        // If an Element just pass it in for parsing
        case Node.ELEMENT_NODE:
            attr.setValue(nv);
            break;

        // If just text, then pass it in
        case Node.TEXT_NODE:
            attr.setValueAsString(nv.getNodeValue());
            break;

        default:
            log.warn("Unsupported Node Type for node [" + nv + "]");
        }
    }
}