Example usage for org.w3c.dom Element setAttribute

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

Introduction

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

Prototype

public void setAttribute(String name, String value) throws DOMException;

Source Link

Document

Adds a new attribute.

Usage

From source file:com.connexta.arbitro.utils.PolicyUtils.java

/**
 * This method creates a match elementof the XACML policy
 * @param matchElementDTO match element data object
 * @param doc XML document//from  w w  w.ja v  a  2s  .  com
 * @return match Element
 * @throws PolicyBuilderException throws
 */
public static Element createMatchElement(MatchElementDTO matchElementDTO, Document doc)
        throws PolicyBuilderException {

    Element matchElement = null;
    if (matchElementDTO.getMatchId() != null && matchElementDTO.getMatchId().trim().length() > 0) {

        matchElement = doc.createElement(PolicyConstants.MATCH_ELEMENT);

        matchElement.setAttribute(PolicyConstants.MATCH_ID, matchElementDTO.getMatchId());

        if (matchElementDTO.getAttributeValueElementDTO() != null) {
            Element attributeValueElement = createAttributeValueElement(
                    matchElementDTO.getAttributeValueElementDTO(), doc);
            matchElement.appendChild(attributeValueElement);
        }

        if (matchElementDTO.getAttributeDesignatorDTO() != null) {
            Element attributeDesignatorElement = createAttributeDesignatorElement(
                    matchElementDTO.getAttributeDesignatorDTO(), doc);
            matchElement.appendChild(attributeDesignatorElement);
        }

        if (matchElementDTO.getAttributeSelectorDTO() != null) {
            Element attributeSelectorElement = createAttributeSelectorElement(
                    matchElementDTO.getAttributeSelectorDTO(), doc);
            matchElement.appendChild(attributeSelectorElement);
        }
    }
    return matchElement;
}

From source file:com.granule.json.utils.XML.java

private static void convertJSONObject(Document doc, Element parent, JSONObject jObject, String tagName) {
    Set attributes = jObject.keySet();
    Iterator attrsItr = attributes.iterator();

    Element element = doc.createElement(removeProblemCharacters(tagName));
    if (parent != null) {
        parent.appendChild(element);//from www  .  j  a v a 2 s  .c  o m
    } else {
        doc.appendChild(element);
    }

    while (attrsItr.hasNext()) {
        String attr = (String) attrsItr.next();
        Object obj = jObject.opt(attr);

        if (obj instanceof Number) {
            element.setAttribute(attr, obj.toString());
        } else if (obj instanceof Boolean) {
            element.setAttribute(attr, obj.toString());
        } else if (obj instanceof String) {
            element.setAttribute(attr, escapeEntityCharacters(obj.toString()));
        } else if (obj == null) {
            element.setAttribute(attr, "");
        } else if (obj instanceof JSONObject) {
            convertJSONObject(doc, element, (JSONObject) obj, attr);
        } else if (obj instanceof JSONArray) {
            convertJSONArray(doc, element, (JSONArray) obj, attr);
        }
    }
}

From source file:com.centeractive.ws.builder.soap.SchemaUtils.java

/**
 * Returns a map mapping urls to corresponding XmlSchema XmlObjects for the
 * specified wsdlUrl/*from w ww .j  ava2s.com*/
 */

public static void getSchemas(String wsdlUrl, Map<String, XmlObject> existing, SchemaLoader loader,
        String tns) {
    if (existing.containsKey(wsdlUrl)) {
        return;
    }

    // if( add )
    // existing.put( wsdlUrl, null );

    log.info("Getting schema " + wsdlUrl);

    ArrayList<?> errorList = new ArrayList<Object>();

    Map<String, XmlObject> result = new HashMap<String, XmlObject>();

    boolean common = false;

    try {
        XmlOptions options = new XmlOptions();
        options.setCompileNoValidation();
        options.setSaveUseOpenFrag();
        options.setErrorListener(errorList);
        options.setSaveSyntheticDocumentElement(new QName(Constants.XSD_NS, "schema"));

        XmlObject xmlObject = loader.loadXmlObject(wsdlUrl, options);
        if (xmlObject == null)
            throw new Exception("Failed to load schema from [" + wsdlUrl + "]");

        Document dom = (Document) xmlObject.getDomNode();
        Node domNode = dom.getDocumentElement();

        // is this an xml schema?
        if (domNode.getLocalName().equals("schema") && Constants.XSD_NS.equals(domNode.getNamespaceURI())) {
            // set targetNamespace (this happens if we are following an include
            // statement)
            if (tns != null) {
                Element elm = ((Element) domNode);
                if (!elm.hasAttribute("targetNamespace")) {
                    common = true;
                    elm.setAttribute("targetNamespace", tns);
                }

                // check for namespace prefix for targetNamespace
                NamedNodeMap attributes = elm.getAttributes();
                int c = 0;
                for (; c < attributes.getLength(); c++) {
                    Node item = attributes.item(c);
                    if (item.getNodeName().equals("xmlns"))
                        break;

                    if (item.getNodeValue().equals(tns) && item.getNodeName().startsWith("xmlns"))
                        break;
                }

                if (c == attributes.getLength())
                    elm.setAttribute("xmlns", tns);
            }

            if (common && !existing.containsKey(wsdlUrl + "@" + tns))
                result.put(wsdlUrl + "@" + tns, xmlObject);
            else
                result.put(wsdlUrl, xmlObject);
        } else {
            existing.put(wsdlUrl, null);

            XmlObject[] schemas = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:schema");

            for (int i = 0; i < schemas.length; i++) {
                XmlCursor xmlCursor = schemas[i].newCursor();
                String xmlText = xmlCursor.getObject().xmlText(options);
                // schemas[i] = XmlObject.Factory.parse( xmlText, options );
                schemas[i] = XmlUtils.createXmlObject(xmlText, options);
                schemas[i].documentProperties().setSourceName(wsdlUrl);

                result.put(wsdlUrl + "@" + (i + 1), schemas[i]);
            }

            XmlObject[] wsdlImports = xmlObject
                    .selectPath("declare namespace s='" + Constants.WSDL11_NS + "' .//s:import/@location");
            for (int i = 0; i < wsdlImports.length; i++) {
                String location = ((SimpleValue) wsdlImports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] wadl10Imports = xmlObject.selectPath(
                    "declare namespace s='" + Constants.WADL10_NS + "' .//s:grammars/s:include/@href");
            for (int i = 0; i < wadl10Imports.length; i++) {
                String location = ((SimpleValue) wadl10Imports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] wadlImports = xmlObject.selectPath(
                    "declare namespace s='" + Constants.WADL11_NS + "' .//s:grammars/s:include/@href");
            for (int i = 0; i < wadlImports.length; i++) {
                String location = ((SimpleValue) wadlImports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

        }

        existing.putAll(result);

        XmlObject[] schemas = result.values().toArray(new XmlObject[result.size()]);

        for (int c = 0; c < schemas.length; c++) {
            xmlObject = schemas[c];

            XmlObject[] schemaImports = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:import/@schemaLocation");
            for (int i = 0; i < schemaImports.length; i++) {
                String location = ((SimpleValue) schemaImports[i]).getStringValue();
                Element elm = ((Attr) schemaImports[i].getDomNode()).getOwnerElement();

                if (location != null && !defaultSchemas.containsKey(elm.getAttribute("namespace"))) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] schemaIncludes = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:include/@schemaLocation");
            for (int i = 0; i < schemaIncludes.length; i++) {
                String location = ((SimpleValue) schemaIncludes[i]).getStringValue();
                if (location != null) {
                    String targetNS = getTargetNamespace(xmlObject);

                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, targetNS);
                }
            }
        }
    } catch (Exception e) {
        throw new SoapBuilderException(e);
    }
}

From source file:fr.aliasource.webmail.server.proxy.client.http.folder.AbstractFolderMethod.java

protected Document getFolderAsXML(Folder f) throws ParserConfigurationException, FactoryConfigurationError {
    Document doc = DOMUtils.createDoc("http://obm.aliasource.fr/xsd/folder_list", "folderList");
    Element root = doc.getDocumentElement();
    Element fe = DOMUtils.createElement(root, "folder");
    fe.setAttribute("displayName", f.getDisplayName());
    fe.setAttribute("name", f.getName());
    fe.setAttribute("subscribed", String.valueOf(f.isSubscribed()));
    fe.setAttribute("shared", String.valueOf(f.isShared()));

    return doc;/*from  ww  w .  j  a  va2  s .  com*/
}

From source file:com.twinsoft.convertigo.engine.localbuild.BuildLocally.java

private static Element cloneNode(Node node, String newNodeName) {

    Element newElement = node.getOwnerDocument().createElement(newNodeName);

    NamedNodeMap attrs = node.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr = (Attr) attrs.item(i);
        newElement.setAttribute(attr.getName(), attr.getValue());
    }/*from w ww . ja  va 2  s . com*/

    return newElement;

}

From source file:org.jasig.portlet.announcements.spring.LazyInitByDefaultBeanDefinitionDocumentReader.java

@Override
protected BeanDefinitionParserDelegate createDelegate(XmlReaderContext readerContext, Element root,
        BeanDefinitionParserDelegate parentDelegate) {
    root.setAttribute(BeanDefinitionParserDelegate.DEFAULT_LAZY_INIT_ATTRIBUTE, "true");
    return super.createDelegate(readerContext, root, parentDelegate);
}

From source file:org.jasig.portlet.calendar.spring.LazyInitByDefaultBeanDefinitionDocumentReader.java

@Override
protected BeanDefinitionParserDelegate createHelper(XmlReaderContext readerContext, Element root,
        BeanDefinitionParserDelegate parentDelegate) {
    root.setAttribute(BeanDefinitionParserDelegate.DEFAULT_LAZY_INIT_ATTRIBUTE, "true");
    return super.createHelper(readerContext, root, parentDelegate);
}

From source file:com.icesoft.faces.util.CoreUtils.java

public static void addPanelTooltip(FacesContext facesContext, UIComponent uiComponent) {
    DOMContext domContext = DOMContext.getDOMContext(facesContext, uiComponent);
    if (uiComponent.getAttributes().get("panelTooltip") == null)
        return;/*from www .j  a v  a2 s .  c o  m*/
    String panelTooltipId = String.valueOf(uiComponent.getAttributes().get("panelTooltip"));
    int delay = 500;
    String hideOn = "mouseout";
    boolean dynamic = false;
    String formId = "";
    String ctxValue = "";
    String displayOn = "hover";
    boolean moveWithMouse = false;

    //TODO: convert to :: utility findComponent
    //            UIComponent panelTooltip = D2DViewHandler.findComponent(panelTooltipId, uiComponent);
    //            UIComponent panelTooltip = facesContext.getViewRoot().findComponent(panelTooltipId);
    UIComponent panelTooltip = CoreComponentUtils.findComponent(panelTooltipId, uiComponent);
    if (panelTooltip != null/* && family type equals panelPopup*/) {
        //replace the id with the clientid
        panelTooltipId = panelTooltip.getClientId(facesContext);
        if (panelTooltip.getAttributes().get("hideOn") != null) {
            hideOn = String.valueOf(panelTooltip.getAttributes().get("hideOn"));
        }
        if (panelTooltip.getAttributes().get("dynamic") != null) {
            dynamic = ((Boolean) panelTooltip.getAttributes().get("dynamic")).booleanValue();
        }
        if (panelTooltip.getAttributes().get("hoverDelay") != null) {
            delay = new Integer(String.valueOf(panelTooltip.getAttributes().get("hoverDelay"))).intValue();
        }
        if (uiComponent.getAttributes().get("contextValue") != null) {
            ctxValue = String.valueOf(uiComponent.getAttributes().get("contextValue"));
        }
        if (panelTooltip.getAttributes().get("displayOn") != null) {
            displayOn = String.valueOf(panelTooltip.getAttributes().get("displayOn"));
        }
        if (panelTooltip.getAttributes().get("moveWithMouse") != null) {
            moveWithMouse = ((Boolean) panelTooltip.getAttributes().get("moveWithMouse")).booleanValue();
        }
    }
    UIComponent form = DomBasicRenderer.findForm(panelTooltip);
    if (form != null) {
        formId = form.getClientId(facesContext);
    }

    Element rootElement = (Element) domContext.getRootNode();
    String onAttr, onValue;
    if (displayOn.equals("click") || displayOn.equals("dblclick")) {
        onAttr = "on" + displayOn;
    } else if (displayOn.equals("altclick")) {
        onAttr = "oncontextmenu";
    } else {
        onAttr = "onmouseover";
    }
    onValue = String.valueOf(rootElement.getAttribute(onAttr));
    onValue += "; new ToolTipPanelPopup(this, '" + panelTooltipId + "', event, '" + hideOn + "','" + delay
            + "', '" + dynamic + "', '" + formId + "', '" + ctxValue + "','"
            + CoreUtils.resolveResourceURL(facesContext, "/xmlhttp/blank") + "','" + displayOn + "',"
            + moveWithMouse + ");";
    rootElement.setAttribute(onAttr, onValue);
}

From source file:cz.mzk.editor.server.fedora.utils.FedoraUtils.java

/**
 * Create new relations part./*from ww w. j ava2s.c o  m*/
 * 
 * @param detail
 *        the detail
 * @return content content of the new relations part
 */
public static String createNewRealitonsPart(DigitalObjectDetail detail) {
    if (detail.getAllItems() == null)
        return null;

    Document relsExt = null;

    try {
        relsExt = fedoraAccess.getRelsExt(detail.getUuid());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        XPathExpression all = makeNSAwareXpath().compile("/rdf:RDF/rdf:Description");
        NodeList nodes1 = (NodeList) all.evaluate(relsExt, XPathConstants.NODESET);
        Element parent = null;
        if (nodes1.getLength() != 0) {
            parent = (Element) nodes1.item(0);
        }

        int modelId = 0;
        boolean changed = false;
        List<DigitalObjectModel> models = NamedGraphModel.getChildren(detail.getModel());
        for (List<DigitalObjectDetail> data : detail.getAllItems()) {
            if (data != null) { // is changed
                changed = true;
                String xPathString = NamedGraphModel.getRelationship(detail.getModel(), models.get(modelId))
                        .getXPathNamespaceAwareQuery();
                removeElements(parent, relsExt, xPathString);
            }
            modelId++;
        }
        if (!changed)
            return null;

        boolean lameNS = false;
        String rdfDescXPath = "/rdf:RDF/rdf:Description";
        Element rdfDescEl = FoxmlUtils.getElement(relsExt, rdfDescXPath);
        Element policyEl = null;
        if (rdfDescEl != null && rdfDescEl.getElementsByTagName("policy").getLength() > 0)
            policyEl = (Element) rdfDescEl.getElementsByTagName("policy").item(0);
        if (policyEl != null && policyEl.getAttribute(XMLNS_ATTR) != null) {
            lameNS = policyEl.getAttribute("xmlns").equals(FedoraNamespaces.KRAMERIUS_URI);
        }
        int i = 0;
        for (List<DigitalObjectDetail> data : detail.getAllItems()) {
            FedoraRelationship relationship = NamedGraphModel.getRelationship(detail.getModel(), models.get(i));
            if (data != null) {
                String relation = relationship.getStringRepresentation();
                for (DigitalObjectDetail obj : data) {

                    Element newEl = relsExt.createElement((lameNS ? "" : RELS_EXT_PART_KRAM).concat(relation));
                    if (lameNS)
                        newEl.setAttribute(XMLNS_ATTR, XMLNS_ATTR_CONTENT);
                    newEl.setAttribute(RDF_RESOURCE_ATTR, Constants.FEDORA_INFO_PREFIX + obj.getUuid());

                    rdfDescEl.appendChild(newEl);
                }
            } else {
                List<Element> removedElements = removeElements(parent, relsExt,
                        relationship.getXPathNamespaceAwareQuery());
                for (Element el : removedElements)
                    rdfDescEl.appendChild(el);
            }
            i++;
        }

    } catch (XPathExpressionException e) {
        LOGGER.warn("XPath failure", e);
    }

    String content = null;
    try {
        content = getStringFromDocument(relsExt, true);
    } catch (TransformerException e) {
        LOGGER.warn("Document transformer failure", e);
        e.printStackTrace();
    }
    return content;
}

From source file:XsltDomServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Document doc = dom.createDocument("", "parameters", null);
    Element parameters = doc.getDocumentElement();

    parameters.setAttribute("title", "XSLT DOM Servlet");
    Enumeration parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String parameterName = parameterNames.nextElement().toString();
        Element parameter = doc.createElement("parameter");
        parameters.appendChild(parameter);
        parameter.setAttribute("name", parameterName);
        parameter.appendChild(doc.createTextNode(request.getParameter(parameterName)));
    }/*from  w  w w.  j  a  va 2 s. c om*/

    DOMSource domSource = new DOMSource(doc);
    StreamResult streamResult = new StreamResult(response.getWriter());

    try {
        transformer.transform(domSource, streamResult);
    } catch (TransformerException te) {
        throw new ServletException(te);
    }
}