Remove XML parsing

pull/214/head
M66B 1 year ago
parent 7456ba958e
commit 8655d3bb7c

@ -470,33 +470,7 @@ public class XCalDocument {
* @throws TransformerException if there's a problem writing to the writer
*/
public void write(Writer writer, Map<String, String> outputProperties) throws TransformerException {
Transformer transformer;
try {
TransformerFactory factory = TransformerFactory.newInstance();
factory.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
transformer = factory.newTransformer();
} catch (TransformerConfigurationException e) {
//should never be thrown because we're not doing anything fancy with the configuration
throw new RuntimeException(e);
} catch (TransformerFactoryConfigurationError e) {
//should never be thrown because we're not doing anything fancy with the configuration
throw new RuntimeException(e);
}
/*
* Using Transformer#setOutputProperties(Properties) doesn't work for
* some reason for setting the number of indentation spaces.
*/
for (Map.Entry<String, String> entry : outputProperties.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
transformer.setOutputProperty(key, value);
}
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
throw new RuntimeException("Removed");
}
@Override

@ -202,25 +202,7 @@ public class XCalReader extends StreamReader {
private volatile boolean finished = false, started = false, closed = false;
public ReadThread() {
setName(getClass().getSimpleName());
//create the transformer
try {
TransformerFactory factory = TransformerFactory.newInstance();
factory.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
XmlUtils.applyXXEProtection(factory);
transformer = factory.newTransformer();
} catch (TransformerConfigurationException e) {
//shouldn't be thrown because it's a simple configuration
throw new RuntimeException(e);
}
//prevent error messages from being printed to stderr
transformer.setErrorListener(new NoOpErrorListener());
result = new SAXResult(new ContentHandlerImpl());
throw new RuntimeException("Removed");
}
@Override

@ -151,25 +151,7 @@ public final class XmlUtils {
}
private static Document toDocument(InputSource in) throws SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setIgnoringComments(true);
applyXXEProtection(factory);
try {
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
} catch (ParserConfigurationException ex) {
throw new SAXException(ex);
}
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
//should never be thrown because we're not doing anything fancy with the configuration
throw new RuntimeException(e);
}
return builder.parse(in);
throw new RuntimeException("Removed");
}
/**
@ -290,27 +272,7 @@ public final class XmlUtils {
* @throws TransformerException if there's a problem writing to the writer
*/
public static void toWriter(Node node, Writer writer, Map<String, String> outputProperties) throws TransformerException {
try {
TransformerFactory factory = TransformerFactory.newInstance();
factory.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
Transformer transformer = factory.newTransformer();
for (Map.Entry<String, String> property : outputProperties.entrySet()) {
try {
transformer.setOutputProperty(property.getKey(), property.getValue());
} catch (IllegalArgumentException e) {
//ignore invalid output properties
}
}
DOMSource source = new DOMSource(node);
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
//no complex configurations
} catch (TransformerFactoryConfigurationError e) {
//no complex configurations
}
throw new RuntimeException("Removed");
}
/**

@ -813,8 +813,6 @@ public class DslJson<TContext> implements UnknownSerializer, TypeLookup {
}
static void registerJavaSpecifics(final DslJson json) {
json.registerReader(Element.class, XmlConverter.Reader);
json.registerWriter(Element.class, XmlConverter.Writer);
}
private final Map<Type, Object> defaults = new ConcurrentHashMap<Type, Object>();

@ -1,220 +0,0 @@
package com.bugsnag.android.repackaged.dslplatform.json;
import androidx.annotation.Nullable;
import org.w3c.dom.*;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.*;
@SuppressWarnings({"rawtypes", "unchecked"}) // suppress pre-existing warnings
public abstract class XmlConverter {
static final JsonReader.ReadObject<Element> Reader = new JsonReader.ReadObject<Element>() {
@Nullable
@Override
public Element read(JsonReader reader) throws IOException {
return reader.wasNull() ? null : deserialize(reader);
}
};
static final JsonWriter.WriteObject<Element> Writer = new JsonWriter.WriteObject<Element>() {
@Override
public void write(JsonWriter writer, @Nullable Element value) {
serializeNullable(value, writer);
}
};
private static final DocumentBuilder documentBuilder;
static {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
try {
dbFactory.setXIncludeAware(false);
dbFactory.setExpandEntityReferences(false);
dbFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
documentBuilder = dbFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
}
public static void serializeNullable(@Nullable final Element value, final JsonWriter sw) {
if (value == null)
sw.writeNull();
else
serialize(value, sw);
}
public static void serialize(final Element value, final JsonWriter sw) {
Document document = value.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
LSOutput lsOutput = domImplLS.createLSOutput();
lsOutput.setEncoding("UTF-8");
StringWriter writer = new StringWriter();
lsOutput.setCharacterStream(writer);
serializer.write(document, lsOutput);
StringConverter.serialize(writer.toString(), sw);
}
public static Element deserialize(final JsonReader reader) throws IOException {
if (reader.last() == '"') {
try {
InputSource source = new InputSource(new StringReader(reader.readString()));
return documentBuilder.parse(source).getDocumentElement();
} catch (SAXException ex) {
throw reader.newParseErrorAt("Invalid XML value", 0, ex);
}
} else {
final Map<String, Object> map = ObjectConverter.deserializeMap(reader);
return mapToXml(map);
}
}
public static Element mapToXml(final Map<String, Object> map) throws IOException {
final Set<String> xmlRootElementNames = map.keySet();
if (xmlRootElementNames.size() > 1) {
throw ParsingException.create("Invalid XML. Expecting root element", true);
}
final String rootName = xmlRootElementNames.iterator().next();
final Document document = createDocument();
final Element rootElement = document.createElement(rootName);
document.appendChild(rootElement);
buildXmlFromHashMap(document, rootElement, map.get(rootName));
return rootElement;
}
private static synchronized Document createDocument() {
try {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
return builder.newDocument();
} catch (ParserConfigurationException e) {
throw new ConfigurationException(e);
}
}
private static final String TEXT_NODE_TAG = "#text";
private static final String COMMENT_NODE_TAG = "#comment";
private static final String CDATA_NODE_TAG = "#cdata-section";
@SuppressWarnings("unchecked")
private static void buildXmlFromHashMap(
final Document doc,
final Element subtreeRootElement,
@Nullable final Object elementContent) {
if (elementContent instanceof HashMap) {
final HashMap<String, Object> elementContentMap = (HashMap<String, Object>) elementContent;
for (final Map.Entry<String, Object> childEntry : elementContentMap.entrySet()) {
final String key = childEntry.getKey();
if (key.startsWith("@")) {
subtreeRootElement.setAttribute(key.substring(1), childEntry.getValue().toString());
} else if (key.startsWith("#")) {
if (key.equals(TEXT_NODE_TAG)) {
if (childEntry.getValue() instanceof List) {
buildTextNodeList(doc, subtreeRootElement, (List<String>) childEntry.getValue());
} else {
final Node textNode = doc.createTextNode(childEntry.getValue().toString());
subtreeRootElement.appendChild(textNode);
}
} else if (key.equals(CDATA_NODE_TAG)) {
if (childEntry.getValue() instanceof List) {
buildCDataList(doc, subtreeRootElement, (List<String>) childEntry.getValue());
} else {
final Node cDataNode = doc.createCDATASection(childEntry.getValue().toString());
subtreeRootElement.appendChild(cDataNode);
}
} else if (key.equals(COMMENT_NODE_TAG)) {
if (childEntry.getValue() instanceof List) {
buildCommentList(doc, subtreeRootElement, (List<String>) childEntry.getValue());
} else {
final Node commentNode = doc.createComment(childEntry.getValue().toString());
subtreeRootElement.appendChild(commentNode);
}
} //else if (key.equals(WHITESPACE_NODE_TAG)
// || key.equals(SIGNIFICANT_WHITESPACE_NODE_TAG)) {
// Ignore
//} else {
/*
* All other nodes whose name starts with a '#' are invalid XML
* nodes, and thus ignored:
*/
//}
} else {
final Element newElement = doc.createElement(key);
subtreeRootElement.appendChild(newElement);
buildXmlFromHashMap(doc, newElement, childEntry.getValue());
}
}
} else if (elementContent instanceof List) {
buildXmlFromJsonArray(doc, subtreeRootElement, (List<Object>) elementContent);
} else {
if (elementContent != null) {
subtreeRootElement.setTextContent(elementContent.toString());
}
}
}
private static void buildTextNodeList(final Document doc, final Node subtreeRoot, final List<String> nodeValues) {
final StringBuilder sb = new StringBuilder();
for (final String nodeValue : nodeValues) {
sb.append(nodeValue);
}
subtreeRoot.appendChild(doc.createTextNode(sb.toString()));
}
private static void buildCDataList(final Document doc, final Node subtreeRoot, final List<String> nodeValues) {
for (final String nodeValue : nodeValues) {
subtreeRoot.appendChild(doc.createCDATASection(nodeValue));
}
}
private static void buildCommentList(final Document doc, final Node subtreeRoot, final List<String> nodeValues) {
for (final String nodeValue : nodeValues) {
subtreeRoot.appendChild(doc.createComment(nodeValue));
}
}
private static void buildXmlFromJsonArray(
final Document doc,
final Node listHeadNode,
final List<Object> elementContentList) {
final Node subtreeRootNode = listHeadNode.getParentNode();
/* The head node (already exists) */
buildXmlFromHashMap(doc, (Element) listHeadNode, elementContentList.get(0));
/* The rest of the list */
for (final Object elementContent : elementContentList.subList(1, elementContentList.size())) {
final Element newElement = doc.createElement(listHeadNode.getNodeName());
subtreeRootNode.appendChild(newElement);
buildXmlFromHashMap(doc, newElement, elementContent);
}
}
@SuppressWarnings("unchecked")
public static ArrayList<Element> deserializeCollection(final JsonReader reader) throws IOException {
return reader.deserializeCollection(Reader);
}
public static void deserializeCollection(final JsonReader reader, final Collection<Element> res) throws IOException {
reader.deserializeCollection(Reader, res);
}
@SuppressWarnings("unchecked")
public static ArrayList<Element> deserializeNullableCollection(final JsonReader reader) throws IOException {
return reader.deserializeNullableCollection(Reader);
}
public static void deserializeNullableCollection(final JsonReader reader, final Collection<Element> res) throws IOException {
reader.deserializeNullableCollection(Reader, res);
}
}

@ -1,124 +0,0 @@
/*
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.mail.handlers;
import java.io.IOException;
import java.io.OutputStream;
import javax.activation.ActivationDataFlavor;
import javax.activation.DataSource;
import javax.mail.internet.ContentType;
import javax.mail.internet.ParseException;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
/**
* DataContentHandler for text/xml.
*
* @author Anil Vijendran
* @author Bill Shannon
*/
public class text_xml extends text_plain {
private static final ActivationDataFlavor[] flavors = {
new ActivationDataFlavor(String.class, "text/xml", "XML String"),
new ActivationDataFlavor(String.class, "application/xml", "XML String"),
new ActivationDataFlavor(StreamSource.class, "text/xml", "XML"),
new ActivationDataFlavor(StreamSource.class, "application/xml", "XML")
};
@Override
protected ActivationDataFlavor[] getDataFlavors() {
return flavors;
}
@Override
protected Object getData(ActivationDataFlavor aFlavor, DataSource ds)
throws IOException {
if (aFlavor.getRepresentationClass() == String.class)
return super.getContent(ds);
else if (aFlavor.getRepresentationClass() == StreamSource.class)
return new StreamSource(ds.getInputStream());
else
return null; // XXX - should never happen
}
/**
*/
@Override
public void writeTo(Object obj, String mimeType, OutputStream os)
throws IOException {
if (!isXmlType(mimeType))
throw new IOException(
"Invalid content type \"" + mimeType + "\" for text/xml DCH");
if (obj instanceof String) {
super.writeTo(obj, mimeType, os);
return;
}
if (!(obj instanceof DataSource || obj instanceof Source)) {
throw new IOException("Invalid Object type = "+obj.getClass()+
". XmlDCH can only convert DataSource or Source to XML.");
}
try {
TransformerFactory factory = TransformerFactory.newInstance();
factory.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
Transformer transformer = factory.newTransformer();
StreamResult result = new StreamResult(os);
if (obj instanceof DataSource) {
// Streaming transform applies only to
// javax.xml.transform.StreamSource
transformer.transform(
new StreamSource(((DataSource)obj).getInputStream()),
result);
} else {
transformer.transform((Source)obj, result);
}
} catch (TransformerException ex) {
IOException ioex = new IOException(
"Unable to run the JAXP transformer on a stream "
+ ex.getMessage());
ioex.initCause(ex);
throw ioex;
} catch (RuntimeException ex) {
IOException ioex = new IOException(
"Unable to run the JAXP transformer on a stream "
+ ex.getMessage());
ioex.initCause(ex);
throw ioex;
}
}
private boolean isXmlType(String type) {
try {
ContentType ct = new ContentType(type);
return ct.getSubType().equals("xml") &&
(ct.getPrimaryType().equals("text") ||
ct.getPrimaryType().equals("application"));
} catch (ParseException ex) {
return false;
} catch (RuntimeException ex) {
return false;
}
}
}

@ -6,7 +6,6 @@
#
text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain
text/html;; x-java-content-handler=com.sun.mail.handlers.text_html
text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml
multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed; x-java-fallback-entry=true
message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822
#

Loading…
Cancel
Save