List of usage examples for org.w3c.dom.ls DOMImplementationLS createLSSerializer
public LSSerializer createLSSerializer();
LSSerializer
object. 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); }//from w w w . jav a2 s .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. j ava 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.adeptnet.auth.saml.SAMLClient.java
private String _createAuthnRequest(final String requestId) throws SAMLException { final AuthnRequest request = createAuthnRequest(requestId); try {// ww w . j a va2s.c om // samlobject to xml dom object final Element elem = Configuration.getMarshallerFactory().getMarshaller(request).marshall(request); // and to a string... final Document document = elem.getOwnerDocument(); final DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation(); final LSSerializer serializer = domImplLS.createLSSerializer(); serializer.getDomConfig().setParameter("xml-declaration", false); return serializer.writeToString(elem); } catch (MarshallingException e) { throw new SAMLException(e); } }
From source file:org.apache.juddi.mapping.MappingApiToModel.java
private static String serializeTransformElement(Element xformEl) throws DOMException, LSException { Document document = xformEl.getOwnerDocument(); DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation(); LSSerializer serializer = domImplLS.createLSSerializer(); // serializer.getDomConfig().setParameter("namespaces", true); // serializer.getDomConfig().setParameter("namespace-declarations", true); serializer.getDomConfig().setParameter("canonical-form", false); serializer.getDomConfig().setParameter("xml-declaration", false); String str = serializer.writeToString(xformEl); return str;//www . j av a 2s . co m }
From source file:org.apache.rahas.impl.SAML2TokenIssuer.java
public SOAPEnvelope issue(RahasData data) throws TrustException { MessageContext inMsgCtx = data.getInMessageContext(); try {//from w ww.j av a 2 s.c o 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 {// w ww. j a v a 2 s .co 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 {/*from w ww . j a va 2s . 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.hawkular.wildfly.module.installer.XmlConfigBuilderTest.java
private void printDocument(Document doc) { try {/*from ww w.j a v a2 s .co m*/ DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation(); System.out.println("XML DOCUMENT:\n" + domImplementation.createLSSerializer().writeToString(doc)); } catch (Throwable t) { System.out.println("Can't print doc: " + t); } }
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 ww w . jav a2 s . 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//from w w w. j a va2s . 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); } }