Example usage for org.w3c.dom.ls LSOutput setByteStream

List of usage examples for org.w3c.dom.ls LSOutput setByteStream

Introduction

In this page you can find the example usage for org.w3c.dom.ls LSOutput setByteStream.

Prototype

public void setByteStream(java.io.OutputStream byteStream);

Source Link

Document

An attribute of a language and binding dependent type that represents a writable stream of bytes.

Usage

From source file:com.collabnet.ccf.core.recovery.HospitalArtifactReplayer.java

@SuppressWarnings("deprecation")
private void loadBeanDefinitionsFromUrl(String url, GenericApplicationContext context) {
    BeanDefinitionReader reader = null;/*from  ww w  . j  a  v  a 2s  . co m*/
    if (url.endsWith(".xml")) {
        reader = new XmlBeanDefinitionReader(context);
    } else if (url.endsWith(".properties")) {
        reader = new PropertiesBeanDefinitionReader(context);
    }

    if (reader != null) {
        try {
            UrlResource urlResource = new UrlResource(url);
            InputStream is = urlResource.getInputStream();
            Document document = builder.parse(is);
            Element routerElement = this.getRouterElement(document);
            this.stripOffProcessors(routerElement);
            this.addGAImportComponents(document, routerElement);
            DOMImplementationRegistry registry = null;
            try {
                registry = DOMImplementationRegistry.newInstance();
            } catch (ClassCastException e) {
                log.error("error", e);
                throw new CCFRuntimeException("error", e);
            } catch (ClassNotFoundException e) {
                log.error("error", e);
                throw new CCFRuntimeException("error", e);
            } catch (InstantiationException e) {
                log.error("error", e);
                throw new CCFRuntimeException("error", e);
            } catch (IllegalAccessException e) {
                log.error("error", e);
                throw new CCFRuntimeException("error", e);
            }
            String originalConfigFileAbsolutePath = urlResource.getFile().getAbsolutePath();
            String componentName = entry.getSourceComponent();
            String configComponentIdentifier = "{" + originalConfigFileAbsolutePath + "}" + componentName;

            File outputFile = null;
            if (componentConfigFileMap.containsKey(configComponentIdentifier)) {
                outputFile = componentConfigFileMap.get(configComponentIdentifier);
            } else {
                outputFile = File.createTempFile(componentName, ".xml", replayWorkDir);
                DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
                LSSerializer writer = impl.createLSSerializer();
                LSOutput output = impl.createLSOutput();
                FileOutputStream bas = new FileOutputStream(outputFile.getAbsolutePath());
                output.setByteStream(bas);
                writer.write(document, output);
                bas.flush();
                bas.close();
                componentConfigFileMap.put(configComponentIdentifier, outputFile);
            }

            // FIXME Use of deprecated method
            UrlResource newUrlResource = new UrlResource(outputFile.toURL().toString());
            ((XmlBeanDefinitionReader) reader).registerBeanDefinitions(document, newUrlResource);
        } catch (BeansException e) {
            log.error("error", e);
            throw new RuntimeException("BeansException : " + e.getMessage(), e);
        } catch (MalformedURLException e) {
            log.error("error", e);
            throw new RuntimeException("MalformedUrlException : " + e.getMessage(), e);
        } catch (IOException e) {
            log.error("error", e);
            throw new RuntimeException("IOExceptionException : " + e.getMessage(), e);
        } catch (SAXException e) {
            log.error("error", e);
            throw new RuntimeException("SAXException : " + e.getMessage(), e);
        }
    } else {
        throw new RuntimeException("No BeanDefinitionReader associated with " + url);
    }
}

From source file:com.commander4j.thread.AutoLabellerThread.java

public void run() {
    logger.debug("AutoLabeller Thread running");
    setSessionID(JUnique.getUniqueID());
    JDBUser user = new JDBUser(getHostID(), getSessionID());
    user.setUserId("interface");
    user.setPassword("interface");
    user.setLoginPassword("interface");
    Common.userList.addUser(getSessionID(), user);
    Common.sd.setData(getSessionID(), "silentExceptions", "Yes", true);

    Boolean dbconnected = false;/*from   www .ja  v a2s .  c  om*/

    if (Common.hostList.getHost(hostID).isConnected(sessionID) == false) {

        dbconnected = Common.hostList.getHost(hostID).connect(sessionID, hostID);

    } else {
        dbconnected = true;
    }

    if (dbconnected) {

        JDBViewAutoLabellerPrinter alp = new JDBViewAutoLabellerPrinter(getHostID(), getSessionID());
        LinkedList<JDBViewAutoLabellerPrinter> autolabellerList = new LinkedList<JDBViewAutoLabellerPrinter>();

        int noOfMessages = 0;

        while (true) {

            JWait.milliSec(500);

            if (allDone) {
                if (dbconnected) {
                    Common.hostList.getHost(hostID).disconnect(getSessionID());
                }
                return;
            }

            autolabellerList.clear();
            autolabellerList = alp.getModifiedPrinterLines();
            noOfMessages = autolabellerList.size();

            if (noOfMessages > 0) {
                for (int x = 0; x < noOfMessages; x++) {
                    JWait.milliSec(100);

                    JDBViewAutoLabellerPrinter autolabview = autolabellerList.get(x);

                    messageProcessedOK = true;
                    messageError = "";

                    if (autolabview.getPrinterObj().isEnabled()) {
                        logger.debug("Line             =" + autolabview.getAutoLabellerObj().getLine());
                        logger.debug("Line Description =" + autolabview.getAutoLabellerObj().getDescription());
                        logger.debug("Printer ID       =" + autolabview.getPrinterObj().getPrinterID());
                        logger.debug("Printer Enabled  =" + autolabview.getPrinterObj().isEnabled());
                        logger.debug("Export Path      =" + autolabview.getPrinterObj().getExportRealPath());
                        logger.debug("Export Enabled   =" + autolabview.getPrinterObj().isExportEnabled());
                        logger.debug("Export Format    =" + autolabview.getPrinterObj().getExportFormat());
                        logger.debug("Direct Print     =" + autolabview.getPrinterObj().isDirectPrintEnabled());
                        logger.debug("Printer Type     =" + autolabview.getPrinterObj().getPrinterType());
                        logger.debug("Printer IP       =" + autolabview.getPrinterObj().getIPAddress());
                        logger.debug("Printer Port     =" + autolabview.getPrinterObj().getPort());
                        logger.debug("Process Order    =" + autolabview.getLabelDataObj().getProcessOrder());
                        logger.debug("Material         =" + autolabview.getLabelDataObj().getMaterial());
                        logger.debug("Module ID        =" + autolabview.getModuleObj().getModuleId());
                        logger.debug("Module Type      =" + autolabview.getModuleObj().getType());

                        if (autolabview.getPrinterObj().isExportEnabled()) {
                            String exportPath = JUtility.replaceNullStringwithBlank(
                                    JUtility.formatPath(autolabview.getPrinterObj().getExportRealPath()));
                            if (exportPath.equals("") == false) {
                                if (exportPath.substring(exportPath.length() - 1)
                                        .equals(File.separator) == false) {
                                    exportPath = exportPath + File.separator;
                                }
                            } else {
                                exportPath = Common.interface_output_path + "Auto Labeller" + File.separator;
                            }

                            String exportFilename = exportPath
                                    + JUtility.removePathSeparators(autolabview.getAutoLabellerObj().getLine())
                                    + "_"
                                    + JUtility.removePathSeparators(autolabview.getPrinterObj().getPrinterID())
                                    + "." + autolabview.getPrinterObj().getExportFormat();

                            String exportFilenameTemp = exportFilename + ".out";

                            logger.debug("Export Filename  =" + exportFilename);

                            /* ================CSV================ */

                            if (autolabview.getPrinterObj().getExportFormat().equals("CSV")) {
                                try {
                                    PreparedStatement stmt = null;
                                    ResultSet rs;
                                    String labelType = autolabview.getLabelDataObj().getLabelType();
                                    stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID())
                                            .prepareStatement(
                                                    Common.hostList.getHost(getHostID()).getSqlstatements()
                                                            .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties"
                                                                    + "_" + labelType));
                                    stmt.setString(1, autolabview.getAutoLabellerObj().getLine());
                                    stmt.setString(2, autolabview.getPrinterObj().getPrinterID());
                                    stmt.setFetchSize(50);

                                    rs = stmt.executeQuery();

                                    logger.debug("Writing CSV");

                                    CSVWriter writer = new CSVWriter(new FileWriter(exportFilenameTemp),
                                            CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER,
                                            CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);

                                    writer.writeAll(rs, true);

                                    rs.close();

                                    stmt.close();

                                    writer.close();

                                    File fromFile = new File(exportFilenameTemp);
                                    File toFile = new File(exportFilename);

                                    FileUtils.deleteQuietly(toFile);
                                    FileUtils.moveFile(fromFile, toFile);

                                    fromFile = null;
                                    toFile = null;

                                } catch (Exception e) {
                                    messageProcessedOK = false;
                                    messageError = e.getMessage();
                                }
                            }

                            /* ================XML================ */

                            if (autolabview.getPrinterObj().getExportFormat().equals("XML")) {
                                try {
                                    PreparedStatement stmt = null;
                                    ResultSet rs;

                                    stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID())
                                            .prepareStatement(Common.hostList.getHost(getHostID())
                                                    .getSqlstatements()
                                                    .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties"));
                                    stmt.setString(1, autolabview.getAutoLabellerObj().getLine());
                                    stmt.setString(2, autolabview.getPrinterObj().getPrinterID());
                                    stmt.setFetchSize(50);

                                    rs = stmt.executeQuery();
                                    ResultSetMetaData rsmd = rs.getMetaData();
                                    int colCount = rsmd.getColumnCount();

                                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                                    DocumentBuilder builder = factory.newDocumentBuilder();
                                    Document document = builder.newDocument();

                                    Element message = (Element) document.createElement("message");

                                    Element hostUniqueID = addElement(document, "hostRef",
                                            Common.hostList.getHost(getHostID()).getUniqueID());
                                    message.appendChild(hostUniqueID);

                                    Element messageRef = addElement(document, "messageRef",
                                            autolabview.getAutoLabellerObj().getUniqueID());
                                    message.appendChild(messageRef);

                                    Element messageType = addElement(document, "interfaceType",
                                            "Auto Labeller Data");
                                    message.appendChild(messageType);

                                    Element messageInformation = addElement(document, "messageInformation",
                                            "Unique ID=" + autolabview.getAutoLabellerObj().getUniqueID());
                                    message.appendChild(messageInformation);

                                    Element messageDirection = addElement(document, "interfaceDirection",
                                            "Output");
                                    message.appendChild(messageDirection);

                                    Element messageDate = addElement(document, "messageDate",
                                            JUtility.getISOTimeStampStringFormat(JUtility.getSQLDateTime()));
                                    message.appendChild(messageDate);

                                    if (rs.first()) {

                                        Element labelData = (Element) document.createElement("LabelData");

                                        Element row = document.createElement("Row");
                                        labelData.appendChild(row);
                                        for (int i = 1; i <= colCount; i++) {
                                            String columnName = rsmd.getColumnName(i);
                                            Object value = rs.getObject(i);
                                            Element node = document.createElement(columnName);
                                            node.appendChild(document.createTextNode(value.toString()));
                                            row.appendChild(node);
                                        }

                                        message.appendChild(labelData);

                                        document.appendChild(message);

                                        JXMLDocument xmld = new JXMLDocument();
                                        xmld.setDocument(document);

                                        // ===============================

                                        DOMImplementationLS DOMiLS = null;
                                        FileOutputStream FOS = null;

                                        // testing the support for DOM
                                        // Load and Save
                                        if ((document.getFeature("Core", "3.0") != null)
                                                && (document.getFeature("LS", "3.0") != null)) {
                                            DOMiLS = (DOMImplementationLS) (document.getImplementation())
                                                    .getFeature("LS", "3.0");

                                            // get a LSOutput object
                                            LSOutput LSO = DOMiLS.createLSOutput();

                                            FOS = new FileOutputStream(exportFilename);
                                            LSO.setByteStream((OutputStream) FOS);

                                            // get a LSSerializer object
                                            LSSerializer LSS = DOMiLS.createLSSerializer();

                                            // do the serialization
                                            LSS.write(document, LSO);

                                            FOS.close();
                                        }

                                        // ===============================

                                    }
                                    rs.close();
                                    stmt.close();

                                } catch (Exception e) {
                                    messageError = e.getMessage();
                                }

                            }

                            if (autolabview.getPrinterObj().getExportFormat().equals("LQF")) {

                            }
                        }

                        if (autolabview.getPrinterObj().isDirectPrintEnabled()) {

                        }

                    }

                    if (messageProcessedOK == true) {
                        autolabview.getAutoLabellerObj().setModified(false);
                        autolabview.getAutoLabellerObj().update();
                    } else {
                        logger.debug(messageError);
                    }

                    autolabview = null;
                }
            }
        }
    }
}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Serialize the given Dom Object to a String.
 * //from  ww  w. ja va2  s  .  c  om
 * @param xml
 *            The Xml Node to serialize.
 * @param omitXMLDeclaration
 *            Indicates if XML declaration will be omitted.
 * @return The String representation of the Xml Node.
 * @throws Exception
 *             If anything fails.
 */
public static String toString(final Node xml, final boolean omitXMLDeclaration) throws Exception {

    String result = new String();
    if (xml instanceof AttrImpl) {
        result = xml.getTextContent();
    } else if (xml instanceof Document) {
        StringWriter stringOut = new StringWriter();
        // format
        OutputFormat format = new OutputFormat((Document) xml);
        format.setIndenting(true);
        format.setPreserveSpace(true);
        format.setOmitXMLDeclaration(omitXMLDeclaration);
        format.setEncoding(DEFAULT_CHARSET);
        // serialize
        XMLSerializer serial = new XMLSerializer(stringOut, format);
        serial.asDOMSerializer();

        serial.serialize((Document) xml);
        result = stringOut.toString();
    } else {
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSOutput lsOutput = impl.createLSOutput();
        lsOutput.setEncoding(DEFAULT_CHARSET);

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        lsOutput.setByteStream(os);
        LSSerializer writer = impl.createLSSerializer();
        // result = writer.writeToString(xml);
        writer.write(xml, lsOutput);
        result = ((ByteArrayOutputStream) lsOutput.getByteStream()).toString(DEFAULT_CHARSET);
        if ((omitXMLDeclaration) && (result.indexOf("?>") != -1)) {
            result = result.substring(result.indexOf("?>") + 2);
        }
        // result = toString(getDocument(writer.writeToString(xml)),
        // true);
    }
    return result;
}

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.//from w  w w.j a  va 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 {// www  .j  av a 2s .co m
        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.  ja  v a2s. com*/

        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.jaggeryjs.modules.sso.common.util.Util.java

/**
 * Serializing a SAML2 object into a String
 *
 * @param xmlObject object that needs to serialized.
 * @return serialized object/*ww w . ja v a  2 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.sakaiproject.tool.assessment.qti.util.XmlStringBuffer.java

/**
 * string value of document//from  w w w.  j av a2s .  c o  m
 *
 * @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.j a  v a  2s.c o  m
 * 
 * @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) {

            }
        }
    }
}

From source file:org.wso2.appserver.webapp.security.utils.SSOUtils.java

/**
 * Serializes the specified SAML 2.0 based XML content representation to its corresponding actual XML syntax
 * representation.//from   ww  w  . j  a  va2  s . co  m
 *
 * @param xmlObject the SAML 2.0 based XML content object
 * @return a {@link String} representation of the actual XML representation of the SAML 2.0 based XML content
 * representation
 * @throws SSOException if an error occurs during the marshalling process
 */
public static String marshall(XMLObject xmlObject) throws SSOException {
    try {
        Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory()
                .getMarshaller(xmlObject);
        Element element = null;
        if (marshaller != null) {
            element = marshaller.marshall(xmlObject);
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS implementation = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = implementation.createLSSerializer();
        LSOutput output = implementation.createLSOutput();
        output.setByteStream(byteArrayOutputStream);
        writer.write(element, output);
        return new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
    } catch (ClassNotFoundException | InstantiationException | MarshallingException
            | IllegalAccessException e) {
        throw new SSOException("Error in marshalling SAML 2.0 Assertion", e);
    }
}