Example usage for org.w3c.dom.ls DOMImplementationLS createLSOutput

List of usage examples for org.w3c.dom.ls DOMImplementationLS createLSOutput

Introduction

In this page you can find the example usage for org.w3c.dom.ls DOMImplementationLS createLSOutput.

Prototype

public LSOutput createLSOutput();

Source Link

Document

Create a new empty output destination object where LSOutput.characterStream, LSOutput.byteStream, LSOutput.systemId, LSOutput.encoding are null.

Usage

From source file:net.svcret.core.util.XMLUtils.java

public static void serialize(Document document, boolean prettyPrint, Writer theWriter) {
    DOMImplementationLS impl = getDOMImpl();
    LSSerializer serializer = impl.createLSSerializer();
    // document.normalizeDocument();
    DOMConfiguration config = serializer.getDomConfig();
    if (prettyPrint && config.canSetParameter("format-pretty-print", Boolean.TRUE)) {
        config.setParameter("format-pretty-print", true);
    }/*  w  ww  .j a  v a 2s.c  o m*/
    config.setParameter("xml-declaration", true);
    LSOutput output = impl.createLSOutput();
    output.setEncoding("UTF-8");
    output.setCharacterStream(theWriter);
    serializer.write(document, output);
}

From source file:nl.imvertor.common.file.XmlFile.java

/**
 * Zet een Document weg als file. Transformeer middels het XSLT file. Als
 * XSLT file is "", identity transform./*  w  w w.jav a 2  s  . c  o m*/
 * 
 * @param doc
 * @param xsltfile
 * @param parms
 * @throws Exception
 */
public void fromDocument(Document doc) throws Exception {
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("XML 3.0 LS 3.0");
    if (impl == null) {
        System.out.println("No DOMImplementation found !");
        System.exit(0);
    }
    LSSerializer serializer = impl.createLSSerializer();
    LSOutput output = impl.createLSOutput();
    output.setEncoding("UTF-8");
    output.setByteStream(new FileOutputStream(this));
    serializer.write(doc, output);
}

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

public SOAPEnvelope issue(RahasData data) throws TrustException {
    MessageContext inMsgCtx = data.getInMessageContext();

    try {//from   w  w w .ja v a2 s .c  om
        SAMLTokenIssuerConfig config = null;
        if (this.configElement != null) {
            config = new SAMLTokenIssuerConfig(
                    configElement.getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG));
        }

        // Look for the file
        if (config == null && this.configFile != null) {
            config = new SAMLTokenIssuerConfig(this.configFile);
            //config = new SAMLTokenIssuerConfig("/home/thilina/Desktop/saml-issuer-config.xml");
        }

        // Look for the param
        if (config == null && this.configParamName != null) {
            Parameter param = inMsgCtx.getParameter(this.configParamName);
            if (param != null && param.getParameterElement() != null) {
                config = new SAMLTokenIssuerConfig(param.getParameterElement()
                        .getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG));
            } else {
                throw new TrustException("expectedParameterMissing", new String[] { this.configParamName });
            }
        }

        if (config == null) {
            throw new TrustException("configurationIsNull");
        }

        //initialize and set token persister and config in configuration context.
        if (TokenIssuerUtil.isPersisterConfigured(config)) {
            TokenIssuerUtil.manageTokenPersistenceSettings(config, inMsgCtx);
        }

        SOAPEnvelope env = TrustUtil
                .createSOAPEnvelope(inMsgCtx.getEnvelope().getNamespace().getNamespaceURI());

        Crypto crypto;
        if (config.cryptoElement != null) { // crypto props
            // defined as
            // elements
            crypto = CryptoFactory.getInstance(TrustUtil.toProperties(config.cryptoElement),
                    inMsgCtx.getAxisService().getClassLoader());
        } else { // crypto props defined in a properties file
            crypto = CryptoFactory.getInstance(config.cryptoPropertiesFile,
                    inMsgCtx.getAxisService().getClassLoader());
        }

        // Get the document
        Document doc = ((Element) env).getOwnerDocument();

        // Get the key size and create a new byte array of that size
        int keySize = data.getKeysize();
        String keyType = data.getKeyType();

        keySize = (keySize == -1) ? config.keySize : keySize;

        //Build the assertion
        AssertionBuilder assertionBuilder = new AssertionBuilder();
        Assertion assertion = assertionBuilder.buildObject();
        assertion.setVersion(SAMLVersion.VERSION_20);

        // Set an UUID as the ID of an assertion
        assertion.setID(UUIDGenerator.getUUID());

        //Set the issuer
        IssuerBuilder issuerBuilder = new IssuerBuilder();
        Issuer issuer = issuerBuilder.buildObject();
        issuer.setValue(config.issuerName);
        assertion.setIssuer(issuer);

        // Validity period
        DateTime creationDate = new DateTime();
        DateTime expirationDate = new DateTime(creationDate.getMillis() + config.ttl);

        // These variables are used to build the trust assertion
        Date creationTime = creationDate.toDate();
        Date expirationTime = expirationDate.toDate();

        Conditions conditions = new ConditionsBuilder().buildObject();
        conditions.setNotBefore(creationDate);
        conditions.setNotOnOrAfter(expirationDate);

        if (data.getAppliesToAddress() != null) {
            AudienceRestriction audienceRestriction = new AudienceRestrictionBuilder().buildObject();
            Audience issuerAudience = new AudienceBuilder().buildObject();
            issuerAudience.setAudienceURI(data.getAppliesToAddress());
            audienceRestriction.getAudiences().add(issuerAudience);
            conditions.getAudienceRestrictions().add(audienceRestriction);
        }

        assertion.setConditions(conditions);

        // Set the issued time.
        assertion.setIssueInstant(new DateTime());

        // Create the subject
        Subject subject;

        if (!data.getKeyType().endsWith(RahasConstants.KEY_TYPE_BEARER)) {
            subject = createSubjectWithHolderOfKeySC(config, doc, crypto, creationDate, expirationDate, data);
        } else {
            subject = createSubjectWithBearerSC(data);
        }

        // Set the subject
        assertion.setSubject(subject);

        // If a SymmetricKey is used build an attr stmt, if a public key is build an authn stmt. 
        if (isSymmetricKeyBasedHoK) {
            AttributeStatement attrStmt = createAttributeStatement(data, config);
            assertion.getAttributeStatements().add(attrStmt);
        } else {
            AuthnStatement authStmt = createAuthnStatement(data);
            assertion.getAuthnStatements().add(authStmt);
            if (data.getClaimDialect() != null && data.getClaimElem() != null) {
                assertion.getAttributeStatements().add(createAttributeStatement(data, config));
            }
        }

        if (data.getOverridenSubjectValue() != null && data.getOverridenSubjectValue().trim().length() > 0) {
            subject.getNameID().setValue(data.getOverridenSubjectValue());
        }

        // Create a SignKeyHolder to hold the crypto objects that are used to sign the assertion
        SignKeyHolder signKeyHolder = createSignKeyHolder(config, crypto);

        // Sign the assertion
        assertion = setSignature(assertion, signKeyHolder);

        OMElement rstrElem;
        int wstVersion = data.getVersion();
        if (RahasConstants.VERSION_05_02 == wstVersion) {
            rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(wstVersion, env.getBody());
        } else {
            OMElement rstrcElem = TrustUtil.createRequestSecurityTokenResponseCollectionElement(wstVersion,
                    env.getBody());
            rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(wstVersion, rstrcElem);
        }

        TrustUtil.createTokenTypeElement(wstVersion, rstrElem).setText(RahasConstants.TOK_TYPE_SAML_20);

        if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {
            TrustUtil.createKeySizeElement(wstVersion, rstrElem, keySize);
        }

        if (config.addRequestedAttachedRef) {
            TrustUtil.createRequestedAttachedRef(wstVersion, rstrElem, "#" + assertion.getID(),
                    RahasConstants.TOK_TYPE_SAML_20);
        }

        if (config.addRequestedUnattachedRef) {
            TrustUtil.createRequestedUnattachedRef(wstVersion, rstrElem, assertion.getID(),
                    RahasConstants.TOK_TYPE_SAML_20);
        }

        if (data.getAppliesToAddress() != null) {
            TrustUtil.createAppliesToElement(rstrElem, data.getAppliesToAddress(), data.getAddressingNs());
        }

        // Use GMT time in milliseconds
        DateFormat zulu = new XmlSchemaDateFormat();

        // Add the Lifetime element
        TrustUtil.createLifetimeElement(wstVersion, rstrElem, zulu.format(creationTime),
                zulu.format(expirationTime));

        // Create the RequestedSecurityToken element and add the SAML token
        // to it
        OMElement reqSecTokenElem = TrustUtil.createRequestedSecurityTokenElement(wstVersion, rstrElem);
        Token assertionToken;

        Node tempNode = assertion.getDOM();

        //Serializing and re-generating the AXIOM element using the DOM Element created using xerces
        Element element = assertion.getDOM();

        ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();

        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");

        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStrm);
        writer.write(element, output);
        String elementString = byteArrayOutputStrm.toString();

        OMElement assertionElement = AXIOMUtil.stringToOM(elementString);

        reqSecTokenElem.addChild((OMNode) ((Element) rstrElem).getOwnerDocument().importNode(tempNode, true));

        // Store the token
        assertionToken = new Token(assertion.getID(), (OMElement) assertionElement, creationTime,
                expirationTime);

        // At this point we definitely have the secret
        // Otherwise it should fail with an exception earlier
        assertionToken.setSecret(data.getEphmeralKey());

        if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)
                && config.keyComputation != SAMLTokenIssuerConfig.KeyComputation.KEY_COMP_USE_REQ_ENT) {
            TokenIssuerUtil.handleRequestedProofToken(data, wstVersion, config, rstrElem, assertionToken, doc);
        }

        //SAML tokens are enabled for persistence only if token store is not disabled.
        if (!config.isTokenStoreDisabled()) {
            assertionToken.setPersistenceEnabled(true);
            TrustUtil.getTokenStore(inMsgCtx).add(assertionToken);
        }

        return env;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.apache.rahas.impl.util.SAML2Utils.java

public static Element getElementFromAssertion(XMLObject xmlObj) throws TrustException {
    try {//from  ww w  .j  av a 2 s.c o m

        String jaxpProperty = System.getProperty("javax.xml.parsers.DocumentBuilderFactory");
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObj);
        Element element = marshaller.marshall(xmlObj);

        // Reset the sys. property to its previous value.
        if (jaxpProperty == null) {
            System.getProperties().remove("javax.xml.parsers.DocumentBuilderFactory");
        } else {
            System.setProperty("javax.xml.parsers.DocumentBuilderFactory", jaxpProperty);
        }

        ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();

        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");

        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStrm);
        writer.write(element, output);
        String elementString = byteArrayOutputStrm.toString();

        DocumentBuilderFactoryImpl.setDOOMRequired(true);

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(new ByteArrayInputStream(elementString.trim().getBytes()));
        Element assertionElement = document.getDocumentElement();
        DocumentBuilderFactoryImpl.setDOOMRequired(false);

        log.debug("DOM element is created successfully from the OpenSAML2 XMLObject");
        return assertionElement;

    } catch (Exception e) {
        throw new TrustException("Error creating DOM object from the assertion", e);
    }
}

From source file:org.apache.syncope.core.logic.init.CamelRouteLoader.java

private String nodeToString(final Node content, final DOMImplementationLS domImpl) {
    StringWriter writer = new StringWriter();
    try {// ww  w .  j av a  2 s .c  o m
        LSSerializer serializer = domImpl.createLSSerializer();
        serializer.getDomConfig().setParameter("xml-declaration", false);
        LSOutput lso = domImpl.createLSOutput();
        lso.setCharacterStream(writer);
        serializer.write(content, lso);
    } catch (Exception e) {
        LOG.debug("While serializing route node", e);
    }
    return writer.toString();
}

From source file:org.intellij.xquery.runner.rt.vendor.exist.ExistRunnerApp.java

private String prettyPrint(Element node, DOMImplementation domImplementation)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    DOMImplementationRegistry domImplementationRegistry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementationRegistry
            .getDOMImplementation("LS");
    LSOutput lsOutput = domImplementationLS.createLSOutput();
    LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
    lsOutput.setEncoding("UTF-8");
    Writer stringWriter = new StringWriter();
    lsOutput.setCharacterStream(stringWriter);
    lsSerializer.write(node, lsOutput);//from w w w  .j a v a2s  .c o  m
    String result = stringWriter.toString();
    return result;
}

From source file:org.jaggeryjs.modules.sso.common.util.Util.java

/**
 * Serializing a SAML2 object into a String
 *
 * @param xmlObject object that needs to serialized.
 * @return serialized object/* w  w  w. ja  va2 s  . c o  m*/
 * @throws Exception
 */
public static String marshall(XMLObject xmlObject) throws Exception {
    try {
        doBootstrap();
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
        Element element = marshaller.marshall(xmlObject);

        ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStrm);
        writer.write(element, output);
        return byteArrayOutputStrm.toString();
    } catch (Exception e) {
        throw new Exception("Error Serializing the SAML Response", e);
    }
}

From source file:org.ms123.common.importing.XmlImporter.java

private String prettyPrint(Element e) {
    DOMImplementation domImplementation = m_document.getImplementation();
    if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) {
        DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation.getFeature("LS",
                "3.0");
        LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
        DOMConfiguration domConfiguration = lsSerializer.getDomConfig();
        if (domConfiguration.canSetParameter("format-pretty-print", Boolean.TRUE)) {
            lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
            LSOutput lsOutput = domImplementationLS.createLSOutput();
            lsOutput.setEncoding("UTF-8");
            StringWriter stringWriter = new StringWriter();
            lsOutput.setCharacterStream(stringWriter);
            lsSerializer.write(e, lsOutput);
            return stringWriter.toString();
        } else {/*ww  w .  j  a v  a 2 s  .c  o  m*/
            throw new RuntimeException("DOMConfiguration 'format-pretty-print' parameter isn't settable.");
        }
    } else {
        throw new RuntimeException("DOM 3.0 LS and/or DOM 2.0 Core not supported.");
    }
}

From source file:org.sakaiproject.tool.assessment.qti.util.XmlStringBuffer.java

/**
 * string value of document// ww  w. jav  a2s. c  om
 *
 * @return the string
 */
public final String stringValue() {
    if (log.isDebugEnabled()) {
        log.debug("stringValue()");
    }

    if (document == null) {
        return this.xml.toString();
    } else {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
            DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
            LSSerializer writer = impl.createLSSerializer();
            writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
            LSOutput output = impl.createLSOutput();
            output.setByteStream(out);
            writer.write(document, output);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return out.toString();
    }
}

From source file:org.sakaiproject.util.StorageUtils.java

/**
 * Write a DOM Document to an xml file.//from   w w  w . java  2  s  .c  om
 * 
 * @param doc
 *        The DOM Document to write.
 * @param fileName
 *        The complete file name path.
 */
public static void writeDocument(Document doc, String fileName) {
    OutputStream out = null;
    try {
        out = new FileOutputStream(fileName);
        //          get an instance of the DOMImplementation registry
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        DOMImplementation impl = builder.getDOMImplementation();

        DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS", "3.0");
        LSSerializer serializer = feature.createLSSerializer();
        LSOutput output = feature.createLSOutput();
        output.setByteStream(out);
        output.setEncoding("UTF-8");
        serializer.write(doc, output);

        out.close();
    } catch (Exception any) {
        M_log.warn("writeDocument: " + any.toString());
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {

            }
        }
    }
}