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:eu.europa.esig.dss.xades.signature.XAdESSignatureBuilder.java

static void createTransform(final Document document, final DSSTransform dssTransform,
        final Element transformDom) {

    transformDom.setAttribute(ALGORITHM, dssTransform.getAlgorithm());

    final String elementName = dssTransform.getElementName();
    final String textContent = dssTransform.getTextContent();
    if (StringUtils.isNotBlank(elementName)) {

        final String namespace = dssTransform.getNamespace();
        DSSXMLUtils.addTextElement(document, transformDom, namespace, elementName, textContent);
    } else if (StringUtils.isNotBlank(textContent)) {

        final Document transformContentDoc = DSSXMLUtils.buildDOM(textContent);
        final Element contextDocumentElement = transformContentDoc.getDocumentElement();
        document.adoptNode(contextDocumentElement);
        transformDom.appendChild(contextDocumentElement);
    }/*from   w  ww .  j  a va2 s  . c  om*/
}

From source file:com.centeractive.ws.legacy.SchemaUtils.java

/**
 * Returns a map mapping urls to corresponding XmlSchema XmlObjects for the specified wsdlUrl
 *//*from   w w w.  j av  a 2 s  .c o  m*/
public static void getSchemas(String wsdlUrl, Map<String, XmlObject> existing, SchemaLoader loader,
        String tns) {
    if (existing.containsKey(wsdlUrl)) {
        return;
    }

    log.debug("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:cross.applicationContext.ReflectionApplicationContextGenerator.java

/**
 * Creates an xml element using the given document for element creation.
 *
 * @param generator/*from  w ww.j  av a  2 s. c  o  m*/
 * @param document the document use for element creation
 * @param beanDescriptor
 * @return the modified element
 */
public static Element createElement(ReflectionApplicationContextGenerator generator, Document document,
        BeanDescriptor beanDescriptor) {
    Class<?> javaClass = beanDescriptor.clazz;
    System.out.println("Building bean element for " + javaClass.getName());
    //get the name of the class
    String className = javaClass.getSimpleName();

    //get the name of the package
    String packageName = javaClass.getPackage().getName();

    //create <bean /> element
    Element beanElement = document.createElement("bean");
    String classNameLower = toLowerCaseName(className);
    beanElement.setAttribute("id", classNameLower);
    String classAttr = (packageName == null) ? className : packageName + "." + className;
    beanElement.setAttribute("class", classAttr);
    beanElement.setAttribute("scope", beanDescriptor.scope);
    //constructors are not supported
    //get all the class' properties from the public fields and setter methods.

    for (Method method : javaClass.getMethods()) {
        checkMutableProperties(method, javaClass, beanDescriptor.obj, beanDescriptor.properties);
    }
    //sort by name
    Collections.sort(beanDescriptor.properties, new Comparator<ObjectProperty>() {
        @Override
        public int compare(ObjectProperty t, ObjectProperty t1) {
            return t.name.compareTo(t1.name);
        }
    });
    List<String> blackList = Arrays.asList("workflow", "progress", "cvResolver");
    //add all properties as <property /> elements
    for (ObjectProperty p : beanDescriptor.properties) {
        if (!blackList.contains(p.name)) {
            Element propertyElement = document.createElement("property");
            propertyElement.setAttribute("name", p.name);
            Comment propertyCommentElement = document
                    .createComment(AnnotationInspector.getDescriptionFor(javaClass, p.name));
            boolean append = true;
            if (p.type.startsWith("java.lang.")) {
                String shortType = p.type.substring("java.lang.".length());
                if (primitives.contains(shortType) || wrappers.contains(shortType)) {
                    propertyElement.setAttribute("value", p.value);
                }
            } else if (primitives.contains(p.type) || wrappers.contains(p.type)) {
                propertyElement.setAttribute("value", p.value);
            } else if ("Array".equals(p.type) || "List".equals(p.type) || "java.util.List".equals(p.type)) {
                Element listElement = document.createElement("list");
                String genericType = p.genericType;
                propertyElement.appendChild(listElement);
            } else if ("Set".equals(p.type) || "java.util.Set".equals(p.type)) {
                Element listElement = document.createElement("set");
                propertyElement.appendChild(listElement);
            } else if ("Map".equals(p.type) || "java.util.Map".equals(p.type)) {
                Element listElement = document.createElement("map");
                propertyElement.appendChild(listElement);
            } else if ("Properties".equals(p.type) || "java.util.Properties".equals(p.type)) {
                Element listElement = document.createElement("props");
                propertyElement.appendChild(listElement);
            } else {
                try {
                    //                    System.err.println("Skipping ref!");
                    Set<BeanDefinition> beanDefinitions = getImplementationsOf(Class.forName(p.type), "cross",
                            "maltcms", "net.sf.maltcms");
                    BeanDefinition first = null;
                    for (BeanDefinition bd : beanDefinitions) {
                        generator.addBean(bd.getBeanClassName());
                        if (first == null) {
                            first = bd;
                        }
                    }
                    if (first != null) {
                        String simpleName = first.getBeanClassName()
                                .substring(first.getBeanClassName().lastIndexOf(".") + 1);
                        propertyElement.setAttribute("ref",
                                generator.classToElement.get(toLowerCaseName(simpleName)).id);
                    }
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE,
                            null, ex);
                }
                append = true;
                //                    try {
                //                        generator.addBean(p.type);
                //                        Class<?> c = Class.forName(p.type);
                //                        List<Object> objects = generator.classToObject.get(c);
                //                        if (objects != null && !objects.isEmpty()) {
                //                            propertyElement.setAttribute("ref", generator.buildBeanElement(objects.get(0)).id);
                //                        } else {
                //                            append = false;
                //                        }
                //                    } catch (ClassNotFoundException ex) {
                //                        Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE, null, ex);
                //                    }

            }
            if (append) {
                beanElement.appendChild(propertyCommentElement);
                beanElement.appendChild(propertyElement);
            } else {
                beanElement.appendChild(propertyCommentElement);
                Comment comment = document.createComment("<property name=\"" + p.name + "\" ref=\"\"/>");
                beanElement.appendChild(comment);
            }
        }
    }
    return beanElement;
}

From source file:com.msopentech.odatajclient.engine.data.ODataBinder.java

private static Element newEntryContent() {
    Element properties = null;
    try {//w w w. ja v  a2  s. co  m
        final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document doc = builder.newDocument();
        properties = doc.createElement(ODataConstants.ELEM_PROPERTIES);
        properties.setAttribute(ODataConstants.XMLNS_METADATA, ODataConstants.NS_METADATA);
        properties.setAttribute(ODataConstants.XMLNS_DATASERVICES, ODataConstants.NS_DATASERVICES);
        properties.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
        properties.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
    } catch (ParserConfigurationException e) {
        LOG.error("Failure building entry content", e);
    }

    return properties;
}

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

public static Element createRequestElement(RequestElementDTO requestElementDTO, Document doc)
        throws PolicyBuilderException {

    Element requestElement = doc.createElement(PolicyConstants.Request.REQUEST_ELEMENT);
    requestElement.setAttribute("xmlns", PolicyConstants.Request.REQ_RES_CONTEXT_XACML3);
    requestElement.setAttribute(PolicyConstants.Request.RETURN_POLICY_LIST,
            Boolean.toString(requestElementDTO.isReturnPolicyIdList()));
    requestElement.setAttribute(PolicyConstants.Request.COMBINED_DECISION,
            Boolean.toString(requestElementDTO.isCombinedDecision()));

    List<AttributesElementDTO> attributesElementDTOs = requestElementDTO.getAttributesElementDTOs();
    if (attributesElementDTOs != null && attributesElementDTOs.size() > 0) {
        for (AttributesElementDTO dto : attributesElementDTOs) {
            requestElement.appendChild(createAttributesElement(dto, doc));
        }//from   ww  w.  j ava  2  s . c om
    }
    return requestElement;
}

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

/**
 * This creates XML representation of Attributes Element using AttributesElementDTO object
 *
 * @param elementDTO  AttributesElementDTO
 * @param doc Document/*from   w ww  .  j  ava2  s . c  o  m*/
 * @return DOM element
 */
public static Element createAttributesElement(AttributesElementDTO elementDTO, Document doc) {

    Element attributesElement = doc.createElement(PolicyConstants.ATTRIBUTES);

    attributesElement.setAttribute(PolicyConstants.CATEGORY, elementDTO.getCategory());

    List<AttributeElementDTO> attributeElementDTOs = elementDTO.getAttributeElementDTOs();
    if (attributeElementDTOs != null && attributeElementDTOs.size() > 0) {
        for (AttributeElementDTO attributeElementDTO : attributeElementDTOs) {
            Element attributeElement = doc.createElement(PolicyConstants.ATTRIBUTE);
            attributeElement.setAttribute(PolicyConstants.ATTRIBUTE_ID, attributeElementDTO.getAttributeId());
            attributeElement.setAttribute(PolicyConstants.INCLUDE_RESULT,
                    Boolean.toString(attributeElementDTO.isIncludeInResult()));

            if (attributeElementDTO.getIssuer() != null
                    && attributeElementDTO.getIssuer().trim().length() > 0) {
                attributeElement.setAttribute(PolicyConstants.ISSUER, attributeElementDTO.getIssuer());
            }

            List<String> values = attributeElementDTO.getAttributeValues();
            for (String value : values) {
                Element attributeValueElement = doc.createElement(PolicyConstants.ATTRIBUTE_VALUE);
                attributeValueElement.setAttribute(PolicyConstants.DATA_TYPE,
                        attributeElementDTO.getDataType());
                attributeValueElement.setTextContent(value.trim());
                attributeElement.appendChild(attributeValueElement);
            }
            attributesElement.appendChild(attributeElement);
        }
    }
    return attributesElement;
}

From source file:com.netspective.sparx.form.DialogContext.java

static public void exportParamToXml(Element parent, String name, String[] values) {
    Document doc = parent.getOwnerDocument();
    Element fieldElem = doc.createElement("request-param");
    fieldElem.setAttribute("name", name);
    if (values != null && values.length > 1) {
        fieldElem.setAttribute("value-type", "strings");
        Element valuesElem = doc.createElement("values");
        for (int i = 0; i < values.length; i++) {
            Element valueElem = doc.createElement("value");
            valueElem.appendChild(doc.createTextNode(values[i]));
            valuesElem.appendChild(valueElem);
        }// ww w .  j a v  a  2  s  .  com
        fieldElem.appendChild(valuesElem);
        parent.appendChild(fieldElem);
    } else if (values != null) {
        fieldElem.setAttribute("value-type", "string");
        Element valueElem = doc.createElement("value");
        valueElem.appendChild(doc.createTextNode(values[0]));
        fieldElem.appendChild(valueElem);
        parent.appendChild(fieldElem);
    }
}

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

/**
 * This creates XML representation of condition element using ConditionElementDT0 object
 *
 * @param conditionElementDT0 ConditionElementDT0
 * @param doc Document/*from w w w  .j av  a2  s.  c om*/
 * @return DOM element
 * @throws PolicyBuilderException throws
 */
public static Element createConditionElement(ConditionElementDT0 conditionElementDT0, Document doc)
        throws PolicyBuilderException {

    Element conditionElement = doc.createElement(PolicyConstants.CONDITION_ELEMENT);

    if (conditionElementDT0.getApplyElement() != null) {
        conditionElement.appendChild(createApplyElement(conditionElementDT0.getApplyElement(), doc));

    } else if (conditionElementDT0.getAttributeValueElementDTO() != null) {
        Element attributeValueElement = createAttributeValueElement(
                conditionElementDT0.getAttributeValueElementDTO(), doc);
        conditionElement.appendChild(attributeValueElement);

    } else if (conditionElementDT0.getAttributeDesignator() != null) {
        AttributeDesignatorDTO attributeDesignatorDTO = conditionElementDT0.getAttributeDesignator();
        conditionElement.appendChild(createAttributeDesignatorElement(attributeDesignatorDTO, doc));

    } else if (conditionElementDT0.getFunctionFunctionId() != null) {
        Element functionElement = doc.createElement(PolicyConstants.FUNCTION_ELEMENT);
        functionElement.setAttribute(PolicyConstants.FUNCTION_ID, conditionElementDT0.getFunctionFunctionId());
        conditionElement.appendChild(functionElement);
    } else if (conditionElementDT0.getVariableId() != null) {
        Element variableReferenceElement = doc.createElement(PolicyConstants.VARIABLE_REFERENCE);
        variableReferenceElement.setAttribute(PolicyConstants.VARIABLE_ID, conditionElementDT0.getVariableId());
        conditionElement.appendChild(variableReferenceElement);
    }

    return conditionElement;

}

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

/**
 * This creates XML representation of advice element using List of ObligationElementDTO object
 *
 * @param obligationElementDTOs List of ObligationElementDTO
 * @param doc Document//w ww  .  j  a va 2s .c om
 * @return DOM element
 * @throws PolicyBuilderException throws
 */
public static Element createAdvicesElement(List<ObligationElementDTO> obligationElementDTOs, Document doc)
        throws PolicyBuilderException {

    Element adviceExpressions = null;

    if (obligationElementDTOs != null && obligationElementDTOs.size() > 0) {

        for (ObligationElementDTO dto : obligationElementDTOs) {
            String id = dto.getId();
            String effect = dto.getEffect();

            if (id != null && id.trim().length() > 0 && effect != null) {
                if (adviceExpressions == null) {
                    adviceExpressions = doc.createElement(PolicyConstants.ADVICE_EXPRESSIONS);
                }

                Element adviceExpression = doc.createElement(PolicyConstants.ADVICE_EXPRESSION);
                adviceExpression.setAttribute(PolicyConstants.ADVICE_ID, id);
                adviceExpression.setAttribute(PolicyConstants.ADVICE_EFFECT, effect);
                List<AttributeAssignmentElementDTO> elementDTOs = dto.getAssignmentElementDTOs();
                if (elementDTOs != null) {
                    for (AttributeAssignmentElementDTO elementDTO : elementDTOs) {
                        Element element = createAttributeAssignmentElement(elementDTO, doc);
                        if (element != null) {
                            adviceExpression.appendChild(element);
                        }
                    }
                }
                adviceExpressions.appendChild(adviceExpression);
            }
        }
    }

    return adviceExpressions;
}

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

/**
 * This creates XML representation of assignment element using AttributeAssignmentElementDTO object
 *
 * @param assignmentElementDTO AttributeAssignmentElementDTO
 * @param doc Document/*from w ww  . ja v a 2 s .c o m*/
 * @return DOM element
 * @throws PolicyBuilderException throws
 */
public static Element createAttributeAssignmentElement(AttributeAssignmentElementDTO assignmentElementDTO,
        Document doc) throws PolicyBuilderException {

    String attributeId = assignmentElementDTO.getAttributeId();

    if (attributeId != null && attributeId.trim().length() > 0) {

        String category = assignmentElementDTO.getCategory();
        String issuer = assignmentElementDTO.getIssuer();
        ApplyElementDTO applyElementDTO = assignmentElementDTO.getApplyElementDTO();
        AttributeDesignatorDTO designatorDTO = assignmentElementDTO.getDesignatorDTO();
        AttributeValueElementDTO valueElementDTO = assignmentElementDTO.getValueElementDTO();

        Element attributeAssignment = doc.createElement(PolicyConstants.ATTRIBUTE_ASSIGNMENT);
        attributeAssignment.setAttribute(PolicyConstants.ATTRIBUTE_ID, attributeId);
        if (category != null && category.trim().length() > 0) {
            attributeAssignment.setAttribute(PolicyConstants.CATEGORY, category);
        }

        if (issuer != null && issuer.trim().length() > 0) {
            attributeAssignment.setAttribute(PolicyConstants.ISSUER, issuer);
        }

        if (applyElementDTO != null) {
            attributeAssignment.appendChild(createApplyElement(applyElementDTO, doc));
        }

        if (designatorDTO != null) {
            attributeAssignment.appendChild(createAttributeDesignatorElement(designatorDTO, doc));
        }

        if (valueElementDTO != null) {
            attributeAssignment.appendChild(createAttributeValueElement(valueElementDTO, doc));
        }

        return attributeAssignment;
    }

    return null;
}