Example usage for org.w3c.dom Document createElementNS

List of usage examples for org.w3c.dom Document createElementNS

Introduction

In this page you can find the example usage for org.w3c.dom Document createElementNS.

Prototype

public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;

Source Link

Document

Creates an element of the given qualified name and namespace URI.

Usage

From source file:org.apache.rahas.impl.SAMLTokenIssuer.java

/**
 * Create the SAML assertion with the secret held in an
 * <code>xenc:EncryptedKey</code>
 * /*from   ww  w  .  j  av  a2s.co  m*/
 * @param doc
 * @param keyInfoContent
 * @param config
 * @param crypto
 * @param notBefore
 * @param notAfter
 * @return
 * @throws TrustException
 */
private SAMLAssertion createAttributeAssertion(Document doc, RahasData data, Element keyInfoContent,
        SAMLNameIdentifier subjectNameId, SAMLTokenIssuerConfig config, Crypto crypto, Date notBefore,
        Date notAfter) throws TrustException {
    try {
        String[] confirmationMethods = new String[] { SAMLSubject.CONF_HOLDER_KEY };

        Element keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "KeyInfo");
        ((OMElement) keyInfoContent).declareNamespace(WSConstants.SIG_NS, WSConstants.SIG_PREFIX);
        ((OMElement) keyInfoContent).declareNamespace(WSConstants.ENC_NS, WSConstants.ENC_PREFIX);

        keyInfoElem.appendChild(keyInfoContent);

        SAMLSubject subject = new SAMLSubject(subjectNameId, Arrays.asList(confirmationMethods), null,
                keyInfoElem);

        SAMLAttribute[] attrs = null;
        if (config.getCallbackHandler() != null) {
            SAMLAttributeCallback cb = new SAMLAttributeCallback(data);
            SAMLCallbackHandler handler = config.getCallbackHandler();
            handler.handle(cb);
            attrs = cb.getAttributes();
        } else if (config.getCallbackHandlerName() != null
                && config.getCallbackHandlerName().trim().length() > 0) {
            SAMLAttributeCallback cb = new SAMLAttributeCallback(data);
            SAMLCallbackHandler handler = null;
            MessageContext msgContext = data.getInMessageContext();
            ClassLoader classLoader = msgContext.getAxisService().getClassLoader();
            Class cbClass = null;
            try {
                cbClass = Loader.loadClass(classLoader, config.getCallbackHandlerName());
            } catch (ClassNotFoundException e) {
                throw new TrustException("cannotLoadPWCBClass",
                        new String[] { config.getCallbackHandlerName() }, e);
            }
            try {
                handler = (SAMLCallbackHandler) cbClass.newInstance();
            } catch (java.lang.Exception e) {
                throw new TrustException("cannotCreatePWCBInstance",
                        new String[] { config.getCallbackHandlerName() }, e);
            }
            handler.handle(cb);
            attrs = cb.getAttributes();
        } else {
            //TODO Remove this after discussing
            SAMLAttribute attribute = new SAMLAttribute("Name", "https://rahas.apache.org/saml/attrns", null,
                    -1, Arrays.asList(new String[] { "Colombo/Rahas" }));
            attrs = new SAMLAttribute[] { attribute };
        }

        List attributeList = Arrays.asList(attrs);

        // If ActAs element is present in the RST
        if (data.getActAs() != null) {
            SAMLAttribute actAsAttribute = new SAMLAttribute("ActAs", "https://rahas.apache.org/saml/attrns",
                    null, -1, Arrays.asList(new String[] { data.getActAs() }));
            attributeList.add(actAsAttribute);
        }
        SAMLAttributeStatement attrStmt = new SAMLAttributeStatement(subject, attributeList);

        SAMLStatement[] statements = { attrStmt };

        List<SAMLCondition> conditions = null;
        if (StringUtils.isNotBlank(this.audienceRestriction)) {
            SAMLAudienceRestrictionCondition audienceRestriction = new SAMLAudienceRestrictionCondition();
            audienceRestriction.addAudience(this.audienceRestriction);
            conditions = new ArrayList<SAMLCondition>();
            conditions.add(audienceRestriction);
        }

        SAMLAssertion assertion = new SAMLAssertion(config.issuerName, notBefore, notAfter, conditions, null,
                Arrays.asList(statements));

        // sign the assertion
        X509Certificate[] issuerCerts = crypto.getCertificates(config.issuerKeyAlias);

        String sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_RSA;
        String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
        if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
            sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_DSA;
        }
        java.security.Key issuerPK = crypto.getPrivateKey(config.issuerKeyAlias, config.issuerKeyPassword);
        assertion.sign(sigAlgo, issuerPK, Arrays.asList(issuerCerts));

        return assertion;
    } catch (Exception e) {
        throw new TrustException("samlAssertionCreationError", e);
    }
}

From source file:org.apache.rahas.impl.SAMLTokenIssuer.java

/**
 * @param doc/*  w w w . j av a 2  s  .c  o m*/
 * @param confMethod
 * @param subjectNameId
 * @param keyInfoContent
 * @param config
 * @param crypto
 * @param notBefore
 * @param notAfter
 * @return
 * @throws TrustException
 */
protected SAMLAssertion createAuthAssertion(Document doc, String confMethod, SAMLNameIdentifier subjectNameId,
        Element keyInfoContent, SAMLTokenIssuerConfig config, Crypto crypto, Date notBefore, Date notAfter,
        RahasData data) throws TrustException {
    try {
        String[] confirmationMethods = new String[] { confMethod };

        Element keyInfoElem = null;
        if (keyInfoContent != null) {
            keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "KeyInfo");
            ((OMElement) keyInfoContent).declareNamespace(WSConstants.SIG_NS, WSConstants.SIG_PREFIX);
            ((OMElement) keyInfoContent).declareNamespace(WSConstants.ENC_NS, WSConstants.ENC_PREFIX);

            keyInfoElem.appendChild(keyInfoContent);
        }

        SAMLSubject subject = new SAMLSubject(subjectNameId, Arrays.asList(confirmationMethods), null,
                keyInfoElem);

        SAMLAuthenticationStatement authStmt = new SAMLAuthenticationStatement(subject,
                SAMLAuthenticationStatement.AuthenticationMethod_Password, notBefore, null, null, null);

        List<SAMLStatement> statements = new ArrayList<SAMLStatement>();

        // According to ws-trust-1.3; <wst:claims> is an optional element requests a specific set of claims.
        // This will be handled by the AttributeCallbackHandler class.
        SAMLStatement attrStatement = createSAMLAttributeStatement((SAMLSubject) subject.clone(), data, config);
        statements.add(attrStatement);
        statements.add(authStmt);

        List<SAMLCondition> conditions = null;
        if (StringUtils.isNotBlank(this.audienceRestriction)) {
            SAMLAudienceRestrictionCondition audienceRestriction = new SAMLAudienceRestrictionCondition();
            audienceRestriction.addAudience(this.audienceRestriction);
            conditions = new ArrayList<SAMLCondition>();
            conditions.add(audienceRestriction);
        }

        SAMLAssertion assertion = new SAMLAssertion(config.issuerName, notBefore, notAfter, conditions, null,
                statements);

        // sign the assertion
        X509Certificate[] issuerCerts = crypto.getCertificates(config.issuerKeyAlias);

        String sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_RSA;
        String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
        if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
            sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_DSA;
        }
        java.security.Key issuerPK = crypto.getPrivateKey(config.issuerKeyAlias, config.issuerKeyPassword);
        assertion.sign(sigAlgo, issuerPK, Arrays.asList(issuerCerts));

        return assertion;
    } catch (Exception e) {
        throw new TrustException("samlAssertionCreationError", e);
    }
}

From source file:org.apache.servicemix.jbi.deployer.utils.ManagementSupport.java

private static Element createChild(Node parent, String name, String text) {
    Document doc = parent instanceof Document ? (Document) parent : parent.getOwnerDocument();
    Element child = doc.createElementNS(HTTP_JAVA_SUN_COM_XML_NS_JBI_MANAGEMENT_MESSAGE, name);
    if (text != null) {
        child.appendChild(doc.createTextNode(text));
    }/*from www  .  j  a v  a2 s . c  o  m*/
    parent.appendChild(child);
    return child;
}

From source file:org.apache.servicemix.jbi.runtime.impl.ServiceEndpointImpl.java

public DocumentFragment getAsReference(QName operationName) {
    try {//from  w  ww .  j  a  v a 2  s.co  m
        Document doc = DOMUtil.newDocument();
        DocumentFragment fragment = doc.createDocumentFragment();
        Element epr = doc.createElementNS(JBI_NAMESPACE, JBI_PREFIX + JBI_ENDPOINT_REFERENCE);
        epr.setAttributeNS(XMLNS_NAMESPACE, "xmlns:sns", getServiceName().getNamespaceURI());
        epr.setAttributeNS(JBI_NAMESPACE, JBI_PREFIX + JBI_SERVICE_NAME,
                "sns:" + getServiceName().getLocalPart());
        epr.setAttributeNS(JBI_NAMESPACE, JBI_PREFIX + JBI_ENDPOINT_NAME, getEndpointName());
        fragment.appendChild(epr);
        return fragment;
    } catch (Exception e) {
        LOG.warn("Unable to create reference for ServiceEndpoint " + this, e);
        return null;
    }
}

From source file:org.apache.shindig.gadgets.servlet.CajaContentRewriter.java

public void rewrite(Gadget gadget, MutableContent mc) {
    if (!cajaEnabled(gadget))
        return;// ww w  . j  a va2s . c  o m

    GadgetContext gadgetContext = gadget.getContext();
    boolean debug = gadgetContext.getDebug();
    Document doc = mc.getDocument();

    // Serialize outside of MutableContent, to prevent a re-parse.
    String docContent = HtmlSerialization.serialize(doc);
    String cacheKey = HashUtil.checksum(docContent.getBytes());
    Node root = doc.createDocumentFragment();
    root.appendChild(doc.getDocumentElement());

    Node cajoledData = null;
    if (cajoledCache != null && !debug) {
        Element cajoledOutput = cajoledCache.getElement(cacheKey);
        if (cajoledOutput != null) {
            cajoledData = doc.adoptNode(cajoledOutput);
            createContainerFor(doc, cajoledData);
            mc.documentChanged();
        }
    }

    if (cajoledData == null) {
        UriFetcher fetcher = makeFetcher(gadget);
        UriPolicy policy = makePolicy(gadget);
        URI javaGadgetUri = gadgetContext.getUrl().toJavaUri();
        MessageQueue mq = new SimpleMessageQueue();
        MessageContext context = new MessageContext();
        PluginMeta meta = new PluginMeta(fetcher, policy);
        PluginCompiler compiler = makePluginCompiler(meta, mq);

        compiler.setMessageContext(context);

        if (debug) {
            // This will load cajita-debugmode.js
            gadget.addFeature("caja-debug");
            compiler.setGoals(compiler.getGoals().without(PipelineMaker.ONE_CAJOLED_MODULE)
                    .with(PipelineMaker.ONE_CAJOLED_MODULE_DEBUG));
        }

        InputSource is = new InputSource(javaGadgetUri);
        boolean safe = false;

        compiler.addInput(new Dom(root), javaGadgetUri);

        try {
            if (!compiler.run()) {
                throw new GadgetRewriteException("Gadget has compile errors");
            }
            StringBuilder scriptBody = new StringBuilder();
            CajoledModule cajoled = compiler.getJavascript();
            TokenConsumer tc = debug ? new JsPrettyPrinter(new Concatenator(scriptBody))
                    : new JsMinimalPrinter(new Concatenator(scriptBody));
            cajoled.render(new RenderContext(tc).withAsciiOnly(true).withEmbeddable(true));

            tc.noMoreTokens();

            Node html = compiler.getStaticHtml();

            Element script = doc.createElementNS(Namespaces.HTML_NAMESPACE_URI, "script");
            script.setAttributeNS(Namespaces.HTML_NAMESPACE_URI, "type", "text/javascript");
            script.appendChild(doc.createTextNode(scriptBody.toString()));

            Element cajoledOutput = doc.createElement("div");
            cajoledOutput.setAttribute("id", "cajoled-output");
            cajoledOutput.setAttribute("classes", "g___");
            cajoledOutput.setAttribute("style", "position: relative;");

            cajoledOutput.appendChild(doc.adoptNode(html));
            cajoledOutput.appendChild(tameCajaClientApi(doc));
            cajoledOutput.appendChild(doc.adoptNode(script));

            Element messagesNode = formatErrors(doc, is, docContent, mq, /* is invisible */ false);
            cajoledOutput.appendChild(messagesNode);
            if (cajoledCache != null && !debug) {
                cajoledCache.addElement(cacheKey, cajoledOutput);
            }

            cajoledData = cajoledOutput;
            createContainerFor(doc, cajoledData);
            mc.documentChanged();
            safe = true;
            HtmlSerialization.attach(doc, htmlSerializer, null);
        } catch (GadgetRewriteException e) {
            // There were cajoling errors
            // Content is only used to produce useful snippets with error messages
            createContainerFor(doc, formatErrors(doc, is, docContent, mq, true /* visible */));
            logException(e, mq);
            safe = true;
        } finally {
            if (!safe) {
                // Fail safe
                mc.setContent("");
            }
        }
    }
}

From source file:org.apache.tuscany.sca.implementation.bpel.ode.TuscanyProcessConfImpl.java

/**
 * Gets the variable initializer DOM sequence for a given property, in the context of a supplied
 * DOM model of the BPEL process//from  w  w  w  . java2  s.  co m
 * @param bpelDOM - DOM representation of the BPEL process
 * @param property - SCA Property which relates to one of the variables in the BPEL process
 * @return - a DOM model representation of the XML statements required to initialize the
 * BPEL variable with the value of the SCA property.
 */
private Element getInitializerSequence(Document bpelDOM, ComponentProperty property) {
    // For an XML simple type (string, int, etc), the BPEL initializer sequence is:
    // <assign><copy><from><literal>value</literal></from><to variable="variableName"/></copy></assign>
    QName type = property.getXSDType();
    if (type != null) {
        if (mapper.isSimpleXSDType(type)) {
            // Simple types
            String NS_URI = bpelDOM.getDocumentElement().getNamespaceURI();
            String valueText = getPropertyValueText(property.getValue());
            Element literalElement = bpelDOM.createElementNS(NS_URI, "literal");
            literalElement.setTextContent(valueText);
            Element fromElement = bpelDOM.createElementNS(NS_URI, "from");
            fromElement.appendChild(literalElement);
            Element toElement = bpelDOM.createElementNS(NS_URI, "to");
            Attr variableAttribute = bpelDOM.createAttribute("variable");
            variableAttribute.setValue(property.getName());
            toElement.setAttributeNode(variableAttribute);
            Element copyElement = bpelDOM.createElementNS(NS_URI, "copy");
            copyElement.appendChild(fromElement);
            copyElement.appendChild(toElement);
            Element assignElement = bpelDOM.createElementNS(NS_URI, "assign");
            assignElement.appendChild(copyElement);
            return assignElement;
        } // end if
          // TODO Deal with Properties which have a non-simple type
    } else {
        // TODO Deal with Properties which have an element as the type
    } // end if

    return null;
}

From source file:org.apache.woden.internal.DOMWSDLReader.java

protected void parseSchemaForXMLSchema(DescriptionElement desc) throws WSDLException {

    // Parse the schema for schema to include the built in schema types in the Woden model.
    // TODO: As there are a finite number of built in schema types it may be better to create
    // constants rather than reading the schema for schema on the creation of every model. 
    // Also, this method currently requires that the schema elements exist in the types element.
    // This may not be the best idea as it may imply that this schema contains an actual import
    // statement in a WSDL 2.0 document. This method also does not work for when building the
    // model programmatically.
    // This method should be reevaluated at a later point.
    TypesElement types = desc.getTypesElement();
    if (types == null) {
        types = desc.addTypesElement();//  w w  w  .j a v a 2 s .  co m
    }
    if (types.getTypeSystem() == null) {
        types.setTypeSystem(Constants.TYPE_XSD_2001);
    }

    try {
        Document schemaDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element schemaElem = schemaDoc.createElementNS(SchemaConstants.NS_STRING_SCHEMA,
                SchemaConstants.ELEM_IMPORT);
        schemaElem.setAttribute(SchemaConstants.ATTR_NAMESPACE, SchemaConstants.NS_STRING_SCHEMA);
        schemaElem.setAttribute(SchemaConstants.ATTR_SCHEMA_LOCATION,
                resolveURI("http://www.w3.org/2001/XMLSchema.xsd"));

        XMLElement xmlEl = createXMLElement(schemaElem);
        desc.getTypesElement().addSchema(parseSchemaImport(xmlEl, desc));
    } catch (Exception e) {
        logger.error("A problem was encountered while creating the build in XML schema types: " + e);
    }
}

From source file:org.apache.ws.axis.security.handler.WSDoAllHandler.java

public Element getDeploymentData(Document doc) {
    log.debug("Enter: BasicHandler::getDeploymentData");

    Element root = doc.createElementNS("", "handler");

    root.setAttribute("class", this.getClass().getName());
    options = this.getOptions();
    if (options != null) {
        Enumeration e = options.keys();
        while (e.hasMoreElements()) {
            String k = (String) e.nextElement();
            Object v = options.get(k);
            Element e1 = doc.createElementNS("", "option");
            e1.setAttribute("name", k);
            e1.setAttribute("value", v.toString());
            root.appendChild(e1);/*from   www  . ja va2s .  c  om*/
        }
    }
    log.debug("Exit: WSDoAllHandler::getDeploymentData");
    return (root);
}

From source file:org.apache.ws.security.message.TimestampTest.java

/**
 * This is a test for processing an Timestamp where the "Created" element is in the (near)
 * future. It should be accepted by default when it is created 30 seconds in the future, 
 * and then rejected once we configure "0 seconds" for future-time-to-live.
 *//* ww w . ja v a2 s .  co  m*/
@org.junit.Test
public void testNearFutureCreated() throws Exception {

    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    Element timestampElement = doc.createElementNS(WSConstants.WSU_NS,
            WSConstants.WSU_PREFIX + ":" + WSConstants.TIMESTAMP_TOKEN_LN);

    DateFormat zulu = new XmlSchemaDateFormat();
    Element elementCreated = doc.createElementNS(WSConstants.WSU_NS,
            WSConstants.WSU_PREFIX + ":" + WSConstants.CREATED_LN);
    Date createdDate = new Date();
    long currentTime = createdDate.getTime() + 30000;
    createdDate.setTime(currentTime);
    elementCreated.appendChild(doc.createTextNode(zulu.format(createdDate)));
    timestampElement.appendChild(elementCreated);

    secHeader.getSecurityHeader().appendChild(timestampElement);

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
        LOG.debug(outputString);
    }
    //
    // Do some processing
    //
    WSSConfig config = WSSConfig.getNewInstance();
    verify(doc, config);
    try {
        config.setTimeStampFutureTTL(0);
        verify(doc, config);
        fail("The timestamp validation should have failed");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == WSSecurityException.MESSAGE_EXPIRED);
    }
}

From source file:org.apache.ws.security.message.TimestampTest.java

/**
 * This is a test for processing an Timestamp where the "Created" element is in the future.
 * A Timestamp that is 120 seconds in the future should be rejected by default.
 *//*w  w w  . ja va  2s .  c  o m*/
@org.junit.Test
public void testFutureCreated() throws Exception {

    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    Element timestampElement = doc.createElementNS(WSConstants.WSU_NS,
            WSConstants.WSU_PREFIX + ":" + WSConstants.TIMESTAMP_TOKEN_LN);

    DateFormat zulu = new XmlSchemaDateFormat();
    Element elementCreated = doc.createElementNS(WSConstants.WSU_NS,
            WSConstants.WSU_PREFIX + ":" + WSConstants.CREATED_LN);
    Date createdDate = new Date();
    long currentTime = createdDate.getTime() + 120000;
    createdDate.setTime(currentTime);
    elementCreated.appendChild(doc.createTextNode(zulu.format(createdDate)));
    timestampElement.appendChild(elementCreated);

    secHeader.getSecurityHeader().appendChild(timestampElement);

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
        LOG.debug(outputString);
    }
    //
    // Do some processing
    //
    WSSConfig config = WSSConfig.getNewInstance();
    try {
        verify(doc, config);
        fail("The timestamp validation should have failed");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == WSSecurityException.MESSAGE_EXPIRED);
    }
}