-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDefaultXPathStreamProcessor.java
More file actions
224 lines (188 loc) · 7.4 KB
/
DefaultXPathStreamProcessor.java
File metadata and controls
224 lines (188 loc) · 7.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package io.codemodder;
import io.github.pixee.security.XMLInputFactorySecurity;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.xml.stream.Location;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.ElementHandler;
import org.dom4j.QName;
import org.dom4j.io.SAXContentHandler;
import org.dom4j.io.SAXReader;
import org.dom4j.tree.DefaultElement;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
final class DefaultXPathStreamProcessor implements XPathStreamProcessor {
@Override
public Optional<XPathStreamProcessChange> process(
final Path path, final String xpathExpression, final XPathStreamEventHandler handler)
throws SAXException, IOException, XMLStreamException {
SAXReader reader = new PositionCapturingReader();
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
reader.setDocumentFactory(new LocatorAwareDocumentFactory());
String xml = Files.readString(path);
Document doc;
try {
doc = reader.read(new StringReader(xml));
} catch (DocumentException e) {
throw new IOException("Problem reading document", e);
}
List<Position> httpMethodPositions =
DocumentHelper.selectNodes(xpathExpression, doc).stream()
.map(node -> (LocationAwareElement) node)
.map(element -> new Position(element.getLine(), element.getColumn()))
.toList();
if (httpMethodPositions.isEmpty()) {
return Optional.empty();
}
XMLInputFactory inputFactory =
XMLInputFactorySecurity.hardenFactory(XMLInputFactory.newFactory());
XMLEventReader xmlReader = inputFactory.createXMLEventReader(Files.newInputStream(path));
XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
StringWriter sw = new StringWriter();
XMLEventWriter xmlWriter = outputFactory.createXMLEventWriter(sw);
while (xmlReader.hasNext()) {
final XMLEvent currentEvent = xmlReader.nextEvent();
// get the position of the last character of the event, that is, the start of the next one
if (xmlReader.hasNext()) {
Location location = xmlReader.peek().getLocation();
if (doesPositionMatch(httpMethodPositions, location)) {
handler.handle(xmlReader, xmlWriter, currentEvent);
} else {
xmlWriter.add(currentEvent);
}
} else {
xmlWriter.add(currentEvent);
}
}
String transformedXml = sw.toString();
if (transformedXml.startsWith("<?xml") && !xml.startsWith("<?xml")) {
transformedXml = transformedXml.substring(transformedXml.indexOf('>') + 1);
}
// Fix prolog string, if needed
if (xml.stripLeading().startsWith("<?xml")) {
var xmlHead = xml.substring(0, xml.indexOf('<', xml.indexOf('<') + 1));
var transformedXmlTail =
transformedXml.substring(transformedXml.indexOf('<', transformedXml.indexOf('<') + 1));
transformedXml = xmlHead + transformedXmlTail;
}
// remove the empty leftover lines affected by our changes if there are any
Set<Integer> linesAffected =
httpMethodPositions.stream().map(pos -> pos.line()).collect(Collectors.toUnmodifiableSet());
List<String> lines = transformedXml.lines().toList();
List<String> updatedLines = new ArrayList<>(lines.size() - linesAffected.size());
for (int i = 1; i <= lines.size(); i++) {
String actualLine = lines.get(i - 1);
if (linesAffected.contains(i) && actualLine.isBlank()) {
continue;
}
updatedLines.add(actualLine);
}
transformedXml = String.join("\n", updatedLines);
// if the old file ended with a blank line, make sure to provide one
if (xml.endsWith("\n") && !transformedXml.endsWith("\n")) {
transformedXml += "\n";
}
Path tmpFile = Files.createTempFile("codemodder", ".xml");
Files.writeString(tmpFile, transformedXml);
XPathStreamProcessChange.Default change =
new XPathStreamProcessChange.Default(linesAffected, tmpFile);
return Optional.of(change);
}
private boolean doesPositionMatch(final List<Position> positions, final Location location) {
return positions.stream()
.anyMatch(
position ->
position.column() == location.getColumnNumber()
&& position.line() == location.getLineNumber());
}
private static class PositionCapturingReader extends SAXReader {
@Override
protected SAXContentHandler createContentHandler(XMLReader reader) {
return new PositionCapturingContentHandler(getDocumentFactory(), getDispatchHandler());
}
@Override
public void setDocumentFactory(DocumentFactory documentFactory) {
super.setDocumentFactory(documentFactory);
}
}
private static class PositionCapturingContentHandler extends SAXContentHandler {
private Locator locator;
private final DocumentFactory documentFactory;
public PositionCapturingContentHandler(
DocumentFactory documentFactory, ElementHandler elementHandler) {
super(documentFactory, elementHandler);
this.documentFactory = documentFactory;
}
@Override
public void setDocumentLocator(Locator documentLocator) {
super.setDocumentLocator(documentLocator);
this.locator = documentLocator;
if (documentFactory instanceof LocatorAwareDocumentFactory) {
((LocatorAwareDocumentFactory) documentFactory).setLocator(documentLocator);
}
}
public Locator getLocator() {
return locator;
}
}
private static class LocatorAwareDocumentFactory extends DocumentFactory {
private Locator locator;
public LocatorAwareDocumentFactory() {
super();
}
public void setLocator(final Locator locator) {
this.locator = locator;
}
@Override
public Element createElement(final QName qname) {
LocationAwareElement element = new LocationAwareElement(qname);
if (locator != null) {
element.setLine(locator.getLineNumber());
element.setColumn(locator.getColumnNumber());
}
return element;
}
}
/** An Element that is aware of its location in the source document. */
private static class LocationAwareElement extends DefaultElement {
private int lineNumber = -1;
private int column = -1;
public LocationAwareElement(final QName qname) {
super(qname);
}
public int getLine() {
return lineNumber;
}
int getColumn() {
return column;
}
public void setLine(int lineNumber) {
this.lineNumber = lineNumber;
}
public void setColumn(int column) {
this.column = column;
}
}
}