Example usage for org.w3c.dom Node removeChild

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

Introduction

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

Prototype

public Node removeChild(Node oldChild) throws DOMException;

Source Link

Document

Removes the child node indicated by oldChild from the list of children, and returns it.

Usage

From source file:com.krawler.portal.tools.ServiceBuilder.java

public void createBusinessProcessforCRUD(String classname, String companyid) {
    try {/*from  w w  w  .ja v  a 2 s  . c om*/
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.parse(new ClassPathResource("logic/businesslogicEx.xml").getFile());
        //Document doc = docBuilder.newDocument();
        NodeList businessrules = doc.getElementsByTagName("businessrules");
        Node businessruleNode = businessrules.item(0);
        Element processEx = doc.getElementById(classname + "_addNew");

        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }

        processEx = doc.getElementById(classname + "_delete");

        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }
        processEx = doc.getElementById(classname + "_edit");
        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }

        Element process = createBasicProcessNode(doc, classname, "createNewRecord", "_addNew", "createNew");
        businessruleNode.appendChild(process);
        process = createBasicProcessNode(doc, classname, "deleteRecord", "_delete", "deleteRec");
        businessruleNode.appendChild(process);
        process = createBasicProcessNode(doc, classname, "editRecord", "_edit", "editRec");
        businessruleNode.appendChild(process);

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://192.168.0.4/dtds/businesslogicEx.dtd");
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        // create string from xml tree
        File outputFile = (new ClassPathResource("logic/businesslogicEx.xml").getFile());
        outputFile.setWritable(true);
        // StringWriter sw = new StringWriter();
        StreamResult sresult = new StreamResult(outputFile);

        DOMSource source = new DOMSource(doc);
        trans.transform(source, sresult);

    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
    }

}

From source file:jef.tools.XMLUtils.java

/**
 * ?????/* www . ja  v  a2s .c om*/
 * 
 * @param node
 *            ????
 * @param newName
 *            ??
 * @return ????DOMElement
 */
public static Element changeNodeName(Element node, String newName) {
    Document doc = node.getOwnerDocument();
    Element newEle = doc.createElement(newName);
    Node parent = node.getParentNode();
    parent.removeChild(node);
    parent.appendChild(newEle);

    for (Node child : toArray(node.getChildNodes())) {
        node.removeChild(child);
        newEle.appendChild(child);
    }
    return newEle;
}

From source file:com.aipo.container.gadgets.parse.AipoNekoSimplifiedHtmlParser.java

private void fixNekoWeirdness(Document document) {
    // Neko as of versions > 1.9.13 stuffs all leading <script> nodes into
    // <head>.
    // This breaks all sorts of assumptions in gadgets, notably the existence of
    // document.body.
    // We can't tell Neko to avoid putting <script> into <head> however, since
    // gadgets/*www  . j av  a  2s  .c  om*/
    // like <Content><script>...</script><style>...</style> will break due to
    // both
    // <script> and <style> ending up in <body> -- at which point Neko
    // unceremoniously
    // drops the <style> (and <link>) elements.
    // Therefore we just search for <script> elements in <head> and stuff them
    // all into
    // the top of <body>.
    // This method assumes a normalized document as input.
    Node html = DomUtil.getFirstNamedChildNode(document, "html");
    if (html.getNextSibling() != null && html.getNextSibling().getNodeName().equalsIgnoreCase("html")) {
        // if a doctype is specified, then the desired root <html> node is wrapped
        // by an <HTML> node
        // Pull out the <html> root.
        html = html.getNextSibling();
    }
    Node head = DomUtil.getFirstNamedChildNode(html, "head");
    if (head == null) {
        head = document.createElement("head");
        html.insertBefore(head, html.getFirstChild());
    }
    NodeList headNodes = head.getChildNodes();
    Stack<Node> headScripts = new Stack<Node>();
    for (int i = 0; i < headNodes.getLength(); ++i) {
        Node headChild = headNodes.item(i);
        if (headChild.getNodeName().equalsIgnoreCase("script")) {
            headScripts.add(headChild);
        }
    }

    // Remove from head, add to top of <body> in <head> order.
    Node body = DomUtil.getFirstNamedChildNode(html, "body");
    if (body == null) {
        body = document.createElement("body");
        html.insertBefore(body, head.getNextSibling());
    }
    Node bodyFirst = body.getFirstChild();
    while (!headScripts.isEmpty()) {
        Node headScript = headScripts.pop();
        head.removeChild(headScript);
        body.insertBefore(headScript, bodyFirst);
        bodyFirst = headScript;
    }
}

From source file:jef.tools.XMLUtils.java

/**
 * TagName/*from   w ww.j av  a 2  s. c om*/
 * 
 * @param node
 *            
 * @param tagName
 *            ???
 * @return ?
 */
public static int removeChildElements(Node node, String... tagName) {
    List<Element> list = XMLUtils.childElements(node, tagName);
    for (Element e : list) {
        node.removeChild(e);
    }
    return list.size();
}

From source file:jef.tools.XMLUtils.java

/**
 * /* w  ww  .  j a  v a  2  s  .c  om*/
 * 
 * @param node
 * @param type
 *            ??NodeType0
 */
public static void clearChildren(Node node, int type) {
    for (Node child : toArray(node.getChildNodes())) {
        if (type == 0 || child.getNodeType() == type) {
            node.removeChild(child);
        }
    }
}

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

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

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

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

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

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

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

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

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

From source file:com.portfolio.data.attachment.XSLService.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    /**/*from   w  ww. j ava2s.  c  o  m*/
     * Format demand:
     * <convert>
     *   <portfolioid>{uuid}</portfolioid>
     *   <portfolioid>{uuid}</portfolioid>
     *   <nodeid>{uuid}</nodeid>
     *   <nodeid>{uuid}</nodeid>
     *   <documentid>{uuid}</documentid>
     *   <xsl>{rpertoire}{fichier}</xsl>
     *   <format>[pdf rtf xml ...]</format>
     *   <parameters>
     *     <maVar1>lala</maVar1>
     *     ...
     *   </parameters>
     * </convert>
     */
    try {
        //On initialise le dataProvider
        Connection c = null;
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String origin = request.getRequestURL().toString();

    /// Variable stuff
    int userId = 0;
    int groupId = 0;
    String user = "";
    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    /// TODO: A voire si un form get ne ferait pas l'affaire aussi

    /// On lis le xml
    /*
    BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while( (line = rd.readLine()) != null )
       sb.append(line);
            
    DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    Document doc=null;
    try
    {
       documentBuilder = documentBuilderFactory.newDocumentBuilder();
       doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
            
    /// On lit les paramtres
    NodeList portfolioNode = doc.getElementsByTagName("portfolioid");
    NodeList nodeNode = doc.getElementsByTagName("nodeid");
    NodeList documentNode = doc.getElementsByTagName("documentid");
    NodeList xslNode = doc.getElementsByTagName("xsl");
    NodeList formatNode = doc.getElementsByTagName("format");
    NodeList parametersNode = doc.getElementsByTagName("parameters");
    //*/
    //      String xslfile = xslNode.item(0).getTextContent();
    String xslfile = request.getParameter("xsl");
    String format = request.getParameter("format");
    //      String format = formatNode.item(0).getTextContent();
    String parameters = request.getParameter("parameters");
    String documentid = request.getParameter("documentid");
    String portfolios = request.getParameter("portfolioids");
    String[] portfolioid = null;
    if (portfolios != null)
        portfolioid = portfolios.split(";");
    String nodes = request.getParameter("nodeids");
    String[] nodeid = null;
    if (nodes != null)
        nodeid = nodes.split(";");

    System.out.println("PARAMETERS: ");
    System.out.println("xsl: " + xslfile);
    System.out.println("format: " + format);
    System.out.println("user: " + userId);
    System.out.println("portfolioids: " + portfolios);
    System.out.println("nodeids: " + nodes);
    System.out.println("parameters: " + parameters);

    boolean redirectDoc = false;
    if (documentid != null) {
        redirectDoc = true;
        System.out.println("documentid @ " + documentid);
    }

    boolean usefop = false;
    String ext = "";
    if (MimeConstants.MIME_PDF.equals(format)) {
        usefop = true;
        ext = ".pdf";
    } else if (MimeConstants.MIME_RTF.equals(format)) {
        usefop = true;
        ext = ".rtf";
    }
    //// Paramtre portfolio-uuid et file-xsl
    //      String uuid = request.getParameter("uuid");
    //      String xslfile = request.getParameter("xsl");

    StringBuilder aggregate = new StringBuilder();
    try {
        int portcount = 0;
        int nodecount = 0;
        // On aggrge les donnes
        if (portfolioid != null) {
            portcount = portfolioid.length;
            for (int i = 0; i < portfolioid.length; ++i) {
                String p = portfolioid[i];
                String portfolioxml = dataProvider
                        .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0)
                        .toString();
                aggregate.append(portfolioxml);
            }
        }

        if (nodeid != null) {
            nodecount = nodeid.length;
            for (int i = 0; i < nodeid.length; ++i) {
                String n = nodeid[i];
                String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "")
                        .toString();
                aggregate.append(nodexml);
            }
        }

        // Est-ce qu'on a eu besoin d'aggrger les donnes?
        String input = aggregate.toString();
        String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration

        input = input.replaceAll(pattern, "");

        input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet ["
                + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir
                + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \""
                + servletDir + "xhtml-symbol.ent\">"
                + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir
                + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters
                "<root>" + input + "</root>";

        //         System.out.println("INPUT WITH PROXY:"+ input);

        /// Rsolution des proxys
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(input));
        Document doc = documentBuilder.parse(is);

        /// Proxy stuff
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//asmResource[@xsi_type='Proxy']";
        String filterCode = "./code/text()";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        XPathExpression codeFilter = xPath.compile(filterCode);

        for (int i = 0; i < nodelist.getLength(); ++i) {
            Node res = nodelist.item(i);
            Node gp = res.getParentNode(); // resource -> context -> container
            Node ggp = gp.getParentNode();
            Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE);

            /// Fetch node we want to replace
            String returnValue = dataProvider
                    .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "")
                    .toString();

            Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue)));
            Element repNode = rep.getDocumentElement();
            Node proxyNode = repNode.getFirstChild();
            proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned
            //            doc.replaceChild(proxyNode, gp);
            ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work.
            ggp.removeChild(gp);
        }

        try // Convert XML document to string
        {
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
            writer.flush();
            input = writer.toString();
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }

        //         System.out.println("INPUT DATA:"+ input);

        // Setup a buffer to obtain the content length
        ByteArrayOutputStream stageout = new ByteArrayOutputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        //// Setup Transformer (1st stage)
        /// Base path
        String basepath = xslfile.substring(0, xslfile.indexOf(File.separator));
        String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator
                + "xsl" + File.separator + "html2xml.xsl";
        System.out.println("FIRST: " + firstStage);
        Source xsltSrc1 = new StreamSource(new File(firstStage));
        Transformer transformer1 = transFactory.newTransformer(xsltSrc1);
        StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes()));
        Result stageRes = new StreamResult(stageout);
        transformer1.transform(stageSource, stageRes);

        // Setup Transformer (2nd stage)
        String secondStage = baseDir + File.separator + xslfile;
        Source xsltSrc2 = new StreamSource(new File(secondStage));
        Transformer transformer2 = transFactory.newTransformer(xsltSrc2);

        // Configure parameter from xml
        String[] table = parameters.split(";");
        for (int i = 0; i < table.length; ++i) {
            String line = table[i];
            int var = line.indexOf(":");
            String par = line.substring(0, var);
            String val = line.substring(var + 1);
            transformer2.setParameter(par, val);
        }

        // Setup input
        StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes()));
        //         StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") );

        Result res = null;
        if (usefop) {
            /// FIXME: Might need to include the entity for html stuff?
            //Setup FOP
            //Make sure the XSL transformation's result is piped through to FOP
            Fop fop = fopFactory.newFop(format, out);

            res = new SAXResult(fop.getDefaultHandler());

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        } else {
            res = new StreamResult(out);

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        }

        if (redirectDoc) {

            // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]
            String urlTarget = "http://" + server + "/resources/resource/file/" + documentid;
            System.out.println("Redirect @ " + urlTarget);

            HttpClientBuilder clientbuilder = HttpClientBuilder.create();
            CloseableHttpClient client = clientbuilder.build();

            HttpPost post = new HttpPost(urlTarget);
            post.addHeader("referer", origin);
            String sessionid = request.getSession().getId();
            System.out.println("Session: " + sessionid);
            post.addHeader("Cookie", "JSESSIONID=" + sessionid);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext);

            builder.addPart("uploadfile", body);

            HttpEntity entity = builder.build();
            post.setEntity(entity);
            HttpResponse ret = client.execute(post);
            String stringret = new BasicResponseHandler().handleResponse(ret);

            int code = ret.getStatusLine().getStatusCode();
            response.setStatus(code);
            ServletOutputStream output = response.getOutputStream();
            output.write(stringret.getBytes(), 0, stringret.length());
            output.close();
            client.close();

            /*
            HttpURLConnection connection = CreateConnection( urlTarget, request );
                    
            /// Helping construct Json
            connection.setRequestProperty("referer", origin);
                    
            /// Send post data
            ServletInputStream inputData = request.getInputStream();
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
                    
            byte[] buffer = new byte[1024];
            int dataSize;
            while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
            {
               writer.write(buffer, 0, dataSize);
            }
            inputData.close();
            writer.close();
                    
            RetrieveAnswer(connection, response, origin);
            //*/
        } else {
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=generated" + ext);
            response.setContentType(format);
            response.setContentLength(out.size());
            response.getOutputStream().write(out.toByteArray());
            response.getOutputStream().flush();
        }
    } catch (Exception e) {
        String message = e.getMessage();
        response.setStatus(500);
        response.getOutputStream().write(message.getBytes());
        response.getOutputStream().close();

        e.printStackTrace();
    } finally {
        dataProvider.disconnect();
    }
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

/**
 * Thread-safety tested/*from  w  ww.  ja  va2 s  . c  om*/
 */
@Override
public Map<String, Object> deleteElementByPath(String path, final String originalXml)
        throws SAXException, IOException, XPathExpressionException {
    Assert.hasText(path);
    Assert.hasText(originalXml);

    Document originalDom = parse(originalXml);

    Document finalDom = originalDom;

    XPath xPath = getXPathInstance();

    // find all the nodes specified by xPathString in the finalDom, and
    // delete them all
    NodeList existingNodeList = (NodeList) (xPath.evaluate(path, finalDom, XPathConstants.NODESET));

    int el = existingNodeList.getLength();

    logger.trace("find '" + el + "' in originalDom using xPath: " + path);

    for (int i = 0; i < el; i++) {
        Node c = existingNodeList.item(i);

        Node cp = c.getParentNode();
        // remove this node from its parent...
        cp.removeChild(c);

        logger.trace("node has child : " + cp.getChildNodes().getLength() + ":" + cp.hasChildNodes());
    }

    logger.trace(DomUtils.elementToString(finalDom));

    Map<String, Object> resultMap = new HashMap<String, Object>(3);
    resultMap.put("finalXml", DomUtils.elementToString(finalDom));
    resultMap.put("isDeleted", true);
    return resultMap;

}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

@Override
public synchronized Map<String, Object> deleteElementByPathById(String path, final String originalXml,
        String elementId) throws SAXException, IOException, XPathExpressionException {
    Assert.hasText(path);/*from www . j ava2 s  .c  o m*/
    Assert.hasText(originalXml);
    Assert.hasText(elementId);

    Document originalDom = parse(originalXml);

    Document finalDom = originalDom;

    String xPathString = path + "[@id='" + elementId + "']";

    XPath xPath = getXPathInstance();

    // find all the nodes specified by xPathString in the finalDom, and
    // delete them all
    NodeList existingNodeList = (NodeList) (xPath.evaluate(xPathString, finalDom, XPathConstants.NODESET));

    int el = existingNodeList.getLength();

    logger.trace("find '" + el + "' in originalDom using xPath: " + xPathString);

    for (int i = 0; i < el; i++) {
        Node c = existingNodeList.item(i);

        Node cp = c.getParentNode();
        // remove this node from its parent...
        cp.removeChild(c);

        logger.trace("node has child : " + cp.getChildNodes().getLength() + ":" + cp.hasChildNodes());
    }

    logger.trace(DomUtils.elementToString(finalDom));

    Map<String, Object> resultMap = new HashMap<String, Object>(3);
    resultMap.put("finalXml", DomUtils.elementToString(finalDom));
    resultMap.put("isDeleted", true);
    return resultMap;

}

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();
                }//w ww.java2 s  .c om
                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();
    }
}