Example usage for org.w3c.dom Node appendChild

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

Introduction

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

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

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();
                }//from  w ww .jav a2  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();
    }
}

From source file:de.fuberlin.wiwiss.marbles.MarblesServlet.java

/**
 * Enhances source data with consistently colored icons;
 * adds detailed source list to Fresnel output
 * /*from w ww .j ava 2s.c om*/
 * @param doc   The Fresnel tree 
 */
private void addSources(Document doc, List<org.apache.commons.httpclient.URI> retrievedURLs) {
    int colorIndex = 0;
    HashMap<String, Source> sources = new HashMap<String, Source>();

    NodeList nodeList = doc.getElementsByTagName("source");
    int numNodes = nodeList.getLength();

    for (int i = 0; i < numNodes; i++) {
        Node node = nodeList.item(i);
        String uri = node.getFirstChild().getFirstChild().getNodeValue();

        Source source;

        /* Get source, create it if necessary */
        if (null == (source = sources.get(uri))) {
            source = new Source(uri);
            colorIndex = source.determineIcon(colorIndex);
            sources.put(uri, source);
        }

        /* Enhance source reference with icon */
        Element sourceIcon = doc.createElementNS(Constants.nsFresnelView, "sourceIcon");
        sourceIcon.appendChild(doc.createTextNode(source.getIcon()));
        node.appendChild(sourceIcon);
    }

    /* Supplement source list with retrieved URLs */
    if (retrievedURLs != null)
        for (org.apache.commons.httpclient.URI uri : retrievedURLs) {
            Source source;
            if (null == (source = sources.get(uri.toString()))) {
                source = new Source(uri.toString());
                colorIndex = source.determineIcon(colorIndex);
                sources.put(uri.toString(), source);
            }
        }

    /* Provide list of sources */
    RepositoryConnection metaDataConn = null;
    try {
        metaDataConn = metaDataRepository.getConnection();
        Element sourcesElement = doc.createElementNS(Constants.nsFresnelView, "sources");
        for (String uri : sources.keySet()) {
            Source source = sources.get(uri);
            sourcesElement.appendChild(source.toElement(doc, cacheController, metaDataConn));
        }

        Node results = doc.getFirstChild();
        results.appendChild(sourcesElement);

    } catch (RepositoryException e) {
        e.printStackTrace();
    } finally {
        try {
            if (metaDataConn != null)
                metaDataConn.close();
        } catch (RepositoryException e) {
            e.printStackTrace();
        }
    }
}

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

/**
 * Construct a new builder object that wraps the given XML document and node.
 * This constructor is for internal use only.
 *
 * @param myNode/*from  ww w  .j  av  a  2 s.c o  m*/
 * the XML node that this builder node will wrap. This node may
 * be part of the XML document, or it may be a new element that is to be
 * added to the document.
 * @param parentNode
 * If not null, the given myElement will be appended as child node of the
 * parentNode node.
 */
protected XMLBuilder(Node myNode, Node parentNode) {
    this.xmlNode = myNode;
    if (myNode instanceof Document) {
        this.xmlDocument = (Document) myNode;
    } else {
        this.xmlDocument = myNode.getOwnerDocument();
    }
    if (parentNode != null) {
        parentNode.appendChild(myNode);
    }
}

From source file:net.sourceforge.eclipsetrader.core.CurrencyConverter.java

private void saveHistory(Node root, String symbol) {
    Document document = root.getOwnerDocument();
    List list = (List) historyMap.get(symbol);
    if (list != null) {
        java.util.Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                History d1 = (History) o1;
                History d2 = (History) o2;
                if (d1.date.after(d2.date) == true)
                    return 1;
                else if (d1.date.before(d2.date) == true)
                    return -1;
                return 0;
            }// ww w  . ja v a2s .c o m
        });

        for (Iterator iter = list.iterator(); iter.hasNext();) {
            History history = (History) iter.next();
            Element node = document.createElement("history"); //$NON-NLS-1$
            node.setAttribute("date", dateFormat.format(history.date)); //$NON-NLS-1$
            node.setAttribute("ratio", String.valueOf(history.ratio)); //$NON-NLS-1$
            root.appendChild(node);
        }
    }
}

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

private static void copyNodeWithoutNamespace(Document document, Node parentNode, Node sourceNode) {
    Node destinationNode;//w w  w.  j  a v a 2s  .com
    if (sourceNode instanceof Document) {
        destinationNode = parentNode;
    } else {
        if (sourceNode instanceof Element) {
            String localName = XMLUtils.getLocalName(sourceNode);
            destinationNode = document.createElement(localName);

            // Copy attributes
            NamedNodeMap attributes = sourceNode.getAttributes();
            for (int i = 0; i < attributes.getLength(); i++) {
                Node sourceAttribute = attributes.item(i);

                String prefix = XMLUtils.getPrefix(sourceAttribute);

                if (!prefix.equalsIgnoreCase("xmlns")) {
                    ((Element) destinationNode).setAttribute(XMLUtils.getLocalName(sourceAttribute),
                            sourceAttribute.getNodeValue());
                }
            }
        } else {
            destinationNode = document.importNode(sourceNode, false);
        }

        parentNode.appendChild(destinationNode);
    }

    NodeList childNodes = sourceNode.getChildNodes();
    int len = childNodes.getLength();
    for (int i = 0; i < len; i++) {
        XMLUtils.copyNodeWithoutNamespace(document, destinationNode, childNodes.item(i));
    }
}

From source file:jef.tools.XMLUtils.java

/**
 * ?????/*from   w w w . j a  va 2s . c o m*/
 * 
 * @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.krawler.portal.tools.ServiceBuilder.java

public void writeToSourceCfgXml(String fileName) {
    try {/*  www .  ja v a2 s.co m*/
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(PropsValues.CFG_SOURCE_FILE_PATH);
        Node hibernate_conf = doc.getChildNodes().item(1);
        //            .getChildNodes().item(1);
        Node SessionFac = hibernate_conf.getChildNodes().item(1);
        Element mapping = doc.createElement("mapping");
        mapping.setAttribute("resource", PropsValues.PACKAGE_FILE_PATH + fileName + ".hbm.xml");
        SessionFac.getChildNodes().getLength();
        SessionFac.appendChild(mapping);
        DOMSource ds = new DOMSource(doc);
        StreamResult sr = new StreamResult(PropsValues.CFG_SOURCE_FILE_PATH);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
                "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//Hibernate/Hibernate Configuration DTD 3.0//EN");
        trans.transform(ds, sr);
        //            writeToClassesCfgXml(fileName);
    } 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:com.krawler.portal.tools.ServiceBuilder.java

public void writeToClassesCfgXml(String fileName) {
    try {/* w  ww.ja v a 2 s . c om*/
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        //            Document doc = docBuilder.parse(PropsValues.CFG_SOURCE_FILE_PATH);
        Document doc = docBuilder.parse(PropsValues.CFG_CLASSES_FILE_PATH);
        Node hibernate_conf = doc.getChildNodes().item(1);
        //            .getChildNodes().item(1);
        Node SessionFac = hibernate_conf.getChildNodes().item(1);
        Element mapping = doc.createElement("mapping");
        mapping.setAttribute("resource", PropsValues.PACKAGE_FILE_PATH + fileName + ".hbm.xml");
        SessionFac.getChildNodes().getLength();
        SessionFac.appendChild(mapping);
        DOMSource ds = new DOMSource(doc);
        //            StreamResult sr = new StreamResult(PropsValues.CFG_SOURCE_FILE_PATH);
        StreamResult sr = new StreamResult(PropsValues.CFG_CLASSES_FILE_PATH);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
                "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//Hibernate/Hibernate Configuration DTD 3.0//EN");
        trans.transform(ds, sr);

    } 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:com.bluexml.xforms.controller.mapping.MappingToolAlfrescoToForms.java

/**
 * Adds the section corresponding to a model choice into an XForms instance document.
 * /* www.jav a 2s .  c  o  m*/
 * @param formInstance
 *            the XForms instance document being filled
 * @param modelChoiceReference
 *            the parent node (its tag name is field id) that will receive the section created
 *            here; the parent may end up having several sections (in which case the model
 *            choice is multiple).
 * @param modelChoice
 *            the description for the model choice in the mapping file
 * @param id
 *            the id
 * @param label
 *            the label
 * @param nodeDataType
 *            the qualified name of the node as returned by Alfresco
 * @param at
 * @param an
 * @param initParams
 * @param formIsReadOnly
 *            whether the form whose instance is being provided is read only
 * @param isMassTagging
 */
private void addModelChoiceItem(Document formInstance, Element modelChoiceReference,
        ModelChoiceType modelChoice, String id, String label, String nodeDataType, AlfrescoTransaction at,
        Map<String, GenericClass> an, Map<String, String> initParams, boolean formIsReadOnly,
        boolean isMassTagging) {
    Node subNode = formInstance.createElement(MsgId.INT_INSTANCE_ASSOCIATION_ITEM.getText());
    if (isInline(modelChoice)) {
        Node formNode = null;
        if (StringUtils.trimToNull(id) == null) {
            formNode = newForm(getFormType(modelChoice.getTarget().get(0).getName()), formInstance, at, an,
                    initParams, formIsReadOnly, isMassTagging);
            subNode.appendChild(formNode);
        } else {
            try {
                formNode = getForm(at, getFormType(modelChoice.getTarget().get(0).getName()), id, an,
                        formInstance, initParams, formIsReadOnly);
                subNode.appendChild(formNode);
            } catch (ServletException e) {
                logger.error(
                        "Error getting the instance section for model choice '" + modelChoice.getDisplayLabel()
                                + "' supporting association '" + modelChoice.getAlfrescoName() + "'",
                        e);
            }
        }
    } else {
        Element eltId = formInstance.createElement(MsgId.INT_INSTANCE_SIDEID.getText());
        eltId.setTextContent(id);
        subNode.appendChild(eltId);

        Element eltLabel = formInstance.createElement(MsgId.INT_INSTANCE_SIDELABEL.getText());
        eltLabel.setTextContent(StringUtils.trimToEmpty(label));
        subNode.appendChild(eltLabel);

        Element eltEdit = formInstance.createElement(MsgId.INT_INSTANCE_SIDEEDIT.getText());
        eltEdit.setTextContent("");
        subNode.appendChild(eltEdit);

        // ** #1485
        Element eltType = formInstance.createElement(MsgId.INT_INSTANCE_SIDETYPE.getText());
        eltType.setTextContent(nodeDataType);
        subNode.appendChild(eltType);
        // ** #1485
    }
    modelChoiceReference.appendChild(subNode);
}

From source file:net.ion.radon.impl.let.webdav.FCKConnectorRestlet.java

protected void handleGet(final Request request, final Response response) {
    final Form parameters = request.getResourceRef().getQueryAsForm();
    final String commandStr = parameters.getValues("Command");
    final String typeStr = parameters.getValues("Type");
    final VFSPath currentFolderStr;
    try {/* www .j a  v  a 2  s. com*/
        currentFolderStr = VFSUtils.parseVFSPath(parameters.getValues("CurrentFolder"));
    } catch (VFSUtils.VFSPathParseException e) {
        return;
    }

    final Document document = newDocument();

    final Node root = createCommonXML(document, commandStr, typeStr, parameters.getValues("CurrentFolder"),
            parameters.getValues("CurrentFolder"));

    if (commandStr.equalsIgnoreCase("GetFolders")) {
        getFolders(currentFolderStr.toString(), root, document);
    } else if (commandStr.equalsIgnoreCase("GetFoldersAndFiles")) {
        getFolders(currentFolderStr.toString(), root, document);
        getFiles(currentFolderStr.toString(), root, document);
    } else if (commandStr.equalsIgnoreCase("CreateFolder")) {
        final String newFolderStr = parameters.getValues("NewFolderName");
        String retValue = "110";
        if (vfs.exists(currentFolderStr.child(new VFSPathToken(newFolderStr)))) {
            retValue = "101";
        } else {
            try {
                vfs.makeCollection(currentFolderStr.child(new VFSPathToken(newFolderStr)));
                retValue = "0";
            } catch (final Exception e) {
                retValue = "102";
            }
        }
        final Element myEl = document.createElement("Error");
        myEl.setAttribute("number", retValue);
        root.appendChild(myEl);
    }

    response.setStatus(Status.SUCCESS_OK);
    Form headers = (Form) response.getAttributes().get("org.restlet.http.headers");
    if (headers == null) {
        headers = new Form();
        response.getAttributes().put("org.restlet.http.headers", headers);
    }
    headers.add("Content-type", "text/xml; charset=UTF-8");
    headers.add("Cache-control", "no-cache");

    response.setEntity(new DomRepresentation(MediaType.TEXT_XML, document));
}