Skip to content

Commit

Permalink
[JENKINS-41653] added fallback method in case xml is wrong
Browse files Browse the repository at this point in the history
  • Loading branch information
escoem committed Oct 20, 2017
1 parent c60bb65 commit 2f01d2c
Showing 1 changed file with 30 additions and 4 deletions.
Expand Up @@ -3,6 +3,7 @@
import com.cloudbees.plugins.credentials.SecretBytes;
import hudson.util.Secret;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
Expand All @@ -20,6 +21,8 @@
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.xml.sax.helpers.XMLFilterImpl;
import org.xml.sax.helpers.XMLReaderFactory;
Expand Down Expand Up @@ -66,7 +69,8 @@ public void characters(char[] ch, int start, int length) throws SAXException {
if (!"".equals(tagName)) {
String value = new String(ch, start, length).trim();
//if it's a secret, then use a place holder
if (!"".equals(value)) {
// convenience check !"{}".equals(value) because of JENKINS-47500
if (!"".equals(value) && !"{}".equals(value)) {
if ((Secret.decrypt(value)) != null || SecretBytes.isSecretBytes(value)) {
ch = SECRET_MARKER.toCharArray();
start = 0;
Expand All @@ -77,15 +81,37 @@ public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
}
};
Source src = new SAXSource(xr, new InputSource(new StringReader(FileUtils.readFileToString(xmlFile))));
String str = FileUtils.readFileToString(xmlFile);
Source src = new SAXSource(xr, new InputSource(new StringReader(str)));
final ByteArrayOutputStream result = new ByteArrayOutputStream();
Result res = new StreamResult(result);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
//omit xml declaration because of https://bugs.openjdk.java.net/browse/JDK-8035437
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, OUTPUT_ENCODING);
transformer.transform(src, res);

return result.toString("UTF-8");
try {
transformer.transform(src, res);
return result.toString("UTF-8");
} catch (TransformerException e) {
return findSecretFallback(str);
}
}


private static String findSecretFallback(String xml) {
Matcher matcher = Pattern.compile(">\\{(.*)\\}<|>(.*)\\=<").matcher(xml);
while(matcher.find()) {
String secret = matcher.group();
if(secret.length() > 1)
secret = secret.substring(1,secret.length()-1);
if ((Secret.decrypt(secret)) != null || SecretBytes.isSecretBytes(secret)) {
xml = StringUtils.replace(xml, secret, SECRET_MARKER);
}
}

return xml;
}


}

0 comments on commit 2f01d2c

Please sign in to comment.