Example usage for org.w3c.dom Element getNodeName

List of usage examples for org.w3c.dom Element getNodeName

Introduction

In this page you can find the example usage for org.w3c.dom Element getNodeName.

Prototype

public String getNodeName();

Source Link

Document

The name of this node, depending on its type; see the table above.

Usage

From source file:org.hippoecm.frontend.editor.layout.LayoutProvider.java

public LayoutProvider(IModel<ClassLoader> loaderModel) {
    this.classLoaderModel = loaderModel;

    layouts = new TreeMap<String, LayoutEntry>();
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//www .  j  a  va2  s . c  o m
    dbf.setValidating(false);

    final ClassLoader loader = classLoaderModel.getObject();
    if (loader == null) {
        log.error("No class-loader could be obtained from the user session, skip reading layout extensions.");
        return;
    }

    try {
        for (Enumeration<URL> iter = loader.getResources("hippoecm-layouts.xml"); iter.hasMoreElements();) {
            URL configurationURL = iter.nextElement();
            InputStream stream = configurationURL.openStream();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(stream);

            Element element = document.getDocumentElement();
            if (!"layouts".equals(element.getNodeName())) {
                throw new RuntimeException("unable to parse layout: no layout node found");
            }

            NodeList nodes = element.getElementsByTagName("layout");
            for (int i = 0; i < nodes.getLength(); i++) {
                Element padElement = (Element) nodes.item(i);

                NodeList plugins = padElement.getElementsByTagName("plugin");
                if (plugins.getLength() != 1) {
                    throw new RuntimeException(
                            "Invalid layout, 0 or more than 1 plugin child nodes found at " + configurationURL);
                }

                Element pluginElement = (Element) plugins.item(0);
                Node childNode = pluginElement.getFirstChild();
                String plugin = childNode.getNodeValue();
                addLayoutEntry(plugin, null);

                NodeList variants = padElement.getElementsByTagName("variant");
                for (int j = 0; j < variants.getLength(); j++) {
                    Element variantElement = (Element) variants.item(j);
                    Node variantNode = variantElement.getFirstChild();
                    String variant = variantNode.getNodeValue();
                    addLayoutEntry(plugin, variant);
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Error while reading layouts extension", e);
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException("Parser configuration error:", ex);
    } catch (SAXException ex) {
        throw new RuntimeException("SAX error:", ex);
    }
}

From source file:org.hisp.dhis.webwork.configuration.UrlXmlConfigurationProvider.java

private void loadConfigurationFile(String fileName, Element includeElement) {
    if (!includedFileNames.contains(fileName)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Loading xwork configuration from: " + fileName);
        }//from www. ja  v  a 2 s.c  o  m

        includedFileNames.add(fileName);

        Document doc = null;
        InputStream is = null;

        try {
            is = getInputStream(fileName);

            if (is == null) {
                throw new Exception("Could not open file " + fileName);
            }

            InputSource in = new InputSource(is);

            // FIXME: we shouldn't be doing this lookup twice
            try {
                in.setSystemId(ClassLoaderUtil.getResource(fileName, getClass()).toString());
            } catch (Exception e) {
                in.setSystemId(fileName);
            }

            Map dtdMappings = new HashMap();
            dtdMappings.put("-//OpenSymphony Group//XWork 1.1.1//EN", "xwork-1.1.1.dtd");
            dtdMappings.put("-//OpenSymphony Group//XWork 1.1//EN", "xwork-1.1.dtd");
            dtdMappings.put("-//OpenSymphony Group//XWork 1.0//EN", "xwork-1.0.dtd");

            doc = DomHelper.parse(in, dtdMappings);
        } catch (XworkException e) {
            // WTF!!??
            if (includeElement != null) {
                System.out.println(e);
                throw new ConfigurationException(e, includeElement);
            } else {
                throw new ConfigurationException(e);
            }
        } catch (Exception e) {
            final String s = "Caught exception while loading file " + fileName;
            LOG.error(s, e);
            // throw new ConfigurationException(s, e, includeElement);
            throw new ConfigurationException(s, e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOG.error("Unable to close input stream", e);
                }
            }
        }

        Element rootElement = doc.getDocumentElement();
        NodeList children = rootElement.getChildNodes();
        int childSize = children.getLength();

        for (int i = 0; i < childSize; i++) {
            Node childNode = children.item(i);

            if (childNode instanceof Element) {
                Element child = (Element) childNode;

                final String nodeName = child.getNodeName();

                if (nodeName.equals("package")) {
                    addPackage(child);
                } else if (nodeName.equals("include")) {
                    String includeFileName = child.getAttribute("file");
                    loadConfigurationFile(includeFileName, child);
                }
            }
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Loaded xwork configuration from: " + fileName);
        }
    }
}

From source file:org.htmlcleaner.XWikiDOMSerializer.java

/**
 * Perform CDATA transformations if the user has specified to use CDATA inside scripts and style elements.
 *
 * @param document the W3C Document to use for creating new DOM elements
 * @param element the W3C element to which we'll add the text content to
 * @param bufferedContent the buffered text content on which we need to perform the CDATA transformations
 * @param item the current HTML Cleaner node being processed
 *//*from ww  w. ja va2  s . c  om*/
private void flushContent(Document document, Element element, StringBuffer bufferedContent, Object item) {
    if (bufferedContent.length() > 0 && !(item instanceof ContentNode)) {
        // Flush the buffered content
        boolean specialCase = this.props.isUseCdataForScriptAndStyle() && isScriptOrStyle(element);
        String content = bufferedContent.toString();

        if (this.escapeXml && !specialCase) {
            content = Utils.escapeXml(content, this.props, true);
        } else if (specialCase) {
            content = processCDATABlocks(content);
        }

        // Generate a javascript comment in front on the CDATA block so that it works in IE and when
        // serving XHTML under a mimetype of HTML.
        if (specialCase) {
            if (SCRIPT_TAG_NAME.equalsIgnoreCase(element.getNodeName())) {
                // JS
                element.appendChild(document.createTextNode(JS_COMMENT));
                element.appendChild(document.createCDATASection(NEW_LINE + content + NEW_LINE + JS_COMMENT));
            } else {
                // CSS
                element.appendChild(document.createTextNode(CSS_COMMENT_START));
                element.appendChild(document.createCDATASection(
                        CSS_COMMENT_END + StringUtils.chomp(content) + NEW_LINE + CSS_COMMENT_START));
                element.appendChild(document.createTextNode(CSS_COMMENT_END));
            }
        } else {
            element.appendChild(document.createTextNode(content));
        }

        bufferedContent.setLength(0);
    }
}

From source file:org.htmlcleaner.XWikiDOMSerializer.java

/**
 * @param element the element to check/*from  w w w . j  av  a  2s.  co  m*/
 * @return true if the passed element is a script or style element
 */
protected boolean isScriptOrStyle(Element element) {
    String tagName = element.getNodeName();
    return SCRIPT_TAG_NAME.equalsIgnoreCase(tagName) || STYLE_TAG_NAME.equalsIgnoreCase(tagName);
}

From source file:org.infoglue.cms.applications.structuretool.actions.ViewSiteNodePageComponentsAction.java

/**
 * This method adds a component to the page. 
 *///from w  ww. jav  a 2 s . c  o  m

public String doMoveComponentToSlot() throws Exception {
    logger.info("************************************************************");
    logger.info("* MOVING COMPONENT TO ANOTHER SLOT                         *");
    logger.info("************************************************************");
    logger.info("siteNodeId:" + this.siteNodeId);
    logger.info("languageId:" + this.languageId);
    logger.info("contentId:" + this.contentId);
    logger.info("queryString:" + this.getRequest().getQueryString());
    logger.info("parentComponentId:" + this.parentComponentId);
    logger.info("componentId:" + this.componentId);
    logger.info("slotId:" + this.slotId);
    logger.info("specifyBaseTemplate:" + this.specifyBaseTemplate);

    initialize();

    logger.info("masterLanguageId:" + this.masterLanguageVO.getId());

    ContentVO componentContentVO = null;

    if (this.specifyBaseTemplate.equalsIgnoreCase("true")) {
        throw new SystemException("Not possible to move component to base slot");
    } else {
        String componentXML = getPageComponentsString(siteNodeId, this.masterLanguageVO.getId());

        Document document = XMLHelper.readDocumentFromByteArray(componentXML.getBytes("UTF-8"));

        String componentXPath = "//component[@id=" + this.componentId + "]";
        String parentComponentXPath = "//component[@id=" + this.parentComponentId + "]/components";

        logger.info("componentXPath:" + componentXPath);
        logger.info("parentComponentXPath:" + parentComponentXPath);

        Node componentNode = org.apache.xpath.XPathAPI.selectSingleNode(document.getDocumentElement(),
                componentXPath);
        logger.info("Found componentNode:" + componentNode);

        Node parentComponentComponentsNode = org.apache.xpath.XPathAPI
                .selectSingleNode(document.getDocumentElement(), parentComponentXPath);
        logger.info("Found parentComponentComponentsNode:" + parentComponentComponentsNode);

        if (componentNode != null && parentComponentComponentsNode != null) {
            Element component = (Element) componentNode;
            Element currentParentElement = (Element) componentNode.getParentNode();
            Element parentComponentComponentsElement = (Element) parentComponentComponentsNode;
            Element parentComponentElement = (Element) parentComponentComponentsNode.getParentNode();

            Integer componentContentId = new Integer(component.getAttribute("contentId"));
            Integer parentComponentContentId = new Integer(parentComponentElement.getAttribute("contentId"));
            logger.info("componentContentId:" + componentContentId);
            logger.info("parentComponentContentId:" + parentComponentContentId);
            componentContentVO = ContentController.getContentController()
                    .getContentVOWithId(componentContentId);

            PageEditorHelper peh = new PageEditorHelper();
            List<Slot> slots = peh.getSlots(parentComponentContentId, languageId, this.getInfoGluePrincipal());
            boolean allowed = true;
            Iterator<Slot> slotsIterator = slots.iterator();
            while (slotsIterator.hasNext()) {
                Slot slot = slotsIterator.next();
                logger.info(slot.getId() + "=" + slotId);
                if (slot.getId().equals(slotId)) {
                    String[] allowedComponentNames = slot.getAllowedComponentsArray();
                    String[] disallowedComponentNames = slot.getDisallowedComponentsArray();
                    if (allowedComponentNames != null && allowedComponentNames.length > 0) {
                        allowed = false;
                        for (int i = 0; i < allowedComponentNames.length; i++) {
                            if (allowedComponentNames[i].equalsIgnoreCase(componentContentVO.getName()))
                                allowed = true;
                        }
                    }
                    if (disallowedComponentNames != null && disallowedComponentNames.length > 0) {
                        for (int i = 0; i < disallowedComponentNames.length; i++) {
                            if (disallowedComponentNames[i].equalsIgnoreCase(componentContentVO.getName()))
                                allowed = false;
                        }
                    }
                }
                break;
            }

            logger.info("Should the component:" + componentContentVO + " be allowed to be put in " + slotId
                    + ":" + allowed);
            logger.info("currentParentElement:" + currentParentElement.getNodeName() + ":"
                    + currentParentElement.hashCode());
            logger.info("parentComponentComponentsElement:" + parentComponentComponentsElement.getNodeName()
                    + ":" + parentComponentComponentsElement.hashCode());

            logger.info("slotPositionComponentId:" + slotPositionComponentId);
            if ((component.getParentNode() == parentComponentComponentsElement
                    && slotId.equalsIgnoreCase(component.getAttribute("name")))) {
                logger.info("Yes...");

                component.getParentNode().removeChild(component);
                component.setAttribute("name", slotId);

                logger.info("slotPositionComponentId:" + slotPositionComponentId);

                if (slotPositionComponentId != null && !slotPositionComponentId.equals("")) {
                    logger.info("Moving component to slot: " + slotPositionComponentId);

                    Element afterElement = null;

                    NodeList childNodes = parentComponentComponentsElement.getChildNodes();
                    for (int i = 0; i < childNodes.getLength(); i++) {
                        Node node = childNodes.item(i);
                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                            Element element = (Element) node;
                            if (element.getAttribute("id").equals(slotPositionComponentId)) {
                                afterElement = element;
                                break;
                            }
                        }
                    }

                    if (afterElement != null) {
                        logger.info("Inserting component before: " + afterElement);
                        parentComponentComponentsElement.insertBefore(component, afterElement);
                    } else {
                        parentComponentComponentsElement.appendChild(component);
                    }
                } else {
                    logger.info("Appending component...");
                    parentComponentComponentsElement.appendChild(component);
                }

                String modifiedXML = XMLHelper.serializeDom(document, new StringBuffer()).toString();

                ContentVO contentVO = NodeDeliveryController
                        .getNodeDeliveryController(siteNodeId, this.masterLanguageVO.getId(), contentId)
                        .getBoundContent(this.getInfoGluePrincipal(), siteNodeId, this.masterLanguageVO.getId(),
                                true, "Meta information", DeliveryContext.getDeliveryContext());
                ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController()
                        .getLatestActiveContentVersionVO(contentVO.getId(), this.masterLanguageVO.getId());

                ContentVersionController.getContentVersionController().updateAttributeValue(
                        contentVersionVO.getContentVersionId(), "ComponentStructure", modifiedXML,
                        this.getInfoGluePrincipal());

                this.url = getComponentRendererUrl() + getComponentRendererAction() + "?siteNodeId="
                        + this.siteNodeId + "&languageId=" + this.languageId + "&contentId=" + this.contentId
                        + "&focusElementId=" + componentId + "&componentContentId=" + componentContentVO.getId()
                        + "&showSimple=" + this.showSimple;
            } else if (allowed && (component.getParentNode() != parentComponentComponentsElement
                    || !slotId.equalsIgnoreCase(component.getAttribute("name")))) {
                logger.info("Moving component...");

                component.getParentNode().removeChild(component);
                component.setAttribute("name", slotId);

                if (slotPositionComponentId != null && !slotPositionComponentId.equals("")) {
                    NodeList childNodes = parentComponentComponentsElement.getChildNodes();
                    for (int i = 0; i < childNodes.getLength(); i++) {
                        Node node = childNodes.item(i);
                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                            Element element = (Element) node;
                            if (element.getAttribute("id").equals(slotPositionComponentId)) {
                                logger.info("Inserting component before: " + element);
                                parentComponentComponentsElement.insertBefore(component, element);
                                break;
                            }
                        }
                    }
                } else {
                    parentComponentComponentsElement.appendChild(component);
                }

                String modifiedXML = XMLHelper.serializeDom(document, new StringBuffer()).toString();

                ContentVO contentVO = NodeDeliveryController
                        .getNodeDeliveryController(siteNodeId, this.masterLanguageVO.getId(), contentId)
                        .getBoundContent(this.getInfoGluePrincipal(), siteNodeId, this.masterLanguageVO.getId(),
                                true, "Meta information", DeliveryContext.getDeliveryContext());
                ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController()
                        .getLatestActiveContentVersionVO(contentVO.getId(), this.masterLanguageVO.getId());

                ContentVersionController.getContentVersionController().updateAttributeValue(
                        contentVersionVO.getContentVersionId(), "ComponentStructure", modifiedXML,
                        this.getInfoGluePrincipal());

                this.url = getComponentRendererUrl() + getComponentRendererAction() + "?siteNodeId="
                        + this.siteNodeId + "&languageId=" + this.languageId + "&contentId=" + this.contentId
                        + "&focusElementId=" + componentId + "&componentContentId=" + componentContentVO.getId()
                        + "&showSimple=" + this.showSimple;
            } else {
                this.url = getComponentRendererUrl() + getComponentRendererAction() + "?siteNodeId="
                        + this.siteNodeId + "&languageId=" + this.languageId + "&contentId=" + this.contentId
                        + "&showSimple=" + this.showSimple;
            }
        }
    }

    //this.getResponse().sendRedirect(url);      

    this.url = this.getResponse().encodeURL(url);
    this.getResponse().sendRedirect(url);
    return NONE;
}

From source file:org.infoglue.cms.applications.structuretool.actions.ViewSiteNodePageComponentsAction.java

/**
 * This method creates a parameter for the given input type.
 * This is to support form steering information later.
 *//*  w w w. j  av  a 2 s  .co  m*/

private void addBindingElement(Element parent, String qualifyerXML) throws Exception {
    Document document = XMLHelper.readDocumentFromByteArray(qualifyerXML.getBytes("utf-8"));
    NodeList nl = document.getChildNodes().item(0).getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Element qualifyerElement = (Element) nl.item(i);
        //logger.info("qualifyerElement:" + qualifyerElement);
        String entityName = qualifyerElement.getNodeName();
        String assetKey = qualifyerElement.getAttribute("assetKey");
        String entityId = qualifyerElement.getFirstChild().getNodeValue();
        String supplementingEntityId = qualifyerElement.getAttribute("supplementingEntityId");
        String supplementingAssetKey = qualifyerElement.getAttribute("supplementingAssetKey");
        //logger.info("entityName:" + entityName);
        //logger.info("entityId:" + entityId);

        Element element = parent.getOwnerDocument().createElement("binding");
        element.setAttribute("entityId", entityId);
        element.setAttribute("entity", entityName);
        element.setAttribute("assetKey", assetKey);

        if (supplementingEntityId != null && !"".equals(supplementingEntityId)) {
            Element supplementingElement = parent.getOwnerDocument().createElement("supplementing-binding");
            supplementingElement.setAttribute("entityId", supplementingEntityId);
            supplementingElement.setAttribute("assetKey", StringEscapeUtils.escapeXml(supplementingAssetKey));
            element.appendChild(supplementingElement);
        }

        parent.appendChild(element);
    }
}

From source file:org.infoscoop.request.filter.HTMLFragmentFilter.java

public byte[] fragmentHTML(Document doc, String xpath, String encoding) {
    if (log.isDebugEnabled())
        log.debug("start fragmentHTML : xpath=" + xpath);

    Element root = doc.getDocumentElement();
    if (!"html".equalsIgnoreCase(root.getNodeName())) {
        NodeList htmlList = root.getElementsByTagName("html");
        if (htmlList.getLength() == 0) {
            log.error("document do not have html tag.");

            return null;
        }/*from   w  w w.jav a 2  s.c o  m*/
        root = (Element) htmlList.item(0);
    }

    if (log.isDebugEnabled())
        log.debug("before html : \n" + document2String(doc));

    // remove scriptTags
    /*
    NodeList scriptTags = XPathAPI.selectNodeList(root, "//script");
    int tagsLength = scriptTags.getLength();
    for(int i=0;i<tagsLength;i++){
       scriptTags.item(i).getParentNode().removeChild(scriptTags.item(i));;
    }
    */

    NodeList headTags = root.getElementsByTagName("head");
    for (int j = 0; j < headTags.getLength(); j++) {
        Element headTag = (Element) headTags.item(j);
        NodeList metas = headTag.getElementsByTagName("meta");
        for (int i = 0; i < metas.getLength(); i++) {
            Element tmpTag = (Element) metas.item(i);
            if (!"Content-Type".equalsIgnoreCase(tmpTag.getAttribute("http-equiv")))
                headTag.removeChild(tmpTag);
        }
    }

    Node targetNode = null;
    Node body = null;
    byte[] fragmentHTML = null;
    try {
        targetNode = XPathAPI.selectSingleNode(root, xpath);
        body = XPathAPI.selectSingleNode(root, "//body");
    } catch (Exception ex) {
        log.error("fragment failed.", ex);
    }

    if (log.isDebugEnabled())
        log.debug("target:" + targetNode + " : body:" + body);

    if (targetNode != null && body != null) {
        if ("body".equals(targetNode.getNodeName().toLowerCase())) {
            // No processing
        } else {
            NodeList childNodes = body.getChildNodes();
            int childLength = childNodes.getLength();
            for (int i = childLength - 1; 0 <= i; i--) {
                body.removeChild(childNodes.item(i));
            }
            body.appendChild(targetNode);
        }

        String resultHTML = document2String(doc);
        //FIXME
        resultHTML = resultHTML.replaceAll("&amp;", "&");

        if (log.isDebugEnabled()) {
            log.debug("result html : \n" + resultHTML);
        }

        try {
            fragmentHTML = resultHTML.getBytes(encoding);
        } catch (UnsupportedEncodingException ex) {
            log.error("Invalid encoding is specified.", ex);

            throw new IllegalArgumentException("unsupported encoding :[" + encoding + "]");
        }
    } else {
        log.error("target is null : " + targetNode + " : " + body + " @" + xpath);

        throw new IllegalArgumentException("node not found :[" + xpath + "]");
    }

    return fragmentHTML;
}

From source file:org.infoscoop.service.SiteAggregationMenuService.java

/**
 * Create JSONObject for under the menu top
 * /*from  w  ww  .j  ava2  s  .c  om*/
 * @param siteEl
 * @param json
 * @param mapJson
 * @throws DOMException
 * @throws JSONException
 * @throws TransformerException
 */
private static void addChildSiteJSON(String sitetopId, Element siteEl, JSONObject json, JSONObject mapJson,
        boolean isEditMode) throws DOMException, JSONException, TransformerException {
    NodeList childs = siteEl.getChildNodes();

    for (int i = 0; i < childs.getLength(); i++) {
        if (childs.item(i).getNodeType() != Node.ELEMENT_NODE)
            continue;

        Element childSite = (Element) childs.item(i);
        if ("site".equalsIgnoreCase(childSite.getNodeName())) {
            String siteId = childSite.getAttribute("id");

            json.put(siteId, siteToJSON(sitetopId, childSite, isEditMode));

            if (mapJson != null)
                mapJson.put(siteId, getChildSiteArray(childSite));

            addChildSiteJSON(sitetopId, childSite, json, mapJson, isEditMode);
        }
    }
}

From source file:org.infoscoop.service.SiteAggregationMenuService.java

/**
 * Create JSONArray that is child site of site|site-top.
 * //from   www .j a v  a  2s  .c o m
 * @param siteEl
 * @return
 */
private static JSONArray getChildSiteArray(Element siteEl) {
    JSONArray childSiteArray = new JSONArray();
    NodeList childs = siteEl.getChildNodes();

    for (int i = 0; i < childs.getLength(); i++) {
        if (childs.item(i).getNodeType() != Node.ELEMENT_NODE)
            continue;

        Element childSite = (Element) childs.item(i);
        if ("site".equalsIgnoreCase(childSite.getNodeName())) {
            childSiteArray.put(childSite.getAttribute("id"));
        }
    }
    return childSiteArray;
}