Example usage for org.w3c.dom Node cloneNode

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

Introduction

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

Prototype

public Node cloneNode(boolean deep);

Source Link

Document

Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes.

Usage

From source file:de.betterform.connector.ModelSubmissionHandler.java

/**
 * Purpose:<br/>/*from  w  w w.j  a v a2s.  c  o  m*/
 * The ModelSubmissionHandler can be used to exchange data between XForms models. It is capable of replacing data
 * in a certain instance of the receiver model.<br/><br/>
 *
 * Syntax: model:[Model ID]#instance('[Instance ID]')/[XPath]<br/><br/>
 *
 * Caveats:<br/>
 * - Model and Instance IDs must be known to allow explicit addressing<br/>
 * - the form author has to make sure that no ID collisions take place<br/>
 * - the XPath must be explicitly given even if the the target Node is the root Node of the instance
 *
 *
 * @param submission the submission issuing the request.
 * @param instance   the instance data to be serialized and submitted.
 * @return
 * @throws de.betterform.xml.xforms.exception.XFormsException
 *          if any error occurred during submission.
 */

public Map submit(Submission submission, Node instance) throws XFormsException {
    try {
        String replaceMode = submission.getReplace();
        if (!(replaceMode.equals("none") || replaceMode.equals("instance"))) {
            throw new XFormsException(
                    "ModelSubmissionHandler only supports 'none' or 'instance' as replace mode");
        }

        String submissionMethod = submission.getMethod();
        String resourceAttr = getURI();
        String resourceModelId = null;
        String instanceId = null;
        String xpath = null;

        try {
            int devider = resourceAttr.indexOf("#");
            resourceModelId = resourceAttr.substring(resourceAttr.indexOf(":") + 1, devider);

            int instanceIdStart = resourceAttr.indexOf("(") + 1;
            int instanceIdEnd = resourceAttr.indexOf(")");
            instanceId = resourceAttr.substring(instanceIdStart + 1, instanceIdEnd - 1);
            if (resourceAttr.indexOf("/") != -1) {
                xpath = resourceAttr.substring(resourceAttr.indexOf("/"));
            } else {
                throw new XFormsException(
                        "Syntax error: xpath mustn't be null. You've to provide at least the path to the rootnode.");
            }
        } catch (IndexOutOfBoundsException e) {
            throw new XFormsException("Syntax error in expression: " + resourceAttr);
        }

        Model providerModel;
        Model receiverModel;
        if (submissionMethod.equalsIgnoreCase("get")) {
            providerModel = submission.getContainerObject().getModel(resourceModelId);
            receiverModel = submission.getModel();
            Node targetNode = XPathUtil.getAsNode(XPathCache.getInstance().evaluate(
                    providerModel.getInstance(instanceId).getRootContext().getNodeset(), 1, xpath,
                    providerModel.getPrefixMapping(), providerModel.getXPathFunctionContext()), 1);

            if (targetNode == null) {
                throw new XFormsException("targetNode for xpath: " + xpath + " not found");
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("targetNode to replace............");
                DOMUtil.prettyPrintDOM(targetNode);
            }

            Document result = DOMUtil.newDocument(true, false);
            result.appendChild(result.importNode(targetNode.cloneNode(true), true));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("result Instance after insertion ............");
                DOMUtil.prettyPrintDOM(result);
            }

            Map response = new HashMap(1);
            response.put(XFormsProcessor.SUBMISSION_RESPONSE_DOCUMENT, result);
            return response;
        } else if (submissionMethod.equalsIgnoreCase("post")) {
            providerModel = submission.getModel();

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Instance Data to post............");
                DOMUtil.prettyPrintDOM(instance);
            }

            receiverModel = submission.getContainerObject().getModel(resourceModelId);
            Node targetNode = XPathUtil.getAsNode(XPathCache.getInstance().evaluate(
                    receiverModel.getInstance(instanceId).getRootContext().getNodeset(), 1, xpath,
                    receiverModel.getPrefixMapping(), receiverModel.getXPathFunctionContext()), 1);

            if (targetNode == null) {
                throw new XFormsException("targetNode for xpath: " + xpath + " not found");
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("targetNode to replace............");
                DOMUtil.prettyPrintDOM(targetNode);
            }
            //todo:review - this can be an Eleement if ref was used on submission!!!
            if (instance instanceof Document) {
                Document toImport = (Document) instance;
                targetNode.getParentNode().replaceChild(
                        targetNode.getOwnerDocument().importNode(toImport.getDocumentElement(), true),
                        targetNode);
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("result Instance after insertion ............");
                DOMUtil.prettyPrintDOM(receiverModel.getDefaultInstance().getInstanceDocument());
            }
        } else {
            throw new XFormsException("Submission method '" + submissionMethod + "' not supported");
        }
        receiverModel.rebuild();
        receiverModel.recalculate();
        receiverModel.revalidate();
        receiverModel.refresh();

        return new HashMap(1);
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:bridge.toolkit.commands.S1000DConverter.java

/** 
 * The unit of processing work to be performed for the S1000DConverter module.
 * @see org.apache.commons.chain.Command#execute(org.apache.commons.chain.Context)
 *///from w w w  .  j  a  va 2  s .  c  om
public boolean execute(Context ctx) {
    System.out.println("Executing S1000D Converter");
    if ((ctx.get(Keys.SCPM_FILE) != null) && (ctx.get(Keys.RESOURCE_PACKAGE) != null)) {
        /*
         * check the output directory in the context if it does not exist make it
         */
        if (!(ctx.containsKey(Keys.OUTPUT_DIRECTORY))) {
            ctx.put(Keys.OUTPUT_DIRECTORY, "");
        }

        resourcepack = ctx.get(Keys.RESOURCE_PACKAGE).toString();
        /*
         * if SCPM is 4.1 then Move the original file to the temp directory
         * in this file it will perform the downgrade to 4.0 version If
         * /scormContentPackage/content/scoEntry/scoEntryItem exists is a
         * 4.1 SCPM
         */
        org.w3c.dom.Document new40 = null;
        File tempSCPM = null;
        try {
            new40 = getDoc(new File(ctx.get(Keys.SCPM_FILE).toString()));
            if (processXPathSingleNode("/scormContentPackage/content/scoEntry/scoEntryItem", new40) == null) {
                System.out.println("S1000D Converter Complete");
                return CONTINUE_PROCESSING;
            }
            tempSCPM = File.createTempFile(new File(ctx.get(Keys.SCPM_FILE).toString()).getName(), ".xml");
            copy(ctx.get(Keys.SCPM_FILE).toString(), tempSCPM.toString());
            ctx.put(Keys.SCPM_FILE, tempSCPM.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            return PROCESSING_COMPLETE;
        }

        List<File> src_files = new ArrayList<File>();
        try {
            src_files = getSourceFiles((String) ctx.get(Keys.RESOURCE_PACKAGE));
        } catch (Exception npe) {
            System.out.println("The 'Resource Package' is empty.");
            return PROCESSING_COMPLETE;
        }

        /*
         * For each scoEntry adding sconEntryAddress and scoEntryStatus
         */
        try {
            // getting the modelic and issuer from status SCPM
            modelic = processXPathSingleNode(
                    "/scormContentPackage/identAndStatusSection/scormContentPackageAddress/scormContentPackageIdent/scormContentPackageCode/@modelIdentCode",
                    new40).getNodeValue();
            PackageIssuer = processXPathSingleNode(
                    "/scormContentPackage/identAndStatusSection/scormContentPackageAddress/scormContentPackageIdent/scormContentPackageCode/@scormContentPackageIssuer",
                    new40).getNodeValue();
            PackageNumber = processXPathSingleNode(
                    "/scormContentPackage/identAndStatusSection/scormContentPackageAddress/scormContentPackageIdent/scormContentPackageCode/@scormContentPackageNumber",
                    new40).getNodeValue();
            PackageVolume = processXPathSingleNode(
                    "/scormContentPackage/identAndStatusSection/scormContentPackageAddress/scormContentPackageIdent/scormContentPackageCode/@scormContentPackageVolume",
                    new40).getNodeValue();

            securityClassification = processXPathSingleNode(
                    "/scormContentPackage/identAndStatusSection/scormContentPackageStatus/security/@securityClassification",
                    new40).getNodeValue();
            ;
            qualityAssurance = processXPathSingleNode(
                    "/scormContentPackage/identAndStatusSection/scormContentPackageStatus/qualityAssurance",
                    new40);

            // getting the content node
            Node content = processXPathSingleNode("//content", new40);

            if (content != null) {
                // delete content..
                Node contentclone = content.cloneNode(true);
                removeNode(content);
                // add the content Node..
                org.w3c.dom.Element newcontent = new40.createElement("content");
                // navigate through the tree seeking for scoEntry
                for (int i = 0; i < contentclone.getChildNodes().getLength(); i++) {
                    Node node = contentclone.getChildNodes().item(i);
                    if (node.getNodeName().equals("scoEntry")) {
                        Node scoE = node.cloneNode(true);
                        walkingthrough(scoE, new40);
                        newcontent.appendChild(scoE);
                    }
                }

                // add the content modified
                Node pm = processXPathSingleNode("//scormContentPackage", new40);
                pm.appendChild(newcontent);

                // re write on temp file the new XML..
                writeOnDisk(tempSCPM, getXMLString(new40));
            }

        } catch (Exception npe) {
            Writer writer = new StringWriter();
            PrintWriter printWriter = new PrintWriter(writer);
            npe.printStackTrace(printWriter);
            writer.toString();
            System.out.println("Error " + npe + " " + writer.toString());
            return PROCESSING_COMPLETE;
        }

        System.out.println("Conversion of SCPM 4.1 to SCPM 4.0 was successful");
    } else {
        System.out.println("One of the required Context entries for the " + this.getClass().getSimpleName()
                + " command to be executed was null");
        return PROCESSING_COMPLETE;
    }
    return CONTINUE_PROCESSING;
}

From source file:com.twinsoft.convertigo.beans.core.Sequence.java

private static Node cloneNodeWithUserData(Node node, boolean recurse) {
    if (node != null) {
        Object node_output = node.getUserData(Step.NODE_USERDATA_OUTPUT);

        Node clonedNode = node.cloneNode(false);
        clonedNode.setUserData(Step.NODE_USERDATA_OUTPUT, node_output, null);

        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // attributes
            NamedNodeMap attributeMap = clonedNode.getAttributes();
            for (int i = 0; i < attributeMap.getLength(); i++) {
                Node clonedAttribute = attributeMap.item(i);
                String attr_name = clonedAttribute.getNodeName();
                Object attr_output = ((Element) node).getAttributeNode(attr_name)
                        .getUserData(Step.NODE_USERDATA_OUTPUT);
                clonedAttribute.setUserData(Step.NODE_USERDATA_OUTPUT, attr_output, null);
            }/*from  ww w . ja v a 2  s.co m*/

            // recurse on element child nodes only
            if (recurse && node.hasChildNodes()) {
                NodeList list = node.getChildNodes();
                for (int i = 0; i < list.getLength(); i++) {
                    Node clonedChild = cloneNodeWithUserData(list.item(i), recurse);
                    if (clonedChild != null) {
                        clonedNode.appendChild(clonedChild);
                    }
                }
            }
        }

        return clonedNode;
    }
    return 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);/*  ww w  .  j a  va  2  s. c  om*/
    //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:com.netspective.sparx.util.xml.XmlSource.java

public void inheritElement(Element srcElement, Element destElem, Set excludeElems, String inheritedFromNode) {
    NamedNodeMap inhAttrs = srcElement.getAttributes();
    for (int i = 0; i < inhAttrs.getLength(); i++) {
        Node attrNode = inhAttrs.item(i);
        final String nodeName = attrNode.getNodeName();
        if (!excludeElems.contains(nodeName) && destElem.getAttribute(nodeName).equals(""))
            destElem.setAttribute(nodeName, attrNode.getNodeValue());
    }/*from   w w w  .java 2  s. co  m*/

    DocumentFragment inheritFragment = xmlDoc.createDocumentFragment();
    NodeList inhChildren = srcElement.getChildNodes();
    for (int i = inhChildren.getLength() - 1; i >= 0; i--) {
        Node childNode = inhChildren.item(i);

        // only add if there isn't an attribute overriding this element
        final String nodeName = childNode.getNodeName();
        if (destElem.getAttribute(nodeName).length() == 0 && (!excludeElems.contains(nodeName))) {
            Node cloned = childNode.cloneNode(true);
            if (inheritedFromNode != null && cloned.getNodeType() == Node.ELEMENT_NODE)
                ((Element) cloned).setAttribute("_inherited-from", inheritedFromNode);
            inheritFragment.insertBefore(cloned, inheritFragment.getFirstChild());
        }
    }

    destElem.insertBefore(inheritFragment, destElem.getFirstChild());
}

From source file:com.icesoft.faces.component.inputfile.InputFile.java

protected void renderIFrame(Writer writer, BridgeFacesContext context) throws IOException {
    writer.write("<html style=\"overflow:hidden;\">");
    ArrayList outputStyleComponents = findOutputStyleComponents(context.getViewRoot());
    if (outputStyleComponents != null) {
        writer.write("<head>");
        for (int i = 0; i < outputStyleComponents.size(); i++) {
            OutputStyle outputStyle = (OutputStyle) outputStyleComponents.get(i);
            String href = outputStyle.getHref();
            if ((href != null) && (href.length() > 0)) {
                href = CoreUtils.resolveResourceURL(context, href);
                writer.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + href + "\">");
            }//from   www.  j  a va2 s.  c o m
        }
        writer.write("</head>");
    }
    String srv = getUploadServletPath(context);
    writer.write("<body style=\"background-color:transparent; overflow:hidden\"><form method=\"post\" action=\""
            + srv + "\" enctype=\"multipart/form-data\" id=\"fileUploadForm\">");
    writer.write("<input type=\"hidden\" name=\"ice.component\" value=\"");
    writer.write(this.getClientId(context));
    writer.write("\"/>");
    writer.write("<input type=\"hidden\" name=\"ice.view\"");
    writer.write(" value=\"" + context.getViewNumber() + "\"/>");
    if (isAutoUpload()) {
        writer.write("<input type=\"file\" name=\"upload\" onchange=\"form.submit()\"");
    } else {
        writer.write("<input type=\"file\" name=\"upload\"");
    }
    if (isDisabled())
        writer.write(" disabled=\"disabled\"");

    writer.write(" size=\"" + getInputTextSize() + "\"");
    String inputTextClass = getInputTextClass();
    if (inputTextClass != null)
        writer.write(" class=\"" + inputTextClass + "\"");
    String title = getTitle();
    if (title != null)
        writer.write(" title=\"" + title + "\"");
    writer.write("/>");
    if (!isAutoUpload()) {
        writer.write("<input type=\"submit\" value=\"" + getLabel() + "\"");
        String buttonClass = getButtonClass();
        if (buttonClass != null)
            writer.write(" class=\"" + buttonClass + "\"");
        if (isDisabled())
            writer.write(" disabled=\"disabled\"");
        writer.write("/>");
    }

    // Retrieve the Node created by that state saving operation and
    // add it to the form root (otherwise it winds up outside the Form)
    ResponseWriter responseWriter = context.getResponseWriter();
    Node node = ((DOMResponseWriter) responseWriter).getSavedNode(); // this will be the containing <div>
    Node copy;
    // #
    if (node != null) {

        // Prepend the div's id with the id of the form for uniqueness. This
        // has to match that above.
        copy = node.cloneNode(true);
        ((Element) copy).setAttribute("id",
                "fileUploadForm" + NamingContainer.SEPARATOR_CHAR + ((Element) copy).getAttribute("id"));

        String divAsString = DOMUtils.nodeToString(copy);
        if (log.isDebugEnabled()) {
            log.debug("State saving view contents: " + divAsString);
        }
        writer.write(divAsString);
    }

    writer.write("</form>");
    writer.write("</body></html>");
}

From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificator.java

/**
 * <p>/* w ww.  ja  va2 s . c  om*/
 * Implementation of MathML unification. In the given W3C DOM represented
 * XML document find all maths nodes (see
 * {@link DocumentParser#findMathMLNodes(org.w3c.dom.Document)}) and
 * remember links to operator elements and other elements in
 * {@link #nodesByDepth} data structure. Then substitute them gradualy for
 * series of formulae with leaf elements substituted for a special
 * unification representing symbol {@code &#x25CD;} (for Presentation
 * MathML, see {@link Constants#PMATHML_UNIFICATOR}) or {@code &#x25D0;}
 * (for Content MathML, see {@link Constants#CMATHML_UNIFICATOR}).
 * </p>
 * <p>
 * Resulting series of the original and unified MathML nodes is itself
 * encapsulated in a new element &lt;unified-math&gt; (see
 * {@link Constants#UNIFIED_MATHML_ROOT_ELEM}) in XML namespace
 * <code>http://mir.fi.muni.cz/mathml-unification/</code> (see
 * {@link Constants#UNIFIED_MATHML_NS}) and put to the place of the original
 * math element {@link Node} in the XML DOM representation the node is
 * attached to.
 * </p>
 *
 * @param mathNode W3C DOM XML document representation attached MathML node
 * to work on.
 * @param workInPlace If <code>true</code>, given <code>mathNode</code> will
 * be modified in place; if <code>false</code>, <code>mathNode</code> will
 * not be modified and series of modified nodes will be returned.
 * @param operatorUnification If <code>true</code> unify also operator
 * nodes, otherwise keep operator nodes intact.
 * @return <code>null</code> if <code>workInPlace</code> is
 * <code>false</code>; otherwise collection of unified versions of the
 * <code>mathNode</code> with key of the {@link HashMap} describing order
 * (level of unification) of elements in the collection.
 */
private HashMap<Integer, Node> unifyMathMLNodeImpl(Node mathNode, boolean operatorUnification,
        boolean workInPlace) {

    if (mathNode.getOwnerDocument() == null) {
        String msg = "The given node is not attached to any document.";
        if (mathNode.getNodeType() == Node.DOCUMENT_NODE) {
            msg = "The given node is document itself. Call with mathNode.getDocumentElement() instead.";
        }
        throw new IllegalArgumentException(msg);
    }

    nodesByDepth = new HashMap<>();

    Node unifiedMathNode = null;
    HashMap<Integer, Node> unifiedNodesList = null;
    Document unifiedMathDoc = null;

    if (workInPlace) {
        // New element encapsulating the series of unified formulae.
        unifiedMathNode = mathNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS,
                UNIFIED_MATHML_ROOT_ELEM);
        mathNode.getParentNode().replaceChild(unifiedMathNode, mathNode);
        unifiedMathNode.appendChild(mathNode.cloneNode(true));
    } else {
        unifiedNodesList = new HashMap<>();
        // Create a new separate DOM to work over with imporeted clone of the node given by user
        unifiedMathDoc = DOMBuilder.createNewDocWithNodeClone(mathNode, true);
        mathNode = unifiedMathDoc.getDocumentElement();
    }

    // Parse XML subtree starting at mathNode and remember elements by their depth.
    rememberLevelsOfNodes(mathNode, operatorUnification);

    // Build series of formulae of level by level unified MathML.
    NodeLevel<Integer, Integer> level = new NodeLevel<>(getMaxMajorNodesLevel(), NUMOFMINORLEVELS);
    int levelAttrCounter = 0;
    Collection<Attr> maxLevelAttrs = new LinkedList<>();
    while (level.major > 0) {
        if (nodesByDepth.containsKey(level)) {
            if (unifyAtLevel(level)) {
                levelAttrCounter++;

                Node thisLevelMathNode = mathNode.cloneNode(true);
                Attr thisLevelAttr = thisLevelMathNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS,
                        UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_LEVEL_ATTR);
                Attr maxLevelAttr = thisLevelMathNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS,
                        UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_MAX_LEVEL_ATTR);
                maxLevelAttrs.add(maxLevelAttr);

                thisLevelAttr.setTextContent(String.valueOf(levelAttrCounter));

                ((Element) thisLevelMathNode).setAttributeNodeNS(thisLevelAttr);
                ((Element) thisLevelMathNode).setAttributeNodeNS(maxLevelAttr);

                if (workInPlace) {
                    unifiedMathNode.appendChild(thisLevelMathNode);
                } else {
                    // Create a new document for every node in the collection.
                    unifiedNodesList.put(levelAttrCounter,
                            DOMBuilder.cloneNodeToNewDoc(thisLevelMathNode, true));
                }
            }
        }
        level.minor--;
        if (level.minor <= 0) {
            level.major--;
            level.minor = NUMOFMINORLEVELS;
        }
    }
    for (Attr attr : maxLevelAttrs) {
        attr.setTextContent(String.valueOf((levelAttrCounter)));
    }

    if (workInPlace) {
        return null;
    } else {
        for (Node node : unifiedNodesList.values()) {
            Attr maxLevelAttr = (Attr) node.getAttributes().getNamedItemNS(UNIFIED_MATHML_NS,
                    UNIFIED_MATHML_MAX_LEVEL_ATTR);
            if (maxLevelAttr != null) {
                maxLevelAttr.setTextContent(String.valueOf((levelAttrCounter)));
            }
        }
        return unifiedNodesList;
    }

}

From source file:com.occamlab.te.parsers.ImageParser.java

private static void processBufferedImage(BufferedImage buffimage, String formatName, NodeList nodes)
        throws Exception {
    HashMap<Object, Object> bandMap = new HashMap<Object, Object>();

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("subimage")) {
                Element e = (Element) node;
                int x = Integer.parseInt(e.getAttribute("x"));
                int y = Integer.parseInt(e.getAttribute("y"));
                int w = Integer.parseInt(e.getAttribute("width"));
                int h = Integer.parseInt(e.getAttribute("height"));
                processBufferedImage(buffimage.getSubimage(x, y, w, h), formatName, e.getChildNodes());
            } else if (node.getLocalName().equals("checksum")) {
                CRC32 checksum = new CRC32();
                Raster raster = buffimage.getRaster();
                DataBufferByte buffer;
                if (node.getParentNode().getLocalName().equals("subimage")) {
                    WritableRaster outRaster = raster.createCompatibleWritableRaster();
                    buffimage.copyData(outRaster);
                    buffer = (DataBufferByte) outRaster.getDataBuffer();
                } else {
                    buffer = (DataBufferByte) raster.getDataBuffer();
                }/*  ww  w  . j  av  a2  s .c o m*/
                int numbanks = buffer.getNumBanks();
                for (int j = 0; j < numbanks; j++) {
                    checksum.update(buffer.getData(j));
                }
                Document doc = node.getOwnerDocument();
                node.appendChild(doc.createTextNode(Long.toString(checksum.getValue())));
            } else if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                if (sample.equals("all")) {
                    bandMap.put(band, null);
                } else {
                    HashMap<Object, Object> sampleMap = (HashMap<Object, Object>) bandMap.get(band);
                    if (sampleMap == null) {
                        if (!bandMap.containsKey(band)) {
                            sampleMap = new HashMap<Object, Object>();
                            bandMap.put(band, sampleMap);
                        }
                    }
                    sampleMap.put(Integer.decode(sample), new Integer(0));
                }
            } else if (node.getLocalName().equals("transparentNodata")) { // 2011-08-24
                                                                          // PwD
                String transparentNodata = checkTransparentNodata(buffimage, node);
                node.setTextContent(transparentNodata);
            }
        }
    }

    Iterator bandIt = bandMap.keySet().iterator();
    while (bandIt.hasNext()) {
        String band_str = (String) bandIt.next();
        int band_indexes[];
        if (buffimage.getType() == BufferedImage.TYPE_BYTE_BINARY
                || buffimage.getType() == BufferedImage.TYPE_BYTE_GRAY) {
            band_indexes = new int[1];
            band_indexes[0] = 0;
        } else {
            band_indexes = new int[band_str.length()];
            for (int i = 0; i < band_str.length(); i++) {
                if (band_str.charAt(i) == 'A')
                    band_indexes[i] = 3;
                if (band_str.charAt(i) == 'B')
                    band_indexes[i] = 2;
                if (band_str.charAt(i) == 'G')
                    band_indexes[i] = 1;
                if (band_str.charAt(i) == 'R')
                    band_indexes[i] = 0;
            }
        }

        Raster raster = buffimage.getRaster();
        java.util.HashMap sampleMap = (java.util.HashMap) bandMap.get(band_str);
        boolean addall = (sampleMap == null);
        if (sampleMap == null) {
            sampleMap = new java.util.HashMap();
            bandMap.put(band_str, sampleMap);
        }

        int minx = raster.getMinX();
        int maxx = minx + raster.getWidth();
        int miny = raster.getMinY();
        int maxy = miny + raster.getHeight();
        int bands[][] = new int[band_indexes.length][raster.getWidth()];

        for (int y = miny; y < maxy; y++) {
            for (int i = 0; i < band_indexes.length; i++) {
                raster.getSamples(minx, y, maxx, 1, band_indexes[i], bands[i]);
            }
            for (int x = minx; x < maxx; x++) {
                int sample = 0;
                for (int i = 0; i < band_indexes.length; i++) {
                    sample |= bands[i][x] << ((band_indexes.length - i - 1) * 8);
                }

                Integer sampleObj = new Integer(sample);

                boolean add = addall;
                if (!addall) {
                    add = sampleMap.containsKey(sampleObj);
                }
                if (add) {
                    Integer count = (Integer) sampleMap.get(sampleObj);
                    if (count == null) {
                        count = new Integer(0);
                    }
                    count = new Integer(count.intValue() + 1);
                    sampleMap.put(sampleObj, count);
                }
            }
        }
    }

    Node node = nodes.item(0);
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                HashMap sampleMap = (HashMap) bandMap.get(band);
                Document doc = node.getOwnerDocument();
                if (sample.equals("all")) {
                    Node parent = node.getParentNode();
                    Node prevSibling = node.getPreviousSibling();
                    Iterator sampleIt = sampleMap.keySet().iterator();
                    Element countnode = null;
                    int digits;
                    String prefix;
                    switch (buffimage.getType()) {
                    case BufferedImage.TYPE_BYTE_BINARY:
                        digits = 1;
                        prefix = "";
                        break;
                    case BufferedImage.TYPE_BYTE_GRAY:
                        digits = 2;
                        prefix = "0x";
                        break;
                    default:
                        prefix = "0x";
                        digits = band.length() * 2;
                    }
                    while (sampleIt.hasNext()) {
                        countnode = doc.createElementNS(node.getNamespaceURI(), "count");
                        Integer sampleInt = (Integer) sampleIt.next();
                        Integer count = (Integer) sampleMap.get(sampleInt);
                        if (band.length() > 0) {
                            countnode.setAttribute("bands", band);
                        }
                        countnode.setAttribute("sample", prefix + HexString(sampleInt.intValue(), digits));
                        Node textnode = doc.createTextNode(count.toString());
                        countnode.appendChild(textnode);
                        parent.insertBefore(countnode, node);
                        if (sampleIt.hasNext()) {
                            if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) {
                                parent.insertBefore(prevSibling.cloneNode(false), node);
                            }
                        }
                    }
                    parent.removeChild(node);
                    node = countnode;
                } else {
                    Integer count = (Integer) sampleMap.get(Integer.decode(sample));
                    if (count == null)
                        count = new Integer(0);
                    Node textnode = doc.createTextNode(count.toString());
                    node.appendChild(textnode);
                }
            }
        }
        node = node.getNextSibling();
    }
}

From source file:com.bstek.dorado.idesupport.robot.EntityDataTypeReflectionRobot.java

public Node execute(Node node, Properties properties) throws Exception {
    ConfigureStore configureStore = Configure.getStore();
    configureStore.set("core.contextConfigLocation", CONFIG_LOCATIONS);
    CommonContext.init();/*w  w  w  . j av  a2  s . co m*/
    try {
        Context context = Context.getCurrent();

        XmlParserHelper xmlParserHelper = (XmlParserHelper) context.getServiceBean("xmlParserHelper");
        XmlParser dataTypeParser = xmlParserHelper.getXmlParser(EntityDataType.class);

        DataConfigManager dataConfigManager = (DataConfigManager) context.getServiceBean("dataConfigManager");
        dataConfigManager.initialize();

        DataParseContext parseContext = new DataParseContext();
        parseContext.setDataTypeDefinitionManager(
                (DataTypeDefinitionManager) context.getServiceBean("dataTypeDefinitionManager"));
        parseContext.setDataProviderDefinitionManager(
                (DataProviderDefinitionManager) context.getServiceBean("dataProviderDefinitionManager"));
        parseContext.setDataResolverDefinitionManager(
                (DataResolverDefinitionManager) context.getServiceBean("dataResolverDefinitionManager"));

        DataTypeDefinition dataTypeDefinition = (DataTypeDefinition) dataTypeParser.parse(node, parseContext);

        Class<?> matchType = dataTypeDefinition.getMatchType();
        if (matchType != null) {
            if (matchType == null || matchType.isPrimitive() || matchType.isArray()) {
                throw new IllegalArgumentException("[matchType] undefined or not a valid class.");
            }
            node = node.cloneNode(true);
            reflectAndComplete((Element) node, matchType);
        }
    } finally {
        CommonContext.dispose();
    }
    return node;
}

From source file:com.ephesoft.gxt.systemconfig.server.SystemConfigServiceImpl.java

private void addPathToApplicationContext(String pluginApplicationContextPath) throws UIException {
    StringBuffer applicationContextFilePathBuffer = new StringBuffer(
            System.getenv(SystemConfigSharedConstants.DCMA_HOME));
    applicationContextFilePathBuffer.append(File.separator);
    applicationContextFilePathBuffer.append(SystemConfigSharedConstants.APPLICATION_CONTEXT_PATH_XML);
    String applicationContextFilePath = applicationContextFilePathBuffer.toString();
    File applicationContextFile = new File(applicationContextFilePath);
    LOGGER.info("Making entry for " + pluginApplicationContextPath + " in the application context file at: "
            + applicationContextFilePath);
    try {//from w  ww.j a v  a 2  s  . c om
        Document xmlDocument = XMLUtil.createDocumentFrom(applicationContextFile);

        NodeList beanTags = xmlDocument.getElementsByTagName(SystemConfigSharedConstants.BEANS_TAG);
        if (beanTags != null) {
            String searchTag = SystemConfigSharedConstants.BEANS_TAG;
            // Get the 1st bean node from
            Node beanNode = getFirstNodeOfType(beanTags, searchTag);

            Node importNodesClone = null;

            NodeList beanChildNodes = beanNode.getChildNodes();
            searchTag = SystemConfigSharedConstants.IMPORT_TAG;
            importNodesClone = getFirstNodeOfType(beanChildNodes, searchTag);
            Node cloneNode = importNodesClone.cloneNode(true);
            cloneNode.getAttributes().getNamedItem(SystemConfigSharedConstants.RESOURCE).setTextContent(
                    SystemConfigSharedConstants.CLASSPATH_META_INF + pluginApplicationContextPath);
            beanNode.insertBefore(cloneNode, importNodesClone);

            Source source = new DOMSource(xmlDocument);

            File batchXmlFile = new File(applicationContextFilePath);

            Result result = new StreamResult(batchXmlFile);

            Transformer xformer = null;
            try {
                xformer = TransformerFactory.newInstance().newTransformer();
                xformer.setOutputProperty(OutputKeys.INDENT, SystemConfigSharedConstants.YES);
                xformer.setOutputProperty(SystemConfigSharedConstants.XML_INDENT_AMOUNT, String.valueOf(2));

            } catch (TransformerConfigurationException e) {
                String errorMsg = SystemConfigSharedConstants.APPLICATION_CONTEXT_ENTRY_ERROR_MESSAGE;
                LOGGER.error(errorMsg + e.getMessage(), e);
                throw new UIException(errorMsg);
            } catch (TransformerFactoryConfigurationError e) {
                String errorMsg = SystemConfigSharedConstants.APPLICATION_CONTEXT_ENTRY_ERROR_MESSAGE;
                LOGGER.error(errorMsg + e.getMessage(), e);
                throw new UIException(errorMsg);
            }
            try {
                xformer.transform(source, result);
            } catch (TransformerException e) {
                String errorMsg = SystemConfigSharedConstants.APPLICATION_CONTEXT_ENTRY_ERROR_MESSAGE;
                LOGGER.error(errorMsg + e.getMessage(), e);
                throw new UIException(errorMsg);
            }
            LOGGER.info("Application Context Entry made successfully.");
        }
    } catch (Exception e) {
        String errorMsg = SystemConfigSharedConstants.APPLICATION_CONTEXT_ENTRY_ERROR_MESSAGE;
        LOGGER.error(errorMsg + e.getMessage());
        throw new UIException(errorMsg);
    }
}