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:com.enonic.vertical.adminweb.ContentObjectHandlerServlet.java

private void addStyleSheet(Element contentobjectElem, String elemName, ResourceKey styleSheetKey)
        throws VerticalAdminException {

    ResourceFile resource = resourceService.getResourceFile(styleSheetKey);
    if (resource == null) {
        throw new StylesheetNotFoundException(styleSheetKey);
    }/*from   w ww.j  a  v  a 2s.c  o  m*/
    Document styleSheetDoc;
    try {
        styleSheetDoc = resource.getDataAsXml().getAsDOMDocument();
    } catch (XMLException e) {
        throw new InvalidStylesheetException(styleSheetKey, e);
    }

    Element styleSheetRoot = styleSheetDoc.getDocumentElement();
    String attr = styleSheetRoot.getAttribute("xmlns:xsl");
    styleSheetRoot.removeAttribute("xmlns:xsl");
    styleSheetRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", attr);
    Document doc = contentobjectElem.getOwnerDocument();
    Element elem = XMLTool.createElement(doc, contentobjectElem, elemName);
    elem.appendChild(doc.importNode(styleSheetRoot, true));
}

From source file:it.cnr.icar.eric.common.security.wss4j.WSS4JSignatureSAML.java

/**
 * Initialize a WSSec SAML Signature.//from  ww w  .j  a v  a2  s  .c o  m
 * 
 * The method sets up and initializes a WSSec SAML Signature structure after
 * the relevant information was set. After setup of the references to
 * elements to sign may be added. After all references are added they can be
 * signed.
 * 
 * This method does not add the Signature element to the security header.
 * See <code>prependSignatureElementToHeader()</code> method.
 * 
 * @param doc
 *            The SOAP envelope as <code>Document</code>
 * @param uCrypto
 *            The user's Crypto instance
 * @param assertion
 *            the complete SAML assertion
 * @param iCrypto
 *            An instance of the Crypto API to handle keystore SAML token
 *            issuer and to generate certificates
 * @param iKeyName
 *            Private key to use in case of "sender-Vouches"
 * @param iKeyPW
 *            Password for issuer private key
 * @param secHeader
 *            The Security header
 * @throws WSSecurityException
 */
public void prepare(Document doc, Crypto uCrypto, AssertionWrapper assertion, Crypto iCrypto, String iKeyName,
        String iKeyPW, WSSecHeader secHeader) throws WSSecurityException {

    if (doDebug) {
        log.debug("Beginning ST signing...");
    }

    userCrypto = uCrypto;
    issuerCrypto = iCrypto;
    document = doc;
    issuerKeyName = iKeyName;
    issuerKeyPW = iKeyPW;

    samlToken = assertion.toDOM(doc);

    //
    // Get some information about the SAML token content. This controls how
    // to deal with the whole stuff. First get the Authentication statement
    // (includes Subject), then get the _first_ confirmation method only
    // thats if "senderVouches" is true.
    //
    String confirmMethod = null;
    List<String> methods = assertion.getConfirmationMethods();
    if (methods != null && methods.size() > 0) {
        confirmMethod = methods.get(0);
    }
    if (OpenSAMLUtil.isMethodSenderVouches(confirmMethod)) {
        senderVouches = true;
    }
    //
    // Gather some info about the document to process and store it for
    // retrieval
    //
    wsDocInfo = new WSDocInfo(doc);

    X509Certificate[] certs = null;
    PublicKey publicKey = null;

    if (senderVouches) {
        CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
        cryptoType.setAlias(issuerKeyName);
        certs = issuerCrypto.getX509Certificates(cryptoType);
        wsDocInfo.setCrypto(issuerCrypto);
    }
    //
    // in case of key holder: - get the user's certificate that _must_ be
    // included in the SAML token. To ensure the cert integrity the SAML
    // token must be signed (by the issuer).
    //
    else {
        if (userCrypto == null || !assertion.isSigned()) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLsecurity",
                    new Object[] { "for SAML Signature (Key Holder)" });
        }
        if (secretKey == null) {
            RequestData data = new RequestData();
            data.setSigCrypto(userCrypto);
            data.setWssConfig(getWsConfig());
            SAMLKeyInfo samlKeyInfo = SAMLUtil.getCredentialFromSubject(assertion, data, wsDocInfo,
                    getWsConfig().isWsiBSPCompliant());
            publicKey = samlKeyInfo.getPublicKey();
            certs = samlKeyInfo.getCerts();
            wsDocInfo.setCrypto(userCrypto);
        }
    }
    if ((certs == null || certs.length == 0 || certs[0] == null) && publicKey == null && secretKey == null) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "noCertsFound",
                new Object[] { "SAML signature" });
    }

    if (sigAlgo == null) {
        PublicKey key = null;
        if (certs != null && certs[0] != null) {
            key = certs[0].getPublicKey();
        } else if (publicKey != null) {
            key = publicKey;
        }

        String pubKeyAlgo = key.getAlgorithm();
        log.debug("automatic sig algo detection: " + pubKeyAlgo);
        if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
            sigAlgo = WSConstants.DSA;
        } else if (pubKeyAlgo.equalsIgnoreCase("RSA")) {
            sigAlgo = WSConstants.RSA;
        } else {
            throw new WSSecurityException(WSSecurityException.FAILURE, "unknownSignatureAlgorithm",
                    new Object[] { pubKeyAlgo });
        }
    }
    sig = null;

    try {
        C14NMethodParameterSpec c14nSpec = null;
        if (getWsConfig().isWsiBSPCompliant() && canonAlgo.equals(WSConstants.C14N_EXCL_OMIT_COMMENTS)) {
            List<String> prefixes = getInclusivePrefixes(secHeader.getSecurityHeader(), false);
            c14nSpec = new ExcC14NParameterSpec(prefixes);
        }

        c14nMethod = signatureFactory.newCanonicalizationMethod(canonAlgo, c14nSpec);
    } catch (Exception ex) {
        log.error("", ex);
        throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex);
    }

    keyInfoUri = getWsConfig().getIdAllocator().createSecureId("KeyId-", keyInfo);
    secRef = new SecurityTokenReference(doc);
    strUri = getWsConfig().getIdAllocator().createSecureId("STRId-", secRef);
    secRef.setID(strUri);

    if (certs != null && certs.length != 0) {

        // __MOD__ 2012-01-15

        if (certUri == null)
            certUri = getWsConfig().getIdAllocator().createSecureId("CertId-", certs[0]);
    }

    //
    // If the sender vouches, then we must sign the SAML token _and_ at
    // least one part of the message (usually the SOAP body). To do so we
    // need to - put in a reference to the SAML token. Thus we create a STR
    // and insert it into the wsse:Security header - set a reference of the
    // created STR to the signature and use STR Transform during the
    // signature
    //
    try {
        if (senderVouches) {
            secRefSaml = new SecurityTokenReference(doc);
            secRefID = getWsConfig().getIdAllocator().createSecureId("STRSAMLId-", secRefSaml);
            secRefSaml.setID(secRefID);

            if (useDirectReferenceToAssertion) {
                Reference ref = new Reference(doc);
                ref.setURI("#" + assertion.getId());
                if (assertion.getSaml1() != null) {
                    ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
                    secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
                } else if (assertion.getSaml2() != null) {
                    secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
                }
                secRefSaml.setReference(ref);
            } else {
                Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier");
                String valueType = null;
                if (assertion.getSaml1() != null) {
                    valueType = WSConstants.WSS_SAML_KI_VALUE_TYPE;
                    secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
                } else if (assertion.getSaml2() != null) {
                    valueType = WSConstants.WSS_SAML2_KI_VALUE_TYPE;
                    secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
                }
                keyId.setAttributeNS(null, "ValueType", valueType);
                keyId.appendChild(doc.createTextNode(assertion.getId()));
                Element elem = secRefSaml.getElement();
                elem.appendChild(keyId);
            }
            wsDocInfo.addTokenElement(secRefSaml.getElement(), false);
        }
    } catch (Exception ex) {
        throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex);
    }

    if (senderVouches) {
        switch (keyIdentifierType) {
        case WSConstants.BST_DIRECT_REFERENCE:
            Reference ref = new Reference(doc);
            ref.setURI("#" + certUri);
            bstToken = new X509Security(doc);
            ((X509Security) bstToken).setX509Certificate(certs[0]);
            bstToken.setID(certUri);
            wsDocInfo.addTokenElement(bstToken.getElement(), false);
            ref.setValueType(bstToken.getValueType());
            secRef.setReference(ref);
            break;

        case WSConstants.X509_KEY_IDENTIFIER:
            secRef.setKeyIdentifier(certs[0]);
            break;

        case WSConstants.SKI_KEY_IDENTIFIER:
            secRef.setKeyIdentifierSKI(certs[0], iCrypto != null ? iCrypto : uCrypto);
            break;

        case WSConstants.THUMBPRINT_IDENTIFIER:
            secRef.setKeyIdentifierThumb(certs[0]);
            break;

        case WSConstants.ISSUER_SERIAL:
            final String issuer = certs[0].getIssuerDN().getName();
            final java.math.BigInteger serialNumber = certs[0].getSerialNumber();
            final DOMX509IssuerSerial domIssuerSerial = new DOMX509IssuerSerial(document, issuer, serialNumber);
            final DOMX509Data domX509Data = new DOMX509Data(document, domIssuerSerial);
            secRef.setX509Data(domX509Data);
            break;

        default:
            throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId", new Object[] {});
        }
    } else if (useDirectReferenceToAssertion) {
        Reference ref = new Reference(doc);
        ref.setURI("#" + assertion.getId());
        if (assertion.getSaml1() != null) {
            ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE);
            secRef.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
        } else if (assertion.getSaml2() != null) {
            secRef.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
        }
        secRef.setReference(ref);
    } else {
        Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier");
        String valueType = null;
        if (assertion.getSaml1() != null) {
            valueType = WSConstants.WSS_SAML_KI_VALUE_TYPE;
            secRef.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
        } else if (assertion.getSaml2() != null) {
            valueType = WSConstants.WSS_SAML2_KI_VALUE_TYPE;
            secRef.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
        }
        keyId.setAttributeNS(null, "ValueType", valueType);
        keyId.appendChild(doc.createTextNode(assertion.getId()));
        Element elem = secRef.getElement();
        elem.appendChild(keyId);
    }
    XMLStructure structure = new DOMStructure(secRef.getElement());
    wsDocInfo.addTokenElement(secRef.getElement(), false);

    keyInfo = keyInfoFactory.newKeyInfo(java.util.Collections.singletonList(structure), keyInfoUri);

    wsDocInfo.addTokenElement(samlToken, false);
}

From source file:be.fedict.eid.tsl.TrustServiceList.java

private Node getSignatureNode() {
    Element nsElement = this.tslDocument.createElement("ns");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", XMLSignature.XMLNS);
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tsl", "http://uri.etsi.org/02231/v2#");

    Node signatureNode;//w  w  w . j a v a 2  s  .co  m
    try {
        signatureNode = XPathAPI.selectSingleNode(this.tslDocument, "tsl:TrustServiceStatusList/ds:Signature",
                nsElement);
    } catch (TransformerException e) {
        throw new RuntimeException("XPath error: " + e.getMessage(), e);
    }
    return signatureNode;
}

From source file:com.enonic.vertical.adminweb.ContentObjectHandlerServlet.java

public void handlerForm(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        AdminService admin, ExtendedMap formItems) throws VerticalAdminException {

    User user = securityService.getLoggedInAdminConsoleUser();
    boolean createContentObject = false;
    String xmlData = null;/*from   w  w  w  .ja v  a  2 s.c  o m*/
    Document doc;
    String queryParam = "";
    String script = "";

    int menuKey = formItems.getInt("menukey");

    if (request.getParameter("key") == null || request.getParameter("key").equals("")) {
        // Blank form, make dummy document
        doc = XMLTool.createDocument("contentobjects");
        createContentObject = true;
    } else {
        int cobKey = Integer.parseInt(request.getParameter("key"));

        xmlData = admin.getContentObject(cobKey);

        doc = XMLTool.domparse(xmlData);

        NodeList coNodes = doc.getElementsByTagName("contentobject");
        Element contentobject = (Element) coNodes.item(0);
        String contentKeyStr = contentobject.getAttribute("contentkey");
        if (contentKeyStr != null && contentKeyStr.length() > 0) {
            int contentKey = Integer.parseInt(contentKeyStr);

            String contentXML = admin.getContent(user, contentKey, 0, 0, 0);
            Document contentDoc = XMLTool.domparse(contentXML);
            NodeList contentNodes = contentDoc.getElementsByTagName("content");
            Element content = (Element) contentNodes.item(0);
            content = (Element) doc.importNode(content, true);
            contentobject.appendChild(content);
        }

        String menuItemsXML;
        menuItemsXML = admin.getMenuItemsByContentObject(user, cobKey);
        Document menuItemsDoc = XMLTool.domparse(menuItemsXML);
        contentobject.appendChild(doc.importNode(menuItemsDoc.getDocumentElement(), true));

        // Henter ut pagetemplates/frameworks som bruker dette contentobject
        String pageTemplatesXML = admin.getPageTemplatesByContentObject(cobKey);
        Document pageTemplatesDoc = XMLTool.domparse(pageTemplatesXML);
        contentobject.appendChild(doc.importNode(pageTemplatesDoc.getDocumentElement(), true));

        Element objectstylesheetElem = XMLTool.getElement(contentobject, "objectstylesheet");
        ResourceKey objectStyleSheetKey = new ResourceKey(objectstylesheetElem.getAttribute("key"));

        ResourceFile res = resourceService.getResourceFile(objectStyleSheetKey);
        objectstylesheetElem.setAttribute("exist", res == null ? "false" : "true");

        if (res != null) {
            try {
                Document styleSheetDoc = res.getDataAsXml().getAsDOMDocument();
                objectstylesheetElem.setAttribute("valid", "true");

                Element styleSheetRoot = styleSheetDoc.getDocumentElement();
                String attr = styleSheetRoot.getAttribute("xmlns:xsl");
                styleSheetRoot.removeAttribute("xmlns:xsl");
                styleSheetRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", attr);
                Element elem = XMLTool.createElement(doc, contentobject, "objectstylesheet_xsl");
                elem.appendChild(doc.importNode(styleSheetRoot, true));
            } catch (XMLException e) {
                objectstylesheetElem.setAttribute("valid", "false");
            }
        }

        Element borderstylesheetElem = XMLTool.getElement(contentobject, "borderstylesheet");
        if (borderstylesheetElem != null) {
            ResourceKey borderStyleSheetKey = ResourceKey.parse(borderstylesheetElem.getAttribute("key"));
            if (borderStyleSheetKey != null) {
                res = resourceService.getResourceFile(borderStyleSheetKey);
                borderstylesheetElem.setAttribute("exist", res == null ? "false" : "true");
                if (res != null) {
                    try {
                        Document borderStyleSheetDoc = res.getDataAsXml().getAsDOMDocument();
                        borderstylesheetElem.setAttribute("valid", "true");

                        Element styleSheetRoot = borderStyleSheetDoc.getDocumentElement();
                        String attr = styleSheetRoot.getAttribute("xmlns:xsl");
                        styleSheetRoot.removeAttribute("xmlns:xsl");
                        styleSheetRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", attr);
                        Element elem = XMLTool.createElement(doc, contentobject, "borderstylesheet_xsl");
                        elem.appendChild(doc.importNode(styleSheetRoot, true));
                    } catch (XMLException e) {
                        borderstylesheetElem.setAttribute("valid", "false");
                    }
                }
            }
        }
    }

    if (xmlData != null) {
        Map subelems = XMLTool.filterElements(doc.getDocumentElement().getChildNodes());
        if (subelems.get("contentobject") != null) {
            Element tempElem = (Element) subelems.get("contentobject");
            Map contentobjectmap = XMLTool.filterElements(tempElem.getChildNodes());

            Element contentobjectdata = (Element) contentobjectmap.get("contentobjectdata");
            Map queryparammap = XMLTool.filterElements(contentobjectdata.getChildNodes());
            tempElem = (Element) queryparammap.get("datasources");

            Document queryParamDoc = XMLTool.createDocument();
            tempElem = (Element) queryParamDoc.importNode(tempElem, true);
            queryParamDoc.appendChild(tempElem);

            StringWriter sw = new StringWriter();
            queryParamDoc.normalize();
            XMLTool.printDocument(sw, queryParamDoc, 0);
            queryParam = sw.toString();

            // Find the script data
            Element scriptElem = (Element) queryparammap.get("script");
            if (scriptElem != null) {
                script = XMLTool.getElementText(scriptElem);
            }

            Element[] paramElems = XMLTool.getElements(contentobjectdata, "stylesheetparam");
            for (Element paramElem1 : paramElems) {
                String type = paramElem1.getAttribute("type");
                if ("page".equals(type)) {
                    String menuItemKeyStr = XMLTool.getElementText(paramElem1);
                    int menuItemKey = Integer.parseInt(menuItemKeyStr);
                    String name = admin.getMenuItemName(menuItemKey);
                    paramElem1.setAttribute("valuename", name);
                } else if ("category".equals(type)) {
                    String categoryKeyStr = XMLTool.getElementText(paramElem1);
                    int categoryKey = Integer.parseInt(categoryKeyStr);
                    String name = admin.getMenuItemName(categoryKey);
                    paramElem1.setAttribute("valuename", name);
                }
            }

            paramElems = XMLTool.getElements(contentobjectdata, "borderparam");
            for (Element paramElem : paramElems) {
                String type = paramElem.getAttribute("type");
                if ("page".equals(type)) {
                    String menuItemKeyStr = XMLTool.getElementText(paramElem);
                    int menuItemKey = Integer.parseInt(menuItemKeyStr);
                    String name = admin.getMenuItemName(menuItemKey);
                    paramElem.setAttribute("valuename", name);
                } else if ("category".equals(type)) {
                    String categoryKeyStr = XMLTool.getElementText(paramElem);
                    int categoryKey = Integer.parseInt(categoryKeyStr);
                    String name = admin.getMenuItemName(categoryKey);
                    paramElem.setAttribute("valuename", name);
                }
            }
        }
    }

    ExtendedMap parameters = new ExtendedMap();

    // Get default css if present
    ResourceKey defaultCSS = admin.getDefaultCSSByMenu(menuKey);
    if (defaultCSS != null) {
        parameters.put("defaultcsskey", defaultCSS.toString());
        parameters.put("defaultcsskeyExist",
                resourceService.getResourceFile(defaultCSS) == null ? "false" : "true");
    }

    VerticalAdminLogger.debug(this.getClass(), 0, doc);

    addCommonParameters(admin, user, request, parameters, -1, menuKey);

    if (createContentObject) {
        parameters.put("create", "1");
        parameters.put("queryparam", "<?xml version=\"1.0\" ?>\n<datasources/>");
    } else {
        parameters.put("create", "0");
        queryParam = StringUtil.formatXML(queryParam, 2);
        parameters.put("queryparam", queryParam);
    }

    parameters.put("menukey", String.valueOf(menuKey));

    parameters.put("page", String.valueOf(request.getParameter("page")));

    String subop = formItems.getString("subop", "");
    if ("popup".equals(subop)) {
        URL redirectURL = new URL("adminpage");
        redirectURL.setParameter("op", "callback");
        redirectURL.setParameter("callback", formItems.getString("callback"));
        redirectURL.setParameter("page", 991);
        redirectURL.setParameter("key", Integer.parseInt(request.getParameter("key")));
        redirectURL.setParameter("fieldname", formItems.getString("fieldname"));
        redirectURL.setParameter("fieldrow", formItems.getString("fieldrow"));
        parameters.put("referer", redirectURL.toString());
        parameters.put("subop", "popup");
    } else {
        parameters.put("referer", request.getHeader("referer"));
    }

    parameters.put("subop", subop);
    parameters.put("fieldname", formItems.getString("fieldname", null));
    parameters.put("fieldrow", formItems.getString("fieldrow", null));
    parameters.put("script", script);

    addAccessLevelParameters(user, parameters);

    UserEntity defaultRunAsUser = siteDao.findByKey(menuKey).resolveDefaultRunAsUser();
    String defaultRunAsUserName = "NA";
    if (defaultRunAsUser != null) {
        defaultRunAsUserName = defaultRunAsUser.getDisplayName();
    }
    parameters.put("defaultRunAsUser", defaultRunAsUserName);

    transformXML(request, response, doc, "contentobject_form.xsl", parameters);
}

From source file:de.betterform.xml.xforms.action.LoadAction.java

private void handleEmbedding(String absoluteURI, HashMap map, boolean includeCSS, boolean includeScript)
        throws XFormsException {

    //        if(this.targetAttribute == null) return;
    //todo: handle multiple params
    if (absoluteURI.indexOf("?") > 0) {
        String name = absoluteURI.substring(absoluteURI.indexOf("?") + 1);
        String value = name.substring(name.indexOf("=") + 1, name.length());
        name = name.substring(0, name.indexOf("="));
        this.container.getProcessor().setContextParam(name, value);
    }/*from www .  jav  a 2  s  .c  o m*/
    if (this.targetAttribute == null) {
        map.put("uri", absoluteURI);
        map.put("show", this.showAttribute);

        // dispatch internal betterform event
        this.container.dispatch(this.target, BetterFormEventNames.LOAD_URI, map);
        return;
    }

    if (!("embed".equals(this.showAttribute))) {
        throw new XFormsException("@show must be 'embed' if @target is given but was: '" + this.showAttribute
                + "' on Element " + DOMUtil.getCanonicalPath(this.element));
    }
    //todo: dirty dirty dirty
    String evaluatedTarget = evalAttributeValueTemplates(this.targetAttribute, this.element);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("targetid evaluated to: " + evaluatedTarget);
    }
    Node embed = getEmbeddedDocument(absoluteURI);
    if (embed == null) {
        //todo: review: context info params containing a '-' fail during access in javascript!
        //todo: the following property should have been 'resource-uri' according to spec
        map.put("resourceUri", absoluteURI);
        this.container.dispatch(this.target, XFormsEventNames.LINK_EXCEPTION, map);
        return;
    }

    // Check for 'ClientSide' events (DOMFocusIN / DOMFocusOUT / xforms-select)
    String utilizedEvents = this.getEventsInSubform(embed);

    // fetch CSS / JavaScript
    String inlineCssRules = "";
    String externalCssRules = "";
    String inlineJavaScript = "";
    String externalJavaScript = "";

    if (includeCSS) {
        inlineCssRules = getInlineCSS(embed);
        externalCssRules = getExternalCSS(embed);
    }
    if (includeScript) {
        inlineJavaScript = getInlineJavaScript(embed);
        externalJavaScript = getExternalJavaScript(embed);
    }

    if (Config.getInstance().getProperty("webprocessor.doIncludes", "false").equals("true")) {
        embed = doIncludes(embed, absoluteURI);
    }

    embed = extractFragment(absoluteURI, embed);
    if (LOGGER.isDebugEnabled()) {
        DOMUtil.prettyPrintDOM(embed);
    }

    Element embeddedNode;
    Element targetElem = getTargetElement(evaluatedTarget);

    //Test if targetElem exist.
    if (targetElem != null) {
        // destroy existing embedded form within targetNode
        if (targetElem.hasChildNodes()) {
            destroyembeddedModels(targetElem);
            Initializer.disposeUIElements(targetElem);
        }

        // import referenced embedded form into host document
        embeddedNode = (Element) this.container.getDocument().importNode(embed, true);

        //import namespaces
        NamespaceResolver.applyNamespaces(targetElem.getOwnerDocument().getDocumentElement(),
                (Element) embeddedNode);

        // keep original targetElem id within hostdoc
        embeddedNode.setAttributeNS(null, "id", targetElem.getAttributeNS(null, "id"));
        //copy all Attributes that might have been on original mountPoint to embedded node
        DOMUtil.copyAttributes(targetElem, embeddedNode, null);
        targetElem.getParentNode().replaceChild(embeddedNode, targetElem);

        //create model for it
        this.container.createEmbeddedForm((Element) embeddedNode);
        // dispatch internal betterform event
        this.container.dispatch((EventTarget) embeddedNode, BetterFormEventNames.EMBED_DONE, map);

        if (getModel().isReady()) {
            map.put("uri", absoluteURI);
            map.put("show", this.showAttribute);
            map.put("targetElement", embeddedNode);
            map.put("nameTarget", evaluatedTarget);
            map.put("xlinkTarget", getXFormsAttribute(targetElem, "id"));
            map.put("inlineCSS", inlineCssRules);
            map.put("externalCSS", externalCssRules);
            map.put("inlineJavascript", inlineJavaScript);
            map.put("externalJavascript", externalJavaScript);
            map.put("utilizedEvents", utilizedEvents);

            this.container.dispatch((EventTarget) embeddedNode, BetterFormEventNames.EMBED, map);
            this.container.dispatch(this.target, BetterFormEventNames.LOAD_URI, map);
        }

        //        storeInContext(absoluteURI, this.showAttribute);
    } else {
        String message = "Element reference for targetid: " + this.targetAttribute + " not found. "
                + DOMUtil.getCanonicalPath(this.element);
        /*
        Element div = this.element.getOwnerDocument().createElementNS("", "div");
        div.setAttribute("class", "bfException");
        div.setTextContent("Element reference for targetid: " + this.targetAttribute + "not found. " + DOMUtil.getCanonicalPath(this.element));
                
        Element body = (Element) this.container.getDocument().getElementsByTagName("body").item(0);
        body.insertBefore(div, DOMUtil.getFirstChildElement(body));
        */
        map.put("message", message);
        map.put("exceptionPath", DOMUtil.getCanonicalPath(this.element));
        this.container.dispatch(this.target, BetterFormEventNames.EXCEPTION, map);
        //throw new XFormsException(message);
    }
}

From source file:edu.stanford.epad.epadws.aim.AIMUtil.java

public static void returnImageAnnotationsXMLV4(PrintWriter responseStream, List<ImageAnnotationCollection> aims)
        throws ParserConfigurationException, edu.stanford.hakan.aim4api.base.AimException {
    long starttime = System.currentTimeMillis();
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    Element root = doc.createElement("imageAnnotations");
    doc.appendChild(root);/*  w  w  w  .  ja va2  s .co  m*/

    for (ImageAnnotationCollection aim : aims) {
        Node node = aim.getXMLNode(docBuilder.newDocument());
        Node copyNode = doc.importNode(node, true);
        Element res = (Element) copyNode; // Copy the node
        res.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:rdf",
                "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
        res.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi",
                "http://www.w3.org/2001/XMLSchema-instance");
        res.setAttribute("xsi:schemaLocation",
                "gme://caCORE.caCORE/4.4/edu.northwestern.radiology.AIM AIM_v4_rv44_XML.xsd");
        res.setAttribute("xmlns", "gme://caCORE.caCORE/4.4/edu.northwestern.radiology.AIM");
        Node n = renameNodeNS(res, "ImageAnnotationCollection",
                "gme://caCORE.caCORE/4.4/edu.northwestern.radiology.AIM");
        root.appendChild(n); // Adding to the root
    }
    String queryResults = XmlDocumentToString(doc, "gme://caCORE.caCORE/4.4/edu.northwestern.radiology.AIM");
    long xmltime = System.currentTimeMillis();
    log.info("Time taken create xml:" + (xmltime - starttime) + " msecs for " + aims.size() + " annotations");
    responseStream.print(queryResults);
    long resptime = System.currentTimeMillis();
    log.info("" + aims.size() + " annotations returned to client, time to write resp:" + (resptime - xmltime)
            + " msecs");
}

From source file:de.betterform.xml.xforms.model.Model.java

/**
 * adds a new instance to this model.//  w  w w  . j  a v  a  2 s.c  o m
 *
 * @param id the optional instance id.
 * @return the new instance.
 */
public Instance addInstance(String id) throws XFormsException {
    // create instance node
    Element instanceNode = this.element.getOwnerDocument().createElementNS(NamespaceConstants.XFORMS_NS,
            (this.xformsPrefix != null ? this.xformsPrefix : NamespaceConstants.XFORMS_PREFIX) + ":"
                    + INSTANCE);

    // ensure id
    String realId = id;
    if (realId == null || realId.length() == 0) {
        realId = this.container.generateId();
    }

    instanceNode.setAttributeNS(null, "id", realId);
    instanceNode.setAttributeNS(NamespaceConstants.XMLNS_NS, "xmlns", "");
    this.element.appendChild(instanceNode);

    // create and initialize instance object
    createInstanceObject(instanceNode);
    return getInstance(id);
}

From source file:com.wfreitas.camelsoap.SoapClient.java

/**
 * Expand the message to accommodate data collections.
 * <p/>/*ww w  . ja va  2  s  .com*/
 * It basically just clones the message where appropriate.
 *
 * @param element The element to be processed.
 * @param params  The message params.  Uses the message params to
 *                decide whether or not cloning is required.
 */
private void expandMessage(Element element, Map params) {

    // If this element is not a cloned element, check does it need to be cloned...
    if (!element.hasAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS, IS_CLONE_ATTRIB)) {
        String ognl = OGNLUtils.getOGNLExpression(element);
        Element clonePoint = getClonePoint(element);

        if (clonePoint != null) {
            int collectionSize;

            collectionSize = calculateCollectionSize(ognl, params);

            if (collectionSize == -1) {
                // It's a collection, but has no entries that match the OGNL expression for this element...
                if (clonePoint == element) {
                    // If the clonePoint is the element itself, we remove it... we're done with it...
                    clonePoint.getParentNode().removeChild(clonePoint);
                } else {
                    // If the clonePoint is not the element itself (it's a child element), leave it
                    // and check it again when we get to it...
                    resetClonePoint(clonePoint);
                }
            } else if (collectionSize == 0) {
                // It's a collection, but has no entries, remove it...
                clonePoint.getParentNode().removeChild(clonePoint);
            } else if (collectionSize == 1) {
                // It's a collection, but no need to clone coz we
                // already have an entry for it...
                clonePoint.setAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS,
                        OGNLUtils.JBOSSESB_SOAP_NS_PREFIX + OGNLUtils.OGNL_ATTRIB, ognl + "[0]");
            } else {
                // It's a collection and we need to do some cloning
                if (clonePoint != null) {
                    // We already have one, so decrement by one...
                    cloneCollectionTemplateElement(clonePoint, (collectionSize - 1), ognl);
                } else {
                    LOGGER.warn("Collection/array template element <" + element.getLocalName()
                            + "> would appear to be invalid.  It doesn't contain any child elements.");
                }
            }
        }
    }

    // Now do the same for the child elements...
    List<Node> children = DOMUtil.copyNodeList(element.getChildNodes());
    for (Node node : children) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            expandMessage((Element) node, params);
        }
    }
}

From source file:fll.scheduler.TournamentSchedule.java

/**
 * Convert the schedule to an XML document that conforms to
 * fll/resources/schedule.xsd. The document that is returned has already been
 * run through {@link #validateXML(org.w3c.dom.Document)}.
 *//*from  w  ww . ja v a2 s.c  o  m*/
public org.w3c.dom.Document createXML() {
    final org.w3c.dom.Document document = XMLUtils.DOCUMENT_BUILDER.newDocument();

    final Element top = document.createElementNS(null, "schedule");
    document.appendChild(top);

    for (final TeamScheduleInfo si : getSchedule()) {
        final Element team = document.createElementNS(null, "team");
        top.appendChild(team);
        team.setAttributeNS(null, "number", String.valueOf(si.getTeamNumber()));
        team.setAttributeNS(null, "judging_station", si.getJudgingGroup());

        for (final String subjName : si.getKnownSubjectiveStations()) {
            final LocalTime time = si.getSubjectiveTimeByName(subjName).getTime();
            final Element subjective = document.createElementNS(null, "subjective");
            team.appendChild(subjective);
            subjective.setAttributeNS(null, "name", subjName);
            subjective.setAttributeNS(null, "time", XML_TIME_FORMAT.format(time));
        }

        for (int round = 0; round < si.getNumberOfRounds(); ++round) {
            final PerformanceTime perfTime = si.getPerf(round);
            final Element perf = document.createElementNS(null, "performance");
            team.appendChild(perf);
            perf.setAttributeNS(null, "round", String.valueOf(round + 1));
            perf.setAttributeNS(null, "table_color", perfTime.getTable());
            perf.setAttributeNS(null, "table_side", String.valueOf(perfTime.getSide()));
            perf.setAttributeNS(null, "time", XML_TIME_FORMAT.format(perfTime.getTime()));
        }
    }

    try {
        validateXML(document);
    } catch (final SAXException e) {
        throw new FLLInternalException("Schedule XML document is invalid", e);
    }

    return document;
}

From source file:com.connectsdk.service.DLNAService.java

protected String getMetadata(String mediaURL, String subsUrl, String mime, String title, String description,
        String iconUrl) {//from   w  w  w .  j  a  v a 2s  .  c  o  m
    try {
        String objectClass = "";
        if (mime.startsWith("image")) {
            objectClass = "object.item.imageItem";
        } else if (mime.startsWith("video")) {
            objectClass = "object.item.videoItem";
        } else if (mime.startsWith("audio")) {
            objectClass = "object.item.audioItem";
        }

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.newDocument();

        Element didlRoot = doc.createElement("DIDL-Lite");
        Element itemElement = doc.createElement("item");
        Element titleElement = doc.createElement("dc:title");
        Element descriptionElement = doc.createElement("dc:description");
        Element resElement = doc.createElement("res");
        Element albumArtElement = doc.createElement("upnp:albumArtURI");
        Element clazzElement = doc.createElement("upnp:class");

        didlRoot.appendChild(itemElement);
        itemElement.appendChild(titleElement);
        itemElement.appendChild(descriptionElement);
        itemElement.appendChild(resElement);
        itemElement.appendChild(albumArtElement);
        itemElement.appendChild(clazzElement);

        didlRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns",
                "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/");
        didlRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:upnp",
                "urn:schemas-upnp-org:metadata-1-0/upnp/");
        didlRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dc",
                "http://purl.org/dc/elements/1.1/");
        didlRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:sec", "http://www.sec.co.kr/");

        titleElement.setTextContent(title);
        descriptionElement.setTextContent(description);
        resElement.setTextContent(encodeURL(mediaURL));
        albumArtElement.setTextContent(encodeURL(iconUrl));
        clazzElement.setTextContent(objectClass);

        itemElement.setAttribute("id", "1000");
        itemElement.setAttribute("parentID", "0");
        itemElement.setAttribute("restricted", "0");

        resElement.setAttribute("protocolInfo", "http-get:*:" + mime + ":DLNA.ORG_OP=01");

        if (subsUrl != null) {
            resElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:pv", "http://www.pv.com/pvns/");
            resElement.setAttribute("pv:subtitleFileUri", subsUrl);
            resElement.setAttribute("pv:subtitleFileType", "srt");

            Element smiResElement = doc.createElement("res");
            smiResElement.setAttribute("protocolInfo", "http-get::smi/caption:");
            smiResElement.setTextContent(subsUrl);
            itemElement.appendChild(smiResElement);

            Element srtResElement = doc.createElement("res");
            srtResElement.setAttribute("protocolInfo", "http-get::text/srt:");
            srtResElement.setTextContent(subsUrl);
            itemElement.appendChild(srtResElement);

            Element captionInfoExElement = doc.createElement("sec:CaptionInfoEx");
            captionInfoExElement.setAttribute("sec:type", "srt");
            captionInfoExElement.setTextContent(subsUrl);
            itemElement.appendChild(captionInfoExElement);

            Element captionInfoElement = doc.createElement("sec:CaptionInfo");
            captionInfoElement.setAttribute("sec:type", "srt");
            captionInfoElement.setTextContent(subsUrl);
            itemElement.appendChild(captionInfoElement);
        }

        doc.appendChild(didlRoot);
        return xmlToString(doc, false);
    } catch (Exception e) {
        return null;
    }
}