Example usage for org.w3c.dom Element hasAttribute

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

Introduction

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

Prototype

public boolean hasAttribute(String name);

Source Link

Document

Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise.

Usage

From source file:org.alfresco.web.config.forms.FormConfigRuntime.java

/**
 * @return//from   w  w w  .  j a  v a 2 s. com
 */
public HashMap<String, HashMap<String, FormConfigElement>> getModelTypeConfigForms() {
    HashMap<String, HashMap<String, FormConfigElement>> modelTypeConfigForms = new HashMap<String, HashMap<String, FormConfigElement>>();
    for (Element modelTypeElem : XmlUtils.findElements("config[@evaluator='model-type']",
            (Element) configDocument.getFirstChild())) {
        if (modelTypeElem.hasAttribute("condition")) {
            String condition = modelTypeElem.getAttribute("condition");
            HashMap<String, FormConfigElement> conditionForms = new HashMap<String, FormConfigElement>();
            for (Element conditionFormElem : XmlUtils.findElements(
                    "config[@evaluator='model-type' and @condition='" + condition + "']/forms/form",
                    (Element) configDocument.getFirstChild())) {
                if (conditionFormElem.hasAttribute("id")) {
                    String formId = conditionFormElem.getAttribute("id");
                    conditionForms.put(formId, this.getModelTypeConfigForm(condition, formId));
                } else {
                    conditionForms.put("default", this.getModelTypeConfigForm(condition, null));
                }
            }
            modelTypeConfigForms.put(condition, conditionForms);
        }
    }
    return modelTypeConfigForms;
}

From source file:org.springmodules.validation.bean.conf.namespace.AnnotationBasedValidatorBeanDefinitionParser.java

protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {

    BeanDefinitionBuilder registryBuilder = BeanDefinitionBuilder
            .rootBeanDefinition(DefaultValidationAnnotationHandlerRegistry.class);
    parseHandlerElements(element, registryBuilder);
    AbstractBeanDefinition beanDefinition = registryBuilder.getBeanDefinition();
    String validatorId = resolveId(element, beanDefinition, parserContext);
    String registryId = HANDLER_REGISTRY_PREFIX + validatorId;
    parserContext.getRegistry().registerBeanDefinition(registryId, beanDefinition);

    BeanDefinitionBuilder loaderBuilder = BeanDefinitionBuilder
            .rootBeanDefinition(AnnotationBeanValidationConfigurationLoader.class);
    loaderBuilder.addPropertyReference("handlerRegistry", registryId);
    beanDefinition = loaderBuilder.getBeanDefinition();
    String loaderId = CONFIGURATION_LOADER_PREFIX + validatorId;
    parserContext.getRegistry().registerBeanDefinition(loaderId, beanDefinition);

    BeanDefinitionBuilder validatorBuilder = BeanDefinitionBuilder.rootBeanDefinition(BeanValidator.class);
    if (element.hasAttribute(AnnotationBasedValidatorBeanDefinitionParser.ERROR_CODE_CONVERTER_ATTR)) {
        validatorBuilder.addPropertyReference("errorCodeConverter",
                element.getAttribute(AnnotationBasedValidatorBeanDefinitionParser.ERROR_CODE_CONVERTER_ATTR));
    }/*from w  w w. ja  v a2  s . c o m*/
    validatorBuilder.addPropertyReference("configurationLoader", loaderId);

    return validatorBuilder.getBeanDefinition();
}

From source file:net.sourceforge.dita4publishers.impl.ditabos.DitaTreeWalkerBase.java

/**
 * @param bos//from   w w w .j a  va  2  s .c o m
 * @param member
 * @param newMembers
 * @throws Exception 
 */
protected void findLinkDependencies(BoundedObjectSet bos, XmlBosMember member, Set<BosMember> newMembers)
        throws Exception {
    NodeList links;
    try {
        links = (NodeList) DitaUtil.allHrefsAndKeyrefs.evaluate(member.getElement(), XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new BosException("Unexcepted exception evaluating xpath " + DitaUtil.allTopicrefs);
    }

    log.debug("findLinkDependencies(): Found " + links.getLength() + " href- or keyref-using elements");

    for (int i = 0; i < links.getLength(); i++) {
        Element link = (Element) links.item(i);
        Document targetDoc = null;
        URI targetUri = null;
        String dependencyKey = null; // Original href or keyref value

        // If there is a key reference, attempt to resolve it,
        // then fall back to href, if any.
        String href = null;
        DependencyType depType = Constants.LINK_DEPENDENCY;
        if (DitaUtil.isDitaType(link, "topic/image")) {
            depType = Constants.IMAGE_DEPENDENCY;
        } else if (DitaUtil.isDitaType(link, "topic/xref")) {
            depType = Constants.XREF_DEPENDENCY;
        }
        try {
            if (link.hasAttribute("keyref")) {
                log.debug("findLinkDependencies(): resolving reference to key \"" + link.getAttribute("keyref")
                        + "\"...");
                if (!DitaUtil.targetIsADitaFormat(link) || DitaUtil.isDitaType(link, "topic/image")) {
                    targetUri = resolveKeyrefToUri(link.getAttribute("keyref"));
                } else {
                    targetDoc = resolveKeyrefToDoc(link.getAttribute("keyref"));
                }
            }
            if (targetUri == null && targetDoc == null && link.hasAttribute("href")) {
                log.debug("findLinkDependencies(): resolving reference to href \"" + link.getAttribute("href")
                        + "\"...");
                href = link.getAttribute("href");
                dependencyKey = href;
                if (DitaUtil.isDitaType(link, "topic/image")) {
                    targetUri = AddressingUtil.resolveHrefToUri(link, link.getAttribute("href"),
                            this.failOnAddressResolutionFailure);
                } else if (!DitaUtil.targetIsADitaFormat(link) && DitaUtil.isLocalOrPeerScope(link)) {
                    targetUri = AddressingUtil.resolveHrefToUri(link, link.getAttribute("href"),
                            this.failOnAddressResolutionFailure);
                } else {
                    // If we get here, isn't an image reference and is presumably a DITA format resource.
                    // Don't bother with links within the same XML document.
                    if (!href.startsWith("#") && DitaUtil.isLocalOrPeerScope(link)) {
                        targetDoc = AddressingUtil.resolveHrefToDoc(link, link.getAttribute("href"),
                                bosConstructionOptions, this.failOnAddressResolutionFailure);
                    }

                }
            } else {
                dependencyKey = AddressingUtil.getKeyNameFromKeyref(link);
            }
        } catch (AddressingException e) {
            if (this.failOnAddressResolutionFailure) {
                throw new BosException(
                        "Failed to resolve href \"" + link.getAttribute("href") + "\" to a managed object", e);
            }
        }

        if (targetDoc == null && targetUri == null || targetDoc == member.getDocument())
            continue;

        BosMember depMember = null;
        if (targetDoc != null) {
            log.debug("findLinkDependencies(): Got document \"" + targetDoc.getDocumentURI() + "\"");
            depMember = bos.constructBosMember(member, targetDoc);
        } else if (targetUri != null) {
            log.debug("findLinkDependencies(): Got URI \"" + targetUri.toString() + "\"");
            depMember = bos.constructBosMember((BosMember) member, targetUri);
        }
        newMembers.add(depMember);
        bos.addMemberAsDependency(dependencyKey, depType, member, depMember);
    }

}

From source file:org.springmodules.validation.bean.conf.namespace.XmlBasedValidatorBeanDefinitionParser.java

protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {

    BeanDefinitionBuilder registryBuilder = BeanDefinitionBuilder
            .rootBeanDefinition(DefaultValidationRuleElementHandlerRegistry.class);
    parseHandlerElements(element, registryBuilder);
    AbstractBeanDefinition beanDefinition = registryBuilder.getBeanDefinition();
    String validatorId = resolveId(element, beanDefinition, parserContext);
    String registryId = HANDLER_REGISTRY_PREFIX + validatorId;
    parserContext.getRegistry().registerBeanDefinition(registryId, beanDefinition);

    String loaderId = CONFIGURATION_LOADER_PREFIX + validatorId;
    BeanDefinitionBuilder loaderBuilder = BeanDefinitionBuilder
            .rootBeanDefinition(DefaultXmlBeanValidationConfigurationLoader.class);
    parseResourcesElements(element, loaderBuilder);
    loaderBuilder.addPropertyReference("elementHandlerRegistry", registryId);
    parserContext.getRegistry().registerBeanDefinition(loaderId, loaderBuilder.getBeanDefinition());

    BeanDefinitionBuilder validatorBuilder = BeanDefinitionBuilder.rootBeanDefinition(BeanValidator.class);
    if (element.hasAttribute(ERROR_CODE_CONVERTER_ATTR)) {
        validatorBuilder.addPropertyReference("errorCodeConverter",
                element.getAttribute(ERROR_CODE_CONVERTER_ATTR));
    }/*  ww  w.  j a  v a  2  s .c o  m*/
    validatorBuilder.addPropertyReference("configurationLoader", loaderId);

    return validatorBuilder.getBeanDefinition();
}

From source file:org.gvnix.support.WebProjectUtilsImpl.java

/**
 * Replaces all namespaces occurrences contained in {@code oldUriMap} in
 * given {@relativePath} file with namespaces occurrences contained in
 * {@code newUriMap}./*from  ww  w  .jav a 2 s  .  c om*/
 * <p/>
 * A namespace in given {@relativePath} file will be replaced by a namespace
 * in {@code newUriMap} when one of the conditions below is true:
 * <p/>
 * <strong>A.</strong> Namespace name is in {@code oldUriMap}, as is in
 * {@code newUriMap} and as is in {@relativePath} file and old namespace
 * (value in {@code oldUriMap}) match with namespace in jspx.
 * <p/>
 * <strong>B.</strong> Namespace name is not in {@code oldUriMap} and
 * namespace name is in {@relativePath} file
 * 
 * @param relativePath XML file to update. The path must be relative to
 *        {@code src/main/webapp} (cannot be null, but may be empty if
 *        referring to the path itself)
 * @param oldUriMap (optional) Keys are namespace names (ex: "xmlns:page")
 *        and values are the old namespace URI (ex:
 *        "urn:jsptagdir:/WEB-INF/tags/form") that must match with the
 *        namespace URI in the XML
 * @param newUriMap Keys are namespace names (ex: "xmlns:page") and values
 *        are the new namespace URI (ex:
 *        "urn:jsptagdir:/WEB-INF/tags/datatables")
 * @param projectOperations
 * @param fileManager
 */

public void updateTagxUriInJspx(String relativePath, Map<String, String> oldUriMap,
        Map<String, String> newUriMap, ProjectOperations projectOperations, FileManager fileManager) {

    // If null, create default oldUriMap causing jspx will be updated with
    // all URIs in newUriMap
    if (oldUriMap == null) {
        oldUriMap = new HashMap<String, String>();
    }

    // Get jspx file path
    PathResolver pathResolver = projectOperations.getPathResolver();
    String docJspx = pathResolver.getIdentifier(getWebappPath(projectOperations), relativePath);

    // Parse XML document
    Document docJspXml = loadXmlDocument(docJspx, fileManager);
    if (docJspXml == null) {
        // file not found: do nothing
        return;
    }

    // Get main div
    Element docRoot = docJspXml.getDocumentElement();
    Element divMain = XmlUtils.findFirstElement("/div", docRoot);
    boolean modified = false;

    // Update namespace URIs
    for (Entry<String, String> newUriEntry : newUriMap.entrySet()) {
        String nsName = newUriEntry.getKey();
        String nsUri = newUriEntry.getValue();

        // Namespace name is in oldUriMap, as is in and as is in given file
        // and old namespace (value in oldUriMap) match with namespace in
        // jspx
        if (oldUriMap.containsKey(nsName) && divMain.hasAttribute(nsName)) {
            String oldNsUri = oldUriMap.get(nsName);
            String currentUri = divMain.getAttribute(nsName);

            if (StringUtils.isEmpty(oldNsUri) || oldNsUri.equalsIgnoreCase(currentUri)) {
                // Compares new value with current before change
                if (!StringUtils.equalsIgnoreCase(currentUri, nsUri)) {
                    divMain.setAttribute(nsName, nsUri);
                    modified = true;
                }
            }
        }

        // Namespace name is not in oldUriMap and namespace name is in
        // given file
        if (!oldUriMap.containsKey(nsName) && divMain.hasAttribute(nsName)) {
            // Compares new value with current before change
            if (!StringUtils.equalsIgnoreCase(divMain.getAttribute(nsName), nsUri)) {
                divMain.setAttribute(nsName, nsUri);
                modified = true;
            }
        }
    }

    // If modified, update the jspx file
    if (modified) {
        DomUtils.removeTextNodes(docJspXml);
        fileManager.createOrUpdateTextFileIfRequired(docJspx, XmlUtils.nodeToString(docJspXml), true);
    }
}

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

public void createJavaFile(String tableName, boolean reportFlag) {
    try {//from   www .  j a  va  2  s  .  co m
        File f1 = new File(PropsValues.GENERATE_DIR_PATH + "service.xml");
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(f1);
        NodeList entity = doc.getElementsByTagName("entity");
        List<EntityColumn> columnList = new ArrayList<EntityColumn>();
        List<EntityColumn> regularColList = new ArrayList<EntityColumn>();
        List<EntityColumn> pkList = new ArrayList<EntityColumn>();
        List<EntityColumn> fkList = new ArrayList<EntityColumn>();
        NodeList columns = ((Element) entity.item(0)).getElementsByTagName("column");//.item(0);
        for (int i = 0; i < columns.getLength(); i++) {
            Element columnElement = (Element) columns.item(i);
            boolean primary = columnElement.hasAttribute("primary") ? true : false;
            boolean foreign = columnElement.hasAttribute("foreign") ? true : false;
            String columnName = columnElement.getAttribute("name");
            String defaultValue = columnElement.hasAttribute("default") ? columnElement.getAttribute("default")
                    : "";
            String columnType = "";
            if (foreign) {
                columnType = columnElement.getAttribute("class");
            } else {
                columnType = columnElement.getAttribute("type");
            }
            boolean convertNull = GetterUtil.getBoolean(null, true);
            EntityColumn col = new EntityColumn(columnName, columnType, primary, foreign, convertNull,
                    defaultValue);
            if (primary) {
                pkList.add(col);
            }
            if (foreign) {
                fkList.add(col);
            } //else{
            regularColList.add(col);
            //                }
            columnList.add(col);
        }
        _ejbList = new ArrayList<Entity>();
        String ejbName = tableName; // entity-> name
        String table = "";// entity-> table
        if (StringUtil.isNullOrEmpty(table)) {
            table = ejbName;
        }
        // iterate for columns
        String packagePath = PropsValues.PACKAGE_PATH;
        Entity entityObj = new Entity(packagePath, ejbName, table, regularColList, columnList, pkList, fkList);
        _ejbList.add(entityObj);
        if (entityObj.hasColumns()) {
            _createModel(entityObj);
        }

        packagePath = PropsValues.PACKAGE_PATH;
        boolean createTableFlg = true;
        Entity entityObj1 = new Entity(packagePath, "impl_" + ejbName, reportFlag, ejbName, createTableFlg);
        _ejbList.add(entityObj1);
        _createModelImpl(entityObj1);

        //Check before adding a cfg entry in _createHbmXml()
        boolean flag = isModuleNew(ejbName);
        if (!flag) {
            deleteClassesModuleStuf(ejbName);
        }
        _createHbmXml(ejbName);
        //            _setModuleProperties(ejbName);
        //_buildModule();

        String resourceName = "";
        if (flag) {
            resourceName = PropsValues.PACKAGE_FILE_PATH + ejbName + ".hbm.xml";
        }
        //            writeToClassesCfgXml(ejbName);
    } catch (Exception ex) {
        logger.warn(ex.getMessage(), ex);
    }
}

From source file:com.concursive.connect.web.modules.wiki.utils.HTMLToWikiUtils.java

public static void processTable(NodeList nodeList, StringBuffer sb, int rowCount, boolean doText,
        boolean anyNodeType, String contextPath, int projectId, int pass) {
    LOG.trace("line reset");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node n = nodeList.item(i);
        if (n != null) {
            if (n.getNodeType() == Node.TEXT_NODE || n.getNodeType() == Node.CDATA_SECTION_NODE) {
                if (doText && anyNodeType) {
                    if (StringUtils.hasText(n.getNodeValue())) {
                        String thisLine = StringUtils.fromHtmlValue(n.getNodeValue());
                        LOG.trace("table - text: " + thisLine);
                        sb.append(thisLine);
                    }/*from  w ww .  j  a v a2s.  c o  m*/
                }
            } else if (n.getNodeType() == Node.ELEMENT_NODE) {
                Element element = ((Element) n);
                String tag = element.getTagName();
                if ("tr".equals(tag)) {
                    LOG.trace("table - tr");
                    ++rowCount;
                    if (rowCount == 1) {
                        LOG.debug("Looking for style");
                        processTable(n.getChildNodes(), sb, rowCount, false, false, contextPath, projectId, 1);
                    }
                    processTable(n.getChildNodes(), sb, rowCount, false, false, contextPath, projectId, 2);
                    sb.append(CRLF);
                } else if ("td".equals(tag) || "th".equals(tag)) {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("table - " + tag + " - " + i + " " + hasNonTextNodes(n.getChildNodes())
                                + " - pass " + pass);
                    }
                    String separator = "|";
                    if (tag.equals("th")) {
                        separator = "||";
                    }

                    // Determin how many columns are spanned by this column
                    int colspan = 1;
                    if (element.hasAttribute("colspan")) {
                        colspan = Integer.parseInt(element.getAttribute("colspan"));
                    }
                    //            if (sb.toString().endsWith(separator)) {
                    //              sb.append(" ");
                    //            }

                    // Style pass
                    boolean hasStyle = false;
                    if (pass == 1) {
                        if (element.hasAttribute("style")) {
                            String style = element.getAttribute("style");
                            if (style.endsWith(";")) {
                                style = style.substring(0, style.length() - 1);
                            }
                            // Start the wiki markup
                            for (int sI = 0; sI < colspan; sI++) {
                                sb.append(separator);
                            }
                            // Append the style data
                            sb.append("{").append(style).append("}");
                            hasStyle = true;
                        }

                        // Close the wiki markup if the last cell
                        if (hasStyle) {
                            if (i + 1 == nodeList.getLength()) {
                                sb.append(separator);
                                // The style pass needs to add it's own CRLF
                                sb.append(CRLF);
                            }
                        }
                    }

                    // Data pass
                    if (pass == 2) {

                        // Start the wiki markup
                        for (int sI = 0; sI < colspan; sI++) {
                            sb.append(separator);
                        }

                        if (n.getChildNodes().getLength() > 0) {
                            // Cell data uses a "!" for each return
                            if (hasNonTextNodes(n.getChildNodes())) {
                                processChildNodes(getNodeList(n), sb, 0, true, true, false, "!", contextPath,
                                        projectId);
                            } else {
                                processChildNodes(getNodeList(n), sb, 0, true, true, false, "!", contextPath,
                                        projectId);
                            }
                            // If the cell didn't have any data, then add a space
                            if (sb.toString().endsWith(separator)) {
                                sb.append(" ");
                            }
                        } else {
                            sb.append(" ");
                        }

                        // Close the wiki markup
                        if (i + 1 == nodeList.getLength()) {
                            sb.append(separator);
                        }
                    }
                } else {
                    LOG.trace("table - text - ** " + tag);
                    processTable(n.getChildNodes(), sb, rowCount, true, true, contextPath, projectId, 0);
                }
            }
        }
    }
}

From source file:org.alfresco.web.config.forms.FormConfigRuntime.java

public boolean compareAttributeList(Element attributeElem, Map<String, String> attributeList) {
    if (compareObject(attributeElem, attributeList)) {
        return true;
    }/*from  w w w.  j av  a 2  s .  co  m*/
    if (attributeElem != null) {
        if (attributeElem.getAttributes().getLength() != attributeList.size()) {
            return true;
        }
        for (String key : attributeList.keySet()) {
            if (!attributeElem.hasAttribute(key)
                    || !attributeElem.getAttribute(key).equals(attributeList.get(key))) {
                return true;
            }
        }
    }
    return false;
}

From source file:com.icesoft.faces.context.BridgeFacesContext.java

protected void applyBrowserFormChanges(Map parameters, Document document, Element form) {
    NodeList inputElements = form.getElementsByTagName("input");
    int inputElementsLength = inputElements.getLength();
    for (int i = 0; i < inputElementsLength; i++) {
        Element inputElement = (Element) inputElements.item(i);
        String id = inputElement.getAttribute("id");
        if (!"".equals(id)) {
            String name = null;//  w  ww.  j a va  2 s  .  c o  m
            if (parameters.containsKey(id)) {
                String value = ((String[]) parameters.get(id))[0];
                //empty string is implied (default) when 'value' attribute is missing
                if (!"".equals(value)) {
                    if (inputElement.hasAttribute("value")) {
                        inputElement.setAttribute("value", value);
                    } else if (inputElement.getAttribute("type").equals("checkbox")) {
                        inputElement.setAttribute("checked", "checked");
                    }
                } else {
                    inputElement.setAttribute("value", "");
                }
            } else if (!"".equals(name = inputElement.getAttribute("name")) && parameters.containsKey(name)) {
                String type = inputElement.getAttribute("type");
                if (type != null && type.equals("checkbox") || type.equals("radio")) {
                    String currValue = inputElement.getAttribute("value");
                    if (!"".equals(currValue)) {
                        boolean found = false;
                        // For multiple checkboxes, values can have length > 1,
                        // but for multiple radios, values would have at most length=1
                        String[] values = (String[]) parameters.get(name);
                        if (values != null) {
                            for (int v = 0; v < values.length; v++) {
                                if (currValue.equals(values[v])) {
                                    found = true;
                                    break;
                                }
                            }
                        }
                        if (found) {
                            // For some reason, our multiple checkbox 
                            // components use checked="true", while
                            // our single checkbox components use
                            // checked="checked". The latter complying
                            // with the HTML specification.
                            // Also, radios use checked="checked"
                            if (type.equals("checkbox")) {
                                inputElement.setAttribute("checked", "true");
                            } else if (type.equals("radio")) {
                                inputElement.setAttribute("checked", "checked");
                            }
                        } else {
                            inputElement.removeAttribute("checked");
                        }
                    }
                }
            } else {
                if (inputElement.getAttribute("type").equals("checkbox")) {
                    ////inputElement.setAttribute("checked", "");
                    inputElement.removeAttribute("checked");
                }
            }
        }
    }

    NodeList textareaElements = form.getElementsByTagName("textarea");
    int textareaElementsLength = textareaElements.getLength();
    for (int i = 0; i < textareaElementsLength; i++) {
        Element textareaElement = (Element) textareaElements.item(i);
        String id = textareaElement.getAttribute("id");
        if (!"".equals(id) && parameters.containsKey(id)) {
            String value = ((String[]) parameters.get(id))[0];
            Node firstChild = textareaElement.getFirstChild();
            if (null != firstChild) {
                //set value on the Text node
                firstChild.setNodeValue(value);
            } else {
                //DOM brought back from compression may have no
                //child for empty TextArea
                if (value != null && value.length() > 0) {
                    textareaElement.appendChild(document.createTextNode(value));
                }
            }
        }
    }

    NodeList selectElements = form.getElementsByTagName("select");
    int selectElementsLength = selectElements.getLength();
    for (int i = 0; i < selectElementsLength; i++) {
        Element selectElement = (Element) selectElements.item(i);
        String id = selectElement.getAttribute("id");
        if (!"".equals(id) && parameters.containsKey(id)) {
            List values = Arrays.asList((String[]) parameters.get(id));

            NodeList optionElements = selectElement.getElementsByTagName("option");
            int optionElementsLength = optionElements.getLength();
            for (int j = 0; j < optionElementsLength; j++) {
                Element optionElement = (Element) optionElements.item(j);
                if (values.contains(optionElement.getAttribute("value"))) {
                    optionElement.setAttribute("selected", "selected");
                } else {
                    optionElement.removeAttribute("selected");
                }
            }
        }
    }
}