Example usage for org.w3c.dom.bootstrap DOMImplementationRegistry getDOMImplementation

List of usage examples for org.w3c.dom.bootstrap DOMImplementationRegistry getDOMImplementation

Introduction

In this page you can find the example usage for org.w3c.dom.bootstrap DOMImplementationRegistry getDOMImplementation.

Prototype

public DOMImplementation getDOMImplementation(final String features) 

Source Link

Document

Return the first implementation that has the desired features, or null if none is found.

Usage

From source file:com.haulmont.cuba.restapi.XMLConverter.java

@Override
public CommitRequest parseCommitRequest(String content) {
    try {//from w  w  w . j a va  2 s  . co  m
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS lsImpl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSParser requestConfigParser = lsImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

        // Set options on the parser
        DOMConfiguration config = requestConfigParser.getDomConfig();
        config.setParameter("validate", Boolean.TRUE);
        config.setParameter("element-content-whitespace", Boolean.FALSE);
        config.setParameter("comments", Boolean.FALSE);
        requestConfigParser.setFilter(new LSParserFilter() {
            @Override
            public short startElement(Element elementArg) {
                return LSParserFilter.FILTER_ACCEPT;
            }

            @Override
            public short acceptNode(Node nodeArg) {
                return StringUtils.isBlank(nodeArg.getTextContent()) ? LSParserFilter.FILTER_REJECT
                        : LSParserFilter.FILTER_ACCEPT;
            }

            @Override
            public int getWhatToShow() {
                return NodeFilter.SHOW_TEXT;
            }
        });
        LSInput lsInput = lsImpl.createLSInput();
        lsInput.setStringData(content);
        Document commitRequestDoc = requestConfigParser.parse(lsInput);
        Node rootNode = commitRequestDoc.getFirstChild();
        if (!"CommitRequest".equals(rootNode.getNodeName()))
            throw new IllegalArgumentException("Not a CommitRequest xml passed: " + rootNode.getNodeName());

        CommitRequest result = new CommitRequest();

        NodeList children = rootNode.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            String childNodeName = child.getNodeName();
            if ("commitInstances".equals(childNodeName)) {
                NodeList entitiesNodeList = child.getChildNodes();

                Set<String> commitIds = new HashSet<>(entitiesNodeList.getLength());
                for (int j = 0; j < entitiesNodeList.getLength(); j++) {
                    Node idNode = entitiesNodeList.item(j).getAttributes().getNamedItem("id");
                    if (idNode == null)
                        continue;

                    String id = idNode.getTextContent();
                    if (id.startsWith("NEW-"))
                        id = id.substring(id.indexOf('-') + 1);
                    commitIds.add(id);
                }

                result.setCommitIds(commitIds);
                result.setCommitInstances(parseNodeList(result, entitiesNodeList));
            } else if ("removeInstances".equals(childNodeName)) {
                NodeList entitiesNodeList = child.getChildNodes();

                List removeInstances = parseNodeList(result, entitiesNodeList);
                result.setRemoveInstances(removeInstances);
            } else if ("softDeletion".equals(childNodeName)) {
                result.setSoftDeletion(Boolean.parseBoolean(child.getTextContent()));
            }
        }
        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * Public default constructor that performs basic initialization
 *//* ww w . j  a v a  2 s  .co  m*/
public SAMLDelegatedAuthenticationService() {
    DOMImplementationRegistry registry;
    try {
        registry = DOMImplementationRegistry.newInstance();
        domLoadSaveImpl = (DOMImplementationLS) registry.getDOMImplementation("LS");
    } catch (ClassCastException ex) {
        logger.error(
                "Unable to initialize XML serializer implementation.  Make sure that the correct jar files are present.",
                ex);
    } catch (ClassNotFoundException ex) {
        logger.error(
                "Unable to initialize XML serializer implementation.  Make sure that the correct jar files are present.",
                ex);
    } catch (InstantiationException ex) {
        logger.error(
                "Unable to initialize XML serializer implementation.  Make sure that the correct jar files are present.",
                ex);
    } catch (IllegalAccessException ex) {
        logger.error(
                "Unable to initialize XML serializer implementation.  Make sure that the correct jar files are present.",
                ex);
    }
}

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

private XSLoader getSchemaLoader()
        throws IllegalAccessException, InstantiationException, ClassNotFoundException {
    // System.setProperty(DOMImplementationRegistry.PROPERTY,
    // "org.apache.xerces.dom.DOMXSImplementationSourceImpl");
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    XSImplementation implementation = (XSImplementation) registry.getDOMImplementation("XS-Loader");
    XSLoader loader = implementation.createXSLoader(null);

    DOMConfiguration cfg = loader.getConfig();

    cfg.setParameter("resource-resolver", new LSResourceResolver() {
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            LSInput input = new LSInput() {
                String systemId;//ww  w .j  ava 2s  . c  om

                public void setSystemId(String systemId) {
                    this.systemId = systemId;
                }

                public void setStringData(String s) {
                }

                String publicId;

                public void setPublicId(String publicId) {
                    this.publicId = publicId;
                }

                public void setEncoding(String s) {
                }

                public void setCharacterStream(Reader reader) {
                }

                public void setCertifiedText(boolean flag) {
                }

                public void setByteStream(InputStream inputstream) {
                }

                String baseURI;

                public void setBaseURI(String baseURI) {
                    if (baseURI == null || "".equals(baseURI)) {
                        baseURI = getContainer().getProcessor().getBaseURI();
                    }
                    this.baseURI = baseURI;
                }

                public String getSystemId() {
                    return this.systemId;
                }

                public String getStringData() {
                    return null;
                }

                public String getPublicId() {
                    return this.publicId;
                }

                public String getEncoding() {
                    return null;
                }

                public Reader getCharacterStream() {
                    return null;
                }

                public boolean getCertifiedText() {
                    return false;
                }

                public InputStream getByteStream() {
                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("Schema resource\n\t\t publicId '" + publicId + "'\n\t\t systemId '"
                                + systemId + "' requested");
                    }
                    try {
                        String pathToSchema = null;
                        if ("http://www.w3.org/MarkUp/SCHEMA/xml-events-attribs-1.xsd".equals(systemId)) {
                            pathToSchema = "schema/xml-events-attribs-1.xsd";
                        } else if ("http://www.w3.org/2001/XMLSchema.xsd".equals(systemId)) {
                            pathToSchema = "schema/XMLSchema.xsd";
                        } else if ("-//W3C//DTD XMLSCHEMA 200102//EN".equals(publicId)) {
                            pathToSchema = "schema/XMLSchema.dtd";
                        } else if ("datatypes".equals(publicId)) {
                            pathToSchema = "schema/datatypes.dtd";
                        } else if ("http://www.w3.org/2001/xml.xsd".equals(systemId)) {
                            pathToSchema = "schema/xml.xsd";
                        }

                        // LOAD WELL KNOWN SCHEMA
                        if (pathToSchema != null) {
                            if (LOGGER.isTraceEnabled()) {
                                LOGGER.trace("loading Schema '" + pathToSchema + "'\n\n");
                            }
                            return Thread.currentThread().getContextClassLoader()
                                    .getResourceAsStream(pathToSchema);
                        }
                        // LOAD SCHEMA THAT IS NOT(!) YET KNWON TO THE XFORMS PROCESSOR
                        else if (systemId != null && !"".equals(systemId)) {
                            URI schemaURI = new URI(baseURI);
                            schemaURI = schemaURI.resolve(systemId);

                            // ConnectorFactory.getFactory()
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("loading schema resource '" + schemaURI.toString() + "'\n\n");
                            }
                            return ConnectorFactory.getFactory().getHTTPResourceAsStream(schemaURI);

                        } else {
                            LOGGER.error("resource not known '" + systemId + "'\n\n");
                            return null;
                        }

                    } catch (XFormsException e) {
                        e.printStackTrace();
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                public String getBaseURI() {
                    return this.baseURI;
                }
            };
            input.setSystemId(systemId);
            input.setBaseURI(baseURI);
            input.setPublicId(publicId);
            return input;
        }
    });
    // END: Patch
    return loader;
}

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 .java 2  s.  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:de.escidoc.core.test.EscidocTestBase.java

/**
 * Serialize the given Dom Object to a String.
 * /*from   w w  w. j av a2  s. c  o m*/
 * @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.//  w ww  .jav  a 2s  .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.alfresco.web.forms.xforms.SchemaUtil.java

public static XSModel parseSchema(final Document schemaDocument, final boolean failOnError)
        throws FormBuilderException {
    try {/*from   w w w .j a v a 2 s .  c om*/
        // Get DOM Implementation using DOM Registry
        System.setProperty(DOMImplementationRegistry.PROPERTY,
                "org.apache.xerces.dom.DOMXSImplementationSourceImpl");

        final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

        final DOMImplementationLS lsImpl = (DOMImplementationLS) registry
                .getDOMImplementation("XML 1.0 LS 3.0");
        if (lsImpl == null) {
            throw new FormBuilderException("unable to create DOMImplementationLS using " + registry);
        }
        final LSInput in = lsImpl.createLSInput();
        in.setStringData(XMLUtil.toString(schemaDocument));

        final XSImplementation xsImpl = (XSImplementation) registry.getDOMImplementation("XS-Loader");
        final XSLoader schemaLoader = xsImpl.createXSLoader(null);
        final DOMConfiguration config = (DOMConfiguration) schemaLoader.getConfig();
        final LinkedList<DOMError> errors = new LinkedList<DOMError>();
        config.setParameter("error-handler", new DOMErrorHandler() {
            public boolean handleError(final DOMError domError) {
                errors.add(domError);
                return true;
            }
        });

        final XSModel result = schemaLoader.load(in);
        if (failOnError && errors.size() != 0) {
            final HashSet<String> messages = new HashSet<String>();
            StringBuilder message = null;
            for (DOMError e : errors) {
                message = new StringBuilder();
                final DOMLocator dl = e.getLocation();
                if (dl != null) {
                    message.append("at line ").append(dl.getLineNumber()).append(" column ")
                            .append(dl.getColumnNumber());
                    if (dl.getRelatedNode() != null) {
                        message.append(" node ").append(dl.getRelatedNode().getNodeName());
                    }
                    message.append(": ").append(e.getMessage());
                }
                messages.add(message.toString());
            }

            message = new StringBuilder();
            message.append(messages.size() > 1 ? "errors" : "error").append(" parsing schema: \n");
            for (final String s : messages) {
                message.append(s).append("\n");
            }

            throw new FormBuilderException(message.toString());
        }

        if (result == null) {
            throw new FormBuilderException("invalid schema");
        }
        return result;
    } catch (ClassNotFoundException x) {
        throw new FormBuilderException(x);
    } catch (InstantiationException x) {
        throw new FormBuilderException(x);
    } catch (IllegalAccessException x) {
        throw new FormBuilderException(x);
    }
}

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

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

    try {/*  ww  w  . j  av a  2 s . com*/
        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 {/* www .ja va  2s  .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 void loadRoutes(final String domain, final DataSource dataSource, final Resource resource,
        final AnyTypeKind anyTypeKind) {

    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    boolean shouldLoadRoutes = jdbcTemplate.queryForList(
            String.format("SELECT * FROM %s WHERE ANYTYPEKIND = ?", CamelRoute.class.getSimpleName()),
            new Object[] { anyTypeKind.name() }).isEmpty();

    if (shouldLoadRoutes) {
        try {//from w  w w.  j  a v a  2s  .  co  m
            TransformerFactory tf = null;
            DOMImplementationLS domImpl = null;
            NodeList routeNodes;
            if (IS_JBOSS) {
                tf = TransformerFactory.newInstance();
                tf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                dbFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(resource.getInputStream());

                routeNodes = doc.getDocumentElement().getElementsByTagName("route");
            } else {
                DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
                domImpl = (DOMImplementationLS) reg.getDOMImplementation("LS");
                LSInput lsinput = domImpl.createLSInput();
                lsinput.setByteStream(resource.getInputStream());

                LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

                routeNodes = parser.parse(lsinput).getDocumentElement().getElementsByTagName("route");
            }

            for (int s = 0; s < routeNodes.getLength(); s++) {
                Node routeElement = routeNodes.item(s);
                String routeContent = IS_JBOSS ? nodeToString(routeNodes.item(s), tf)
                        : nodeToString(routeNodes.item(s), domImpl);
                String routeId = ((Element) routeElement).getAttribute("id");

                jdbcTemplate.update(
                        String.format("INSERT INTO %s(ID, ANYTYPEKIND, CONTENT) VALUES (?, ?, ?)",
                                CamelRoute.class.getSimpleName()),
                        new Object[] { routeId, anyTypeKind.name(), routeContent });
                LOG.info("[{}] Route successfully loaded: {}", domain, routeId);
            }
        } catch (Exception e) {
            LOG.error("[{}] Route load failed", domain, e);
        }
    }
}