下面列出了怎么用org.w3c.dom.ls.DOMImplementationLS的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Serialize XML objects
*
* @param xmlObject : XACML or SAML objects to be serialized
* @return serialized XACML or SAML objects
*/
private String marshall(XMLObject xmlObject) throws EntitlementProxyException {
try {
doBootstrap();
System.setProperty(DOCUMENT_BUILDER_FACTORY, DOCUMENT_BUILDER_FACTORY_IMPL);
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 new String(byteArrayOutputStrm.toByteArray(), Charset.forName("UTF-8"));
} catch (Exception e) {
log.error("Error Serializing the SAML Response");
throw new EntitlementProxyException("Error Serializing the SAML Response", e);
}
}
public static String elementToString(Element element) {
try {
if (element == null) {
/* return an empty string because, the other way around works the same,
where if we give a empty string as the XML, we get a null element
from "stringToElement" */
return "";
}
Document document = element.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
//by default its true, so set it to false to get String without xml-declaration
serializer.getDomConfig().setParameter(XML_DECLARATION, false);
return serializer.writeToString(element);
} catch (Exception e) {
log.error("Error while convering element to string: " + e.getMessage(), e);
return null;
}
}
/***
* Helper method which converts XML Document into pretty formatted string
*
* @param doc to convert
* @return converted XML as String
*/
public static String documentToString(Document doc) {
String strMsg = "";
try {
DOMImplementation domImpl = doc.getImplementation();
DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
LSSerializer lsSerializer = domImplLS.createLSSerializer();
lsSerializer.getDomConfig().setParameter("format-pretty-print", true);
Writer stringWriter = new StringWriter();
LSOutput lsOutput = domImplLS.createLSOutput();
lsOutput.setEncoding("UTF-8");
lsOutput.setCharacterStream(stringWriter);
lsSerializer.write(doc, lsOutput);
strMsg = stringWriter.toString();
} catch (Exception e) {
logger.warn("Error occurred when converting document to string", e);
}
return strMsg;
}
/**
* Serializing a SAML2 object into a String
*
* @param xmlObject object that needs to serialized.
* @return serialized object
* @throws SAMLSSOException
*/
public static String marshall(XMLObject xmlObject) throws SAMLSSOException {
try {
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) {
log.error("Error Serializing the SAML Response");
throw new SAMLSSOException("Error Serializing the SAML Response", e);
}
}
public void load(File f) throws ConfigPersisterException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
String configString = lsSerializer.writeToString(doc);
_config = (Config) _xstream.fromXML(convertToCurrent(configString));
setConfigPath(f);
} catch (Exception e) {
throw new ConfigPersisterException(e);
}
}
/**
* Normalize and pretty-print XML so that it can be compared using string
* compare. The following code does the following: - Removes comments -
* Makes sure attributes are ordered consistently - Trims every element -
* Pretty print the document
*
* @param xml The XML to be normalized
* @return The equivalent XML, but now normalized
*/
public static String normalizeXML(String xml) throws Exception {
// Remove all white space adjoining tags ("trim all elements")
xml = xml.replaceAll("\\s*<", "<");
xml = xml.replaceAll(">\\s*", ">");
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS domLS = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSParser lsParser = domLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
LSInput input = domLS.createLSInput();
input.setStringData(xml);
Document document = lsParser.parse(input);
LSSerializer lsSerializer = domLS.createLSSerializer();
lsSerializer.getDomConfig().setParameter("comments", Boolean.FALSE);
lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
return lsSerializer.writeToString(document);
}
/**
* Obtain a the DOM, level 3, Load/Save serializer {@link LSSerializer} instance from the
* given {@link DOMImplementationLS} instance.
*
* <p>
* The serializer instance will be configured with the parameters passed as the <code>serializerParams</code>
* argument. It will also be configured with an {@link LSSerializerFilter} that shows all nodes to the filter,
* and accepts all nodes shown.
* </p>
*
* @param domImplLS the DOM Level 3 Load/Save implementation to use
* @param serializerParams parameters to pass to the {@link DOMConfiguration} of the serializer
* instance, obtained via {@link LSSerializer#getDomConfig()}. May be null.
*
* @return a new LSSerializer instance
*/
public static LSSerializer getLSSerializer(DOMImplementationLS domImplLS, Map<String, Object> serializerParams) {
LSSerializer serializer = domImplLS.createLSSerializer();
serializer.setFilter(new LSSerializerFilter() {
public short acceptNode(Node arg0) {
return FILTER_ACCEPT;
}
public int getWhatToShow() {
return SHOW_ALL;
}
});
if (serializerParams != null) {
DOMConfiguration serializerDOMConfig = serializer.getDomConfig();
for (String key : serializerParams.keySet()) {
serializerDOMConfig.setParameter(key, serializerParams.get(key));
}
}
return serializer;
}
/**
* Serializing a SAML2 object into a String
*
* @param xmlObject object that needs to serialized.
* @return serialized object
* @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);
}
}
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
DOMImplementation impl = document.getImplementation();
DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
LSSerializer dsi = implLS.createLSSerializer();
/* We should have here incorrect document without getXmlVersion() method:
* Such Document is generated by replacing the JDK bootclasses with it's
* own Node,Document and DocumentImpl classes (see run.sh). According to
* XERCESJ-1007 the AbstractMethodError should be thrown in such case.
*/
String result = dsi.writeToString(document);
System.out.println("Result:" + result);
}
public static String dom2String2(Document document) {
DOMImplementationRegistry registry;
try {
registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS domImplLS = (DOMImplementationLS)registry.getDOMImplementation("LS");
LSSerializer ser = domImplLS.createLSSerializer(); // Create a serializer for the DOM
LSOutput out = domImplLS.createLSOutput();
StringWriter stringOut = new StringWriter(); // Writer will be a String
out.setCharacterStream(stringOut);
ser.write(document, out); // Serialize the DOM
System.out.println( "STRXML = "
+ stringOut.toString() ); // Spit out the DOM as a String
return stringOut.toString();
} catch (Exception e) {
System.err.println("Cannot create registry: "+e.getMessage());
}
return null;
}
public static void writeDoc() throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
Document domDocument = factory.newDocumentBuilder().newDocument();
Element root = domDocument.createElement("root");
root.setAttribute("xml:lang", "en");
root.setAttribute("foo", "bar");
root.appendChild(domDocument.createElement("child"));
root.appendChild(domDocument.createTextNode("mixed"));
domDocument.appendChild(root);
@SuppressWarnings("unused")
String domString = ((DOMImplementationLS) factory.newDocumentBuilder()
.getDOMImplementation()).createLSSerializer().writeToString(domDocument);
XMLDocumentManager docMgr = client.newXMLDocumentManager();
docMgr.write(docId, new DOMHandle().with(domDocument));
}
private static String marshall(XMLObject xmlObject) throws org.wso2.carbon.identity.base.IdentityException {
try {
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("UTF-8");
} catch (Exception e) {
log.error("Error Serializing the SAML Response");
throw IdentityException.error("Error Serializing the SAML Response", e);
}
}
/**
* Serializing a SAML2 object into a String
*
* @param xmlObject object that needs to serialized.
* @return serialized object
* @throws SAML2SSOUIAuthenticatorException
*/
public static String marshall(XMLObject xmlObject) throws SAML2SSOUIAuthenticatorException {
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) {
log.error("Error Serializing the SAML Response");
throw new SAML2SSOUIAuthenticatorException("Error Serializing the SAML Response", e);
}
}
public static String prettyPrint(String xml) {
if (StringUtils.isEmpty(xml))
return xml;
try {
final InputSource src = new InputSource(new StringReader(xml));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
final boolean keepDeclaration = xml.startsWith("<?xml");
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
final LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", true);
writer.getDomConfig().setParameter("xml-declaration", keepDeclaration);
return writer.writeToString(document);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
return xml; // Return the same string if error take place
}
public void load(File f) throws ConfigPersisterException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
String configString = lsSerializer.writeToString(doc);
_config = (Config) _xstream.fromXML(convertToCurrent(configString));
setConfigPath(f);
} catch (Exception e) {
throw new ConfigPersisterException(e);
}
}
private void format(Document document, Writer writer) {
DOMImplementation implementation = document.getImplementation();
if(implementation.hasFeature(LS_FEATURE_KEY, LS_FEATURE_VERSION) && implementation.hasFeature(CORE_FEATURE_KEY, CORE_FEATURE_VERSION)) {
DOMImplementationLS implementationLS = (DOMImplementationLS) implementation.getFeature(LS_FEATURE_KEY, LS_FEATURE_VERSION);
LSSerializer serializer = implementationLS.createLSSerializer();
DOMConfiguration configuration = serializer.getDomConfig();
configuration.setParameter("format-pretty-print", Boolean.TRUE);
configuration.setParameter("comments", preserveComments);
LSOutput output = implementationLS.createLSOutput();
output.setEncoding("UTF-8");
output.setCharacterStream(writer);
serializer.write(document, output);
}
}
static public String getInnerXmlText(Node xmlNode)
{
StringBuilder result = new StringBuilder();
Document xmlDocument = xmlNode.getOwnerDocument();
DOMImplementation xmlDocumentImpl = xmlDocument.getImplementation();
DOMImplementationLS lsImpl = (DOMImplementationLS) xmlDocumentImpl.getFeature("LS", "3.0");
LSSerializer lsSerializer = lsImpl.createLSSerializer();
NodeList childNodes = xmlNode.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
String childText = lsSerializer.writeToString(childNodes.item(i));
int pos = childText.indexOf("?>");
if (pos > -1) {
childText = childText.substring(pos + 2);
}
result.append(childText);
}
return result.toString();
}
/**
* Normalize and pretty-print XML so that it can be compared using string
* compare. The following code does the following: - Removes comments -
* Makes sure attributes are ordered consistently - Trims every element -
* Pretty print the document
*
* @param xml The XML to be normalized
* @return The equivalent XML, but now normalized
*/
public static String normalizeXML(String xml) throws Exception {
// Remove all white space adjoining tags ("trim all elements")
xml = xml.replaceAll("\\s*<", "<");
xml = xml.replaceAll(">\\s*", ">");
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS domLS = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSParser lsParser = domLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
LSInput input = domLS.createLSInput();
input.setStringData(xml);
Document document = lsParser.parse(input);
LSSerializer lsSerializer = domLS.createLSSerializer();
lsSerializer.getDomConfig().setParameter("comments", Boolean.FALSE);
lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
return lsSerializer.writeToString(document);
}
/**
* Serialise the given SVG document.
* @param path The file of the future serialised document.
* @return True: the document has been successfully saved.
*/
public boolean saveSVGDocument(final String path) {
if(path == null) {
return false;
}
boolean ok = true;
try {
final DOMImplementationLS impl = (DOMImplementationLS) DOMImplementationRegistry.newInstance().getDOMImplementation("XML 3.0 LS 3.0"); //NON-NLS
final LSSerializer serializer = impl.createLSSerializer();
serializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); //NON-NLS
serializer.getDomConfig().setParameter("namespaces", Boolean.FALSE); //NON-NLS
final LSOutput output = impl.createLSOutput();
final Charset charset = Charset.defaultCharset();
try(final OutputStreamWriter fw = new OutputStreamWriter(Files.newOutputStream(Path.of(path)), charset.newEncoder())) {
output.setEncoding(charset.name());
output.setCharacterStream(fw);
serializer.write(getDocumentElement(), output);
}
}catch(final ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException | IOException ex) {
BadaboomCollector.INSTANCE.add(ex);
ok = false;
}
return ok;
}
/**
* Check for DOMErrorHandler handling DOMError. Before fix of bug 4890927
* DOMConfiguration.setParameter("well-formed",true) throws an exception.
*
* @throws Exception If any errors occur.
*/
@Test
public void testCreateNewItem2Sell() throws Exception {
String xmlFile = XML_DIR + "novelsInvalid.xml";
Document document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(xmlFile);
document.getDomConfig().setParameter("well-formed", true);
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
MyDOMOutput domOutput = new MyDOMOutput();
domOutput.setByteStream(System.out);
LSSerializer writer = impl.createLSSerializer();
writer.write(document, domOutput);
}
/**
* Check for DOMErrorHandler handling DOMError. Before fix of bug 4896132
* test throws DOM Level 1 node error.
*
* @throws Exception If any errors occur.
*/
@Test
public void testCreateNewItem2SellRetry() throws Exception {
String xmlFile = XML_DIR + "accountInfo.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document document = dbf.newDocumentBuilder().parse(xmlFile);
DOMConfiguration domConfig = document.getDomConfig();
MyDOMErrorHandler errHandler = new MyDOMErrorHandler();
domConfig.setParameter("error-handler", errHandler);
DOMImplementationLS impl =
(DOMImplementationLS) DOMImplementationRegistry.newInstance()
.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
MyDOMOutput domoutput = new MyDOMOutput();
domoutput.setByteStream(System.out);
writer.write(document, domoutput);
document.normalizeDocument();
writer.write(document, domoutput);
assertFalse(errHandler.isError());
}
@Test
public void testLSInputParsingByteStream() throws Exception {
DOMImplementationLS impl = (DOMImplementationLS) getDocumentBuilder().getDOMImplementation();
LSParser domParser = impl.createLSParser(MODE_SYNCHRONOUS, null);
LSInput src = impl.createLSInput();
try (InputStream is = new FileInputStream(ASTROCAT)) {
src.setByteStream(is);
assertNotNull(src.getByteStream());
// set certified accessor methods
boolean origCertified = src.getCertifiedText();
src.setCertifiedText(true);
assertTrue(src.getCertifiedText());
src.setCertifiedText(origCertified); // set back to orig
src.setSystemId(filenameToURL(ASTROCAT));
Document doc = domParser.parse(src);
Element result = doc.getDocumentElement();
assertEquals(result.getTagName(), "stardb");
}
}
/**
* Serializing a SAML2 object into a String
*
* @param xmlObject object that needs to serialized.
* @return serialized object
* @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 = XMLObjectProviderRegistrySupport.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);
}
}
/**
* `
* Serialize XML objects
*
* @param xmlObject : XACML or SAML objects to be serialized
* @return serialized XACML or SAML objects
* @throws EntitlementException
*/
private String marshall(XMLObject xmlObject) throws EntitlementException {
try {
doBootstrap();
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
Element element = marshaller.marshall(xmlObject);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl =
(DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
LSOutput output = impl.createLSOutput();
output.setByteStream(byteArrayOutputStream);
writer.write(element, output);
return byteArrayOutputStream.toString();
} catch (Exception e) {
log.error("Error Serializing the SAML Response");
throw new EntitlementException("Error Serializing the SAML Response", e);
}
}
/**
* `
* Serialize XML objects
*
* @param xmlObject : XACML or SAML objects to be serialized
* @return serialized XACML or SAML objects
* @throws EntitlementException
*/
private String marshall(XMLObject xmlObject) throws EntitlementException {
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 byteArrayOutputStream = new ByteArrayOutputStream();
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl =
(DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
LSOutput output = impl.createLSOutput();
output.setByteStream(byteArrayOutputStream);
writer.write(element, output);
return byteArrayOutputStream.toString();
} catch (Exception e) {
log.error("Error Serializing the SAML Response");
throw new EntitlementException("Error Serializing the SAML Response", e);
}
}
/**
* Saves the process configuration.
*/
private void saveConfiguration(Document docXMLConfig) {
String fileToSaveConf = properties.getSaveRemoteConfig();
if (fileToSaveConf.length() > 0 && docXMLConfig != null) {
log.info("saveConfiguration - saving the process configuration XML in a file " + fileToSaveConf + " due to user request");
File file = new File(fileToSaveConf);
if (file.isDirectory() || !fileToSaveConf.endsWith(".xml")) {
throw new RuntimeException("Path to which to save remote config must end with '.xml'");
}
try {
DOMImplementationLS domImplementation = (DOMImplementationLS) docXMLConfig.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
lsSerializer.writeToURI(docXMLConfig, file.toURI().toURL().toString());
} catch (java.io.IOException ex) {
log.error("saveConfiguration - Could not save the configuration to the file " + fileToSaveConf, ex);
}
}
}
public static String toXml(Document domDoc) throws TransformerException {
DOMImplementation domImplementation = domDoc.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("xml-declaration", Boolean.TRUE))
lsSerializer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE);
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(domDoc, lsOutput);
return stringWriter.toString();
}
}
return toXml((Node) domDoc);
}
public static String format(String xml) {
try {
final InputSource src = new InputSource(new StringReader(xml));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));
//May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
final LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified.
writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted.
return writer.writeToString(document);
} catch (Exception e) {
return xml;
}
}
public static String elementToString(Element el) {
if (el == null)
return "";
Document document = el.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document
.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
return serializer.writeToString(el);
}
/**
* this converts a xml document to a string for writing back to the browser
*
* @param doc
* @return string
*/
public String getStringFromDoc(org.w3c.dom.Document doc) {
DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
lsSerializer.getDomConfig().setParameter("xml-declaration", false);
//lsSerializer.getDomConfig().setParameter("xml-declaration", false);
return lsSerializer.writeToString(doc);
}