Example usage for org.w3c.dom Element setAttributeNS

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

Introduction

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

Prototype

public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException;

Source Link

Document

Adds a new attribute.

Usage

From source file:org.wso2.carbon.bpel.ui.bpel2svg.impl.ProcessImpl.java

/**
 * @param doc            SVG document which defines the components including shapes, gradients etc. of the process
 * @param startX         x-coordinate of the start point
 * @param startY         y-coordinate of the start point
 * @param endX           x-coordinate of the end point
 * @param endY           y-coordinate of the end point
 * @param id             previous activity id + current activity id
 * @param startIconWidth width of the startIcon
 * @param linkName       name of the link
 * @return/*  w w  w  .  jav a  2 s .  c o  m*/
 */
private Element drawLink(SVGDocument doc, int startX, int startY, int endX, int endY, int startIconWidth,
        String id, String linkName) {
    Element path = doc.createElementNS(SVGNamespace.SVG_NAMESPACE, "path");
    /*Arrows are created using  <path> : An element in svg used to create smooth, flowing lines using relatively
     few
     control points.
     A path element is defined by attribute: d. This attribute contains a series of commands for path data :
     M = move to
     L = line to
     Arrow flows will be generated according to the coordinates given
    */
    int firstBend = 20;
    if (layoutManager.isVerticalLayout()) {
        if (startY < endY) {
            path.setAttributeNS(null, "d",
                    "M " + startX + "," + startY + " L " + startX + "," + (startY + firstBend) + " L " + startX
                            + "," + (startY + firstBend) + " L " + endX + "," + (startY + firstBend) + " L "
                            + endX + "," + endY); //use constants for these propotions
        } else {
            if (startX > endX) {
                path.setAttributeNS(null, "d",
                        "M " + startX + "," + startY + " L " + startX + "," + (startY + firstBend) + " L "
                                + (startX - (startIconWidth / 2 + firstBend)) + "," + (startY + firstBend)
                                + " L " + (startX - (startIconWidth / 2 + firstBend)) + "," + (endY - firstBend)
                                + " L " + endX + "," + (endY - firstBend) + " L " + endX + "," + endY); //use constants for these propotions
            } else {
                path.setAttributeNS(null, "d",
                        "M " + startX + "," + startY + " L " + startX + "," + (startY + firstBend) + " L "
                                + (startX + (startIconWidth / 2 + firstBend)) + "," + (startY + firstBend)
                                + " L " + (startX + (startIconWidth / 2 + firstBend)) + "," + (endY - firstBend)
                                + " L " + endX + "," + (endY - firstBend) + " L " + endX + "," + endY);
            }
        }

    } else {
        path.setAttributeNS(null, "d", "M " + startX + "," + startY + " L " + ((startX + 1 * endX) / 2) + ","
                + startY + " L " + ((startX + 1 * endX) / 2) + "," + endY + " L " + endX + "," + endY);
        //use constants for these propotions
    }
    //Set the id
    path.setAttributeNS(null, "id", id);
    //Set the arrow style
    path.setAttributeNS(null, "style", getLinkArrowStyle());
    //Set the link name
    path.setAttributeNS("xlink", "title", linkName);
    return path;
}

From source file:org.wso2.carbon.bpel.ui.bpel2svg.impl.SequenceImpl.java

/**
 * @param doc SVG document which defines the components including shapes, gradients etc. of the activity
 * @return Element(represents an element in a XML/HTML document) which contains the components of the Sequence
 * composite activity//from  ww  w  . j  ava  2s .  c o  m
 */
@Override
public Element getSVGString(SVGDocument doc) {
    Element group = null;
    group = doc.createElementNS(SVGNamespace.SVG_NAMESPACE, "g");
    //Get the id of the activity
    group.setAttributeNS(null, "id", getLayerId());
    //Checks for the icon opacity
    if (isAddOpacity()) {
        group.setAttributeNS(null, "style", "opacity:" + getOpacity());
    }
    //Get the arrow flows of the subActivities inside the Sequence composite activity
    group.appendChild(getArrows(doc));
    //Get the Sequence Box where the subActivities are placed
    group.appendChild(getBoxDefinition(doc));
    //Get the start image/icon text
    group.appendChild(getStartImageText(doc));
    // Process Sub Activities
    group.appendChild(getSubActivitiesSVGString(doc));

    return group;
}

From source file:org.wso2.carbon.humantask.core.engine.runtime.xpath.XPathExpressionRuntime.java

private Element replaceElement(Element lval, Element src) {
    Document doc = lval.getOwnerDocument();
    NodeList nl = src.getChildNodes();
    for (int i = 0; i < nl.getLength(); ++i) {
        lval.appendChild(doc.importNode(nl.item(i), true));
    }//from  w ww  .j  a va  2 s  .  c om
    NamedNodeMap attrs = src.getAttributes();
    for (int i = 0; i < attrs.getLength(); ++i) {
        Attr attr = (Attr) attrs.item(i);
        if (!attr.getName().startsWith("xmlns")) {
            lval.setAttributeNodeNS((Attr) doc.importNode(attrs.item(i), true));
            // Case of qualified attribute values, we're forced to add corresponding namespace declaration manually
            int colonIdx = attr.getValue().indexOf(":");
            if (colonIdx > 0) {
                String prefix = attr.getValue().substring(0, colonIdx);
                String attrValNs = src.lookupPrefix(prefix);
                if (attrValNs != null) {
                    lval.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:" + prefix, attrValNs);
                }
            }
        }
    }

    return lval;
}

From source file:org.wyona.yanel.core.util.ConfigurationUtil.java

/**
 * Parse a configuration node into a element and add it to the document. <br/>This method may
 * call itself recusively.//from w w w  .  ja  v  a2s  . c o m
 *
 * @param conf
 *            The configuration element to parse
 * @param doc
 *            The DOM document to create elements for
 *
 * @return Returns the created element
 */
private static Element createElement(Configuration config, Document doc) throws Exception {

    Element element = doc.createElementNS(config.getNamespace(), config.getName());
    String[] attrs = config.getAttributeNames();
    for (int i = 0; i < attrs.length; i++) {
        element.setAttributeNS(config.getNamespace(), attrs[i], config.getAttribute(attrs[i]));
    }
    // TODO: Does not work for elements with mixed content (text and
    // elements)
    try {
        element.appendChild(doc.createTextNode(config.getValue()));
    } catch (Exception e) {
        log.debug("No value: " + element.getLocalName() + "  - skipped child creation");
    }
    Configuration[] children = config.getChildren();
    if (children.length > 0) {
        for (int i = 0; i < children.length; i++) {
            element.appendChild(ConfigurationUtil.createElement(children[i], doc));
        }
    }
    return element;
}

From source file:org.wyona.yanel.servlet.YanelServlet.java

/**
 * Generate response from view of resource
 * @param request TODO//from   w  w w . j  a v  a 2 s.  c  o  m
 * @param response TODO
 */
private void getContent(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // INFO: Generate "yanel" document in order to collect information in case something should go wrong or some meta information should be requested
    org.w3c.dom.Document doc = null;
    try {
        doc = getDocument(NAMESPACE, "yanel");
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }

    Element rootElement = doc.getDocumentElement();

    rootElement.setAttribute("servlet-context-real-path", servletContextRealPath);

    Element requestElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "request"));
    requestElement.setAttributeNS(NAMESPACE, "uri", request.getRequestURI());
    requestElement.setAttributeNS(NAMESPACE, "servlet-path", request.getServletPath());

    HttpSession session = request.getSession(true);
    Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session"));
    sessionElement.setAttribute("id", session.getId());
    Enumeration<?> attrNames = session.getAttributeNames();
    if (!attrNames.hasMoreElements()) {
        Element sessionNoAttributesElement = (Element) sessionElement
                .appendChild(doc.createElement("no-attributes"));
    }
    while (attrNames.hasMoreElements()) {
        String name = (String) attrNames.nextElement();
        String value = session.getAttribute(name).toString();
        Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute"));
        sessionAttributeElement.setAttribute("name", name);
        sessionAttributeElement.appendChild(doc.createTextNode(value));
    }

    String usecase = request.getParameter(YANEL_RESOURCE_USECASE);
    Resource res = null;
    TrackingInformationV1 trackInfo = null;
    long lastModified = -1;
    long size = -1;

    // START first try
    View view = null;
    try {
        Environment environment = getEnvironment(request, response);
        res = getResource(request, response);
        if (res != null) {
            if (isTrackable(res)) {
                //log.debug("Do track: " + res.getPath());
                trackInfo = new TrackingInformationV1();
                ((org.wyona.yanel.core.api.attributes.TrackableV1) res).doTrack(trackInfo);
                //} else {
                //    log.debug("Resource '" + res.getPath() + "' is not trackable.");
            }

            // START introspection generation
            if (usecase != null && usecase.equals("introspection")) {
                sendIntrospectionAsResponse(res, doc, rootElement, request, response);
                return;
            }
            // END introspection generation

            Element resourceElement = getResourceMetaData(res, doc, rootElement);
            Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view"));
            if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) {
                if (log.isDebugEnabled())
                    log.debug("Resource is viewable V1");
                viewElement.setAttributeNS(NAMESPACE, "version", "1");
                appendViewDescriptors(doc, viewElement, ((ViewableV1) res).getViewDescriptors());

                String viewId = getViewID(request);
                try {
                    view = ((ViewableV1) res).getView(request, viewId);
                } catch (org.wyona.yarep.core.NoSuchNodeException e) {
                    String message = e.getMessage();
                    log.error(message, e);
                    do404(request, response, doc, message);
                    return;
                } catch (Exception e) {
                    String message = e.getMessage();
                    log.error(message, e);
                    Element exceptionElement = (Element) rootElement
                            .appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME));
                    exceptionElement.appendChild(doc.createTextNode(message));
                    exceptionElement.setAttributeNS(NAMESPACE, "status", "500");
                    response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    setYanelOutput(request, response, doc);
                    return;
                }
            } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "2")) {
                if (log.isDebugEnabled())
                    log.debug("Resource '" + res.getPath() + "' is viewable V2");
                viewElement.setAttributeNS(NAMESPACE, "version", "2");
                appendViewDescriptors(doc, viewElement, ((ViewableV2) res).getViewDescriptors());

                if (!((ViewableV2) res).exists()) {
                    log.warn("ViewableV2 resource '" + res.getPath()
                            + "' does not seem to exist, whereas this resource might not implement exists() properly. Yanel does not generate a 404 response for backwards compatibility reasons, because there are various ViewableV2 resources which do not implement exists() properly. As a workaround one might want to use the exists() method within the getView(String) method and throw a ResourceNotFoundException instead.");
                    //do404(request, response, doc, res.getPath());
                    //return;
                }

                try {
                    size = ((ViewableV2) res).getSize();
                    Element sizeElement = (Element) resourceElement.appendChild(doc.createElement("size"));
                    sizeElement.appendChild(doc.createTextNode(String.valueOf(size)));
                } catch (ResourceNotFoundException e) {
                    log.error(e, e); // INFO: Let's be fault tolerant such that a 404 can be handled more gracefully further down
                }

                String viewId = getViewID(request);
                try {
                    String revisionName = request.getParameter(YANEL_RESOURCE_REVISION);
                    // NOTE: Check also if usecase is not roll-back, because roll-back is also using the yanel.resource.revision
                    if (revisionName != null && !isRollBack(request)) {
                        if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) {
                            view = ((VersionableV2) res).getView(viewId, revisionName);
                        } else {
                            log.warn("Resource '" + res.getPath()
                                    + "' has not VersionableV2 implemented, hence we cannot generate view for revision: "
                                    + revisionName);
                            view = ((ViewableV2) res).getView(viewId);
                        }
                    } else if (environment.getStateOfView().equals(StateOfView.LIVE)
                            && ResourceAttributeHelper.hasAttributeImplemented(res, "Workflowable", "1")
                            && WorkflowHelper.getWorkflow(res) != null) { // TODO: Instead using the WorkflowHelper the Workflowable interface should have a method to check if the resource actually has a workflow assigned, see http://lists.wyona.org/pipermail/yanel-development/2009-June/003709.html
                        // TODO: Check if resource actually exists (see the exist problem above), because even it doesn't exist, the workflowable interfaces can return something although it doesn't really make sense. For example if a resource type is workflowable, but it has no workflow associated with it, then WorkflowHelper.isLive will nevertheless return true, whereas WorkflowHelper.getLiveView will throw an exception!
                        if (!((ViewableV2) res).exists()) {
                            log.warn("No such ViewableV2 resource: " + res.getPath());
                            log.warn(
                                    "TODO: It seems like many ViewableV2 resources are not implementing exists() properly!");
                            do404(request, response, doc, res.getPath());
                            return;
                        }

                        WorkflowableV1 workflowable = (WorkflowableV1) res;
                        if (workflowable.isLive()) {
                            view = workflowable.getLiveView(viewId);
                        } else {
                            String message = "The viewable (V2) resource '" + res.getPath()
                                    + "' is WorkflowableV1, but has not been published yet.";
                            log.warn(message);
                            // TODO: Make this configurable per resource (or rather workflowable interface) or per realm?!
                            if (displayMostRecentVersion) {
                                // INFO: Because of backwards compatibility the default should display the most recent version
                                log.warn(
                                        "Instead a live/published version, the most recent version will be displayed!");
                                view = ((ViewableV2) res).getView(viewId);
                            } else {
                                log.warn("Instead a live/published version, a 404 will be displayed!");
                                // TODO: Instead a 404 one might want to show a different kind of screen
                                do404(request, response, doc, message);
                                return;
                            }
                        }
                    } else {
                        view = ((ViewableV2) res).getView(viewId);
                    }
                } catch (org.wyona.yarep.core.NoSuchNodeException e) {
                    String message = e.getMessage();
                    log.warn(message, e);
                    do404(request, response, doc, message);
                    return;
                } catch (ResourceNotFoundException e) {
                    String message = e.getMessage();
                    log.warn(message, e);
                    do404(request, response, doc, message);
                    return;
                } catch (Exception e) {
                    log.error(e, e);
                    handleException(request, response, e);
                    return;
                }
            } else { // NO Viewable interface implemented!
                String message = res.getClass().getName() + " is not viewable! (" + res.getPath() + ", "
                        + res.getRealm() + ")";
                log.error(message);
                Element noViewElement = (Element) resourceElement
                        .appendChild(doc.createElement("not-viewable"));
                noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!"));
                Element exceptionElement = (Element) rootElement
                        .appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME));
                exceptionElement.appendChild(doc.createTextNode(message));
                exceptionElement.setAttributeNS(NAMESPACE, "status", "501");
                response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED);
                setYanelOutput(request, response, doc);
                return;
            }

            if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) {
                lastModified = ((ModifiableV2) res).getLastModified();
                Element lastModifiedElement = (Element) resourceElement
                        .appendChild(doc.createElement("last-modified"));
                lastModifiedElement.appendChild(doc.createTextNode(new Date(lastModified).toString()));
            } else {
                Element noLastModifiedElement = (Element) resourceElement
                        .appendChild(doc.createElement("no-last-modified"));
            }

            // INFO: Get the revisions, but only in the meta usecase (because of performance reasons)
            if (request.getParameter(RESOURCE_META_ID_PARAM_NAME) != null) {
                appendRevisionsAndWorkflow(doc, resourceElement, res, request);
            }

            if (ResourceAttributeHelper.hasAttributeImplemented(res, "Translatable", "1")) {
                TranslatableV1 translatable = ((TranslatableV1) res);
                Element translationsElement = (Element) resourceElement
                        .appendChild(doc.createElement("translations"));
                String[] languages = translatable.getLanguages();
                for (int i = 0; i < languages.length; i++) {
                    Element translationElement = (Element) translationsElement
                            .appendChild(doc.createElement("translation"));
                    translationElement.setAttribute("language", languages[i]);
                    String path = translatable.getTranslation(languages[i]).getPath();
                    translationElement.setAttribute("path", path);
                }
            }

            if (usecase != null && usecase.equals("checkout")) {
                if (log.isDebugEnabled())
                    log.debug("Checkout data ...");

                if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) {
                    // NOTE: The code below will throw an exception if the document is checked out already by another user.
                    String userID = environment.getIdentity().getUsername();
                    VersionableV2 versionable = (VersionableV2) res;
                    if (versionable.isCheckedOut()) {
                        String checkoutUserID = versionable.getCheckoutUserID();
                        if (checkoutUserID.equals(userID)) {
                            log.warn("Resource " + res.getPath() + " is already checked out by this user: "
                                    + checkoutUserID);
                        } else {
                            if (isClientSupportingNeutron(request)) {
                                String eMessage = "Resource '" + res.getPath()
                                        + "' is already checked out by another user: " + checkoutUserID;
                                response.setContentType("application/xml");
                                response.setStatus(
                                        javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                                // TODO: Checkout date and break-lock (optional)
                                response.getWriter().print(XMLExceptionV1.getCheckoutException(eMessage,
                                        res.getPath(), checkoutUserID, null));
                                return;
                            } else {
                                throw new Exception("Resource '" + res.getPath()
                                        + "' is already checked out by another user: " + checkoutUserID);
                            }
                        }
                    } else {
                        versionable.checkout(userID);
                    }
                } else {
                    log.warn("Acquire lock has not been implemented yet ...!");
                    // acquireLock();
                }
            }
        } else {
            Element resourceIsNullElement = (Element) rootElement
                    .appendChild(doc.createElement("resource-is-null"));
        }
    } catch (org.wyona.yarep.core.NoSuchNodeException e) {
        String message = e.getMessage();
        log.warn(message, e);
        do404(request, response, doc, message);
        return;
    } catch (org.wyona.yanel.core.ResourceNotFoundException e) {
        String message = e.getMessage();
        log.warn(message, e);
        do404(request, response, doc, message);
        return;
    } catch (Exception e) {
        log.error(e, e);
        handleException(request, response, e);
        return;
    }
    // END first try

    String meta = request.getParameter(RESOURCE_META_ID_PARAM_NAME);
    if (meta != null) {
        if (meta.length() > 0) {
            if (meta.equals("annotations")) {
                log.debug("Remove everything from the page meta document except the annotations");
                cleanMetaDoc(doc);
                appendAnnotations(doc, res);
                appendTrackingInformation(doc, trackInfo);
            } else {
                log.warn("TODO: Stripping everything from page meta document but, '" + meta
                        + "' not supported!");
            }
        } else {
            log.debug("Show all meta");
            appendAnnotations(doc, res);
            appendTrackingInformation(doc, trackInfo);
        }
        response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
        setYanelOutput(request, response, doc);
        return;
    }

    if (view != null) {
        if (generateResponse(view, res, request, response, -1, doc, size, lastModified, trackInfo) != null) {
            //log.debug("Response has been generated successfully :-)");
            return;
        } else {
            log.warn("No response has been generated!");
        }
    } else {
        String message = "View is null!";
        Element exceptionElement = (Element) rootElement
                .appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME));
        exceptionElement.appendChild(doc.createTextNode(message));
    }

    response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    setYanelOutput(request, response, doc);
    return;
}

From source file:org.wyona.yanel.servlet.YanelServlet.java

/**
 * Generate a graceful 404 response/*from w  ww . j  a  v  a 2 s  .  c o m*/
 * @param doc Debug/Meta document
 */
private void do404(HttpServletRequest request, HttpServletResponse response, Document doc,
        String exceptionMessage) throws ServletException {
    log404.info("Referer: " + request.getHeader("referer"));
    log404.warn(request.getRequestURL().toString());

    // TODO: Log 404 per realm
    //org.wyona.yarep.core.Node node = realm.getRepository().getNode("/yanel-logs/404.txt");

    String message = "No such node/resource exception: " + exceptionMessage;
    log.warn(message);

    Element exceptionElement = (Element) doc.getDocumentElement()
            .appendChild(doc.createElementNS(NAMESPACE, EXCEPTION_TAG_NAME));
    exceptionElement.appendChild(doc.createTextNode(message));
    exceptionElement.setAttributeNS(NAMESPACE, "status", "404");

    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    try {
        Realm realm = yanelInstance.getMap().getRealm(request.getServletPath());
        String path = getResource(request, response).getPath();

        ResourceConfiguration rc = getGlobalResourceConfiguration("404_yanel-rc.xml", realm);
        if (generateResponseFromRTview(request, response, HttpServletResponse.SC_NOT_FOUND, rc, path)) {
            return;
        }
        log.error("404 response seems to be broken!");
        return;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return;
    }
}

From source file:org.wyona.yanel.servlet.YanelServlet.java

/**
 * Set/get meta data re resource/*  w ww.  ja v a 2 s .  c  o  m*/
 */
private Element getResourceMetaData(Resource res, Document doc, Element rootElement) {
    Element resourceElement = (Element) rootElement.appendChild(doc.createElement("resource"));
    ResourceConfiguration resConfig = res.getConfiguration();
    if (resConfig != null) {
        Element resConfigElement = (Element) resourceElement
                .appendChild(doc.createElementNS(NAMESPACE, "config"));
        resConfigElement.setAttributeNS(NAMESPACE, "rti-name", resConfig.getName());
        resConfigElement.setAttributeNS(NAMESPACE, "rti-namespace", resConfig.getNamespace());
    } else {
        Element noResConfigElement = (Element) resourceElement
                .appendChild(doc.createElementNS(NAMESPACE, "no-config"));
    }

    Element realmElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "realm"));
    realmElement.setAttributeNS(NAMESPACE, "name", res.getRealm().getName());
    realmElement.setAttributeNS(NAMESPACE, "rid", res.getRealm().getID());
    realmElement.setAttributeNS(NAMESPACE, "prefix", res.getRealm().getMountPoint());
    Element identityManagerElement = (Element) realmElement
            .appendChild(doc.createElementNS(NAMESPACE, "identity-manager"));
    Element userManagerElement = (Element) identityManagerElement
            .appendChild(doc.createElementNS(NAMESPACE, "user-manager"));
    return resourceElement;
}

From source file:org.wyona.yanel.servlet.YanelServlet.java

/**
 * Append view descriptors to meta//from ww  w .  j  av  a2s.  c om
 */
private void appendViewDescriptors(Document doc, Element viewElement, ViewDescriptor[] vd) {
    if (vd != null) {
        for (int i = 0; i < vd.length; i++) {
            Element descriptorElement = (Element) viewElement.appendChild(doc.createElement("descriptor"));
            if (vd[i].getMimeType() != null) {
                descriptorElement.appendChild(doc.createTextNode(vd[i].getMimeType()));
            }
            descriptorElement.setAttributeNS(NAMESPACE, "id", vd[i].getId());
        }
    } else {
        viewElement.appendChild(doc.createTextNode("No View Descriptors!"));
    }
}

From source file:org.xwiki.xml.Sax2Dom.java

@Override
public void startElement(String namespace, String localName, String qName, Attributes atts) {
    final Element element = this.document.createElementNS(namespace, qName);

    // Add namespace declarations first
    if (this.namespaceDecls != null) {
        final int nDecls = this.namespaceDecls.size();
        for (int i = 0; i < nDecls; i += 2) {
            String prefix = this.namespaceDecls.get(i);
            String uri = this.namespaceDecls.get(i + 1);

            if (StringUtils.isEmpty(prefix)) {
                element.setAttributeNS(XMLNS_URI, XMLNS_PREFIX, uri);
            } else {
                element.setAttributeNS(XMLNS_URI, XMLNS_STRING + prefix, uri);
            }/*from w w  w .  j av a 2  s .c  om*/
        }
        this.namespaceDecls.clear();
    }

    // Add attributes to element
    final int nattrs = atts.getLength();
    for (int i = 0; i < nattrs; i++) {
        if (atts.getLocalName(i) == null) {
            element.setAttribute(atts.getQName(i), atts.getValue(i));
        } else {
            element.setAttributeNS(atts.getURI(i), atts.getQName(i), atts.getValue(i));
        }
    }

    // Append this new node onto current stack node
    this.nodes.peek().appendChild(element);

    // Push this node onto stack
    this.nodes.push(element);
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

@Override
public AppData normalize(List<QName> namespaces, String appData) {
    try {/*from   w  ww.ja v a2  s  .c  om*/
        final Document doc = createDocumentFromFragment(namespaces, appData);
        NodeList childNodes = doc.getDocumentElement().getChildNodes();
        Element body = (Element) childNodes.item(0);
        String _id;
        Attr id = body.getAttributeNodeNS(WSU, "Id");
        if (id == null) {
            _id = "AppData";
            body.setAttributeNS(WSU, "Id", _id);
        } else {
            _id = id.getValue();
        }
        final Transforms transforms = new Transforms(doc);
        //   ? ds:Signature, ?   
        // Element signature = doc.createElementNS(Constants.SignatureSpecNS, Constants._TAG_SIGNATURE);
        // signature = (Element) body.insertBefore(signature, body.getFirstChild());
        // transforms.setElement(signature, _id);
        // transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
        ByteArrayOutputStream c14nStream = new ByteArrayOutputStream();
        MessageDigestAlgorithm mda = MessageDigestAlgorithm.getInstance(doc,
                MessageDigestAlgorithm.ALGO_ID_DIGEST_GOST3411);
        mda.reset();
        XMLSignatureInput output = transforms.performTransforms(new XMLSignatureInput(body), c14nStream);
        DigesterOutputStream digesterStream = new DigesterOutputStream(mda);
        output.updateOutputStream(digesterStream);
        return new AppData(c14nStream.toByteArray(), digesterStream.getDigestValue());
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (CanonicalizationException e) {
        throw new RuntimeException(e);
    } catch (XMLSecurityException e) {
        throw new RuntimeException(e);
    }
}